我正在为Android制作一个指南针应用程序,我已经设法通过使用陀螺仪,加速度计和磁力计捕获方位角(请参阅here我使用的教程)。不幸的是,指南针只在设备平行放置在地面上时才起作用(即平放在桌子/手掌上等)。每当我将设备倾斜到一个完全直立的位置(屏幕朝向我)时,指南针只会给出错误的读数。我假设这是因为当设备的方向本身发生变化时轴会发生变化。我该如何防止这种情况发生?我希望指南针在这两个位置同时工作:平行于地面和完全直立的位置。我该怎么做呢?如果有人能给我一个正确的方向,那将是非常有帮助的。
感谢您的帮助! :d
答案 0 :(得分:0)
在SensorFusionActivity中添加mDisplay变量,如下所示:
private Display mDisplay = null;
然后,在onCreate方法中添加以下代码:
mDisplay = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
最后,用这种方式修改calculateAccMagOrientation:
// calculates orientation angles from accelerometer and magnetometer output
public void calculateAccMagOrientation() {
if(SensorManager.getRotationMatrix(rotationMatrix, null, accel, magnet)) {
int rotation = mDisplay.getRotation();
if(rotation == Surface.ROTATION_0)
SensorManager.remapCoordinateSystem(rotationMatrix, SensorManager.AXIS_MINUS_Y, SensorManager.AXIS_X, rotationMatrix);
else if(rotation == Surface.ROTATION_180)
SensorManager.remapCoordinateSystem(rotationMatrix, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, rotationMatrix);
else if(rotation == Surface.ROTATION_270)
SensorManager.remapCoordinateSystem(rotationMatrix, SensorManager.AXIS_MINUS_X, SensorManager.AXIS_MINUS_Y, rotationMatrix);
SensorManager.getOrientation(rotationMatrix, accMagOrientation);
}
}