基本思路:我想同时监控陀螺仪和加速度计。
private SensorManager mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
private Sensor mAccSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
private Sensor mGyroSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mGyroSensor, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mAccSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
mGyroValues = event.values.clone();
float x = mGyroValues[0];
float y = mGyroValues[1];
float z = mGyroValues[2];
if (Math.abs(x) > 0.2 || Math.abs(y) > 0.2 || Math.abs(z) > 0.2) {
deviceStatus.setText("Your device IS moving");
} else {
deviceStatus.setText("Your device IS NOT moving");
}
} else if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
mAccValues = event.values.clone();
float x = mAccValues[0];
float y = mAccValues[1];
float z = mAccValues[2];
mAccelLast = mAccelCurrent;
mAccelCurrent = FloatMath.sqrt(x * x + y * y + z * z);
float delta = mAccelCurrent - mAccelLast;
mAccel = mAccel * 1.0f + delta;
if (mAccel > 0.2) {
deviceStatus.setText("Your device IS moving");
} else {
deviceStatus.setText("Your device IS NOT moving");
}
}
理论上,这应该使deviceStatus
(只是一个TextView)在我拿起电话的时候(通过加速度计数据)有文字"Your device IS moving"
或任何时候我旋转它时放下它表(通过陀螺仪数据)。
但是,当我在桌面上旋转它时,它似乎没有改变文本。我正在将各种传感器数据输出到其他TextView,以便我可以确认两个传感器都在发送数据。在我看来,只有我的加速度计代码才能正确执行。关于我做错了什么想法?