我正在构建一个 Android 应用程序,它将设备的罗盘度数记录到一个文件中。获得这个学位有两种方法:
方法一:
SensorManager mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
Sensor orientationSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
mSensorManager.registerListener(this, orientationSensor, SensorManager.SENSOR_DELAY_NORMAL);
public void onSensorChanged(SensorEvent event) {
float azimuthInDegrees = event.values[0]
}
方法二:
SensorManager mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
Sensor accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
Sensor magnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_NORMAL);
float[] mGravity;
float[] mGeomagnetic;
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);
float azimuthInDegress = ((float) Math.toDegrees(orientation[0]) + 360) % 360;
}
}
}
我通过将我的设备放在北方向(大约 360 度)来尝试这两种方法:
方法 1返回完美的结果,但不幸的是,此方法已被弃用:
- 359.6567
- 359.5034
- 359.859
- 359.76212
- 359.8878
- 359.87048
- 359.8356
- 359.80356
- 359.81192
- 359.7671
- 359.84668
- 359.88528
方法 2也返回良好的结果,但有时(随机)它返回不正确的度数:
- 359.91495
- 359.83652
- 263.67697
- 359.67993
- 359.70038
- 359.688
- 359.71155
- 359.70276
- 359.6984
- 359.6429
- 270.6323
- 359.62302
- 359.49954
- 359.44757
- 359.47803
- 359.4947
- 359.39572
如您所见,使用第二种方法会随机返回一些不正确的度数。该设备已校准,我认为问题在于第二种方法,因为第一种方法返回完美的结果。你们能帮帮我吗?