我有一个应用程序可以接收推送通知、检测当前设备方向(纵向/右侧横向/左侧横向)并拍照。
方向用于为 Camera.Parameters
设置旋转。
我正在使用 SensorManager.getRotationMatrix()
来计算方向,但它需要来自地磁传感器的值。
Lenovo S90-A
没有指南针,所以我似乎无法获得这些值。
我尝试使用这段代码:
int rotation = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay().getRotation();
来 self 的服务
,但它仅在设备开启时有效。
但是,如果设备正在休眠并且我收到推送通知,则此方法始终返回 Surface.ROTATION_0
。
设备将固定在墙上,不应移动。
那么,有没有一种方法可以在没有指南针的情况下检测当前设备的方向?
最佳答案
这answer真的很有帮助。实际上,如果您的设备的方向是平的(例如,它位于 table 上),您不能只依赖加速度计。
我最终采用了这种用于没有指南针的设备的方法。
对于带罗盘的设备,我使用 SensorManager.getRotationMatrix()
和 SensorManager.getOrientation()
。
/**
* calculates rotation only from accelerometer values
* @param g - accelerometer event values
* @return
*/
private int getRotationFromAccelerometerOnly(float[] g) {
double normOfG = Math.sqrt(g[0] * g[0] + g[1] * g[1] + g[2] * g[2]);
// Normalize the accelerometer vector
g[0] = (float) (g[0] / normOfG);
g[1] = (float) (g[1] / normOfG);
g[2] = (float) (g[2] / normOfG);
int inclination = (int) Math.round(Math.toDegrees(Math.acos(g[2])));
int rotation;
if (inclination < 25 || inclination > 155) {
// device is flat, return 0
rotation = 0;
} else {
// device is not flat
rotation = (int) Math.round(Math.toDegrees(Math.atan2(g[0], g[1])));
}
return rotation;
}
关于android - 在没有指南针的设备上从服务中获取方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33101488/