我将在我的应用程序中使用加速计传感器来读取手机方向数据。大多数时候我可以读取数据,但有时加速度计不起作用。
当加速计失败时,Logcat会产生以下消息:
W/SensorManager: ACCELEROMETER Sensor data was zero
以下是我的代码:
在onCreate()中:
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
在onResume()中:
sensorManager.registerListener(sensorListener, accelerometer, SensorManager.SENSOR_DELAY_FASTEST);
sensorManager.registerListener(sensorListener, magnetometer, SensorManager.SENSOR_DELAY_FASTEST);
在onPause()中:
sensorManager.unregisterListener(sensorListener);
监听器:
private SensorEventListener sensorListener = new SensorEventListener() {
float[] mGravity;
float[] mGeomagnetic;
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
mGravity = event.values;
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
mGeomagnetic = event.values;
if (mGravity != null && mGeomagnetic != null) {
float R[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic);
if (success) {
float orientation[] = new float[3];
SensorManager.getOrientation(R, orientation);
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};