是否可以在方法内获取 Android 加速度计值onCreate
?我想要它,以便在阅读后进行一些初始化。到目前为止,我已经注册了一个传感器侦听器,以便在它们通过onSensorChanged
回调更改时获取这些值。我有 3 个浮点属性(lastx、lasty和lastz)初始化为 -1,以便在更改时将加速度计值存储在那里。在onCreate
方法中,注册我的传感器侦听器后,我试图检查这些值,但它们总是等于-1。有没有办法在方法中获取这些值onCreate
?
这是我的代码:
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
TextView textView;
StringBuilder builder = new StringBuilder();
float lastx = -1;
float lasty = -1;
float lastz = -1;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
textView = new TextView(this);
SensorManager manager = (SensorManager)
getSystemService(Context.SENSOR_SERVICE);
Sensor accelerometer = manager.getDefaultSensor(
Sensor.TYPE_ACCELEROMETER);
if(!manager.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_GAME)){
Log.d("ERROR: ", "NO accelerometer found!");
}
setContentView(textView);
builder.setLength(0);
builder.append(
"X " + this.lastx + "\nY " + this.lasty + "\nZ " + this.lasty);
textView.setText(builder.toString());
Log.d(" * accelerometer values:",
"X: " + this.lastx+", Y: " + this.lasty + ", Z: " + this.lastz);
}
public void onAccuracyChanged(Sensor sensor,int accuracy){
}
public void onSensorChanged(SensorEvent event){
// check sensor type
if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){
// assign directions
float x=event.values[0];
float y=event.values[1];
float z=event.values[2];
this.lastx = x;
this.lasty = y;
this.lastz = z;
// builder.setLength(0);
// builder.append("X " + x + "\nY " + y + "\nZ " + z);
// textView.setText(builder.toString());
}
}
}