我想计算指南针的方向,所以我使用以下代码:
SensorManager mManager = (SensorManager)mContext.getSystemService(Context.SENSOR_SERVICE);
Sensor accelerometer = mManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
Sensor magnetometer = mManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
mManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_NORMAL);
private float mR[] = new float[9];
private float mI[] = new float[9];
float mOrientation[] = new float[3];
....
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) {
boolean success = SensorManager.getRotationMatrix(mR, mI, mGravity, mGeomagnetic);
if (success) {
SensorManager.getOrientation(mR, mOrientation);
int azimut = (int) (mOrientation[0]*180/3.14159f); // This is the data
}
}
}
通常工作正常。当磁场干扰时它不起作用 - 例如在我的汽车收音机下。在那种情况下 - 我得到一个错误的不断读数。
如何检测磁干扰?