【发布时间】:2014-09-22 11:01:41
【问题描述】:
我需要获取更新的设备方向,但我必须将我的活动修复为肖像(我在布局 xml 文件中所做的),这使我无法使用它:
int rotation = getWindowManager().getDefaultDisplay().getRotation();
因为它总是给我纵向旋转,
所以,我正在尝试依靠传感器。我发现Sensor.TYPE_ORIENTATION 已被弃用,所以我使用Sensor.TYPE_ACCELEROMETER 和Sensor.TYPE_MAGNETIC_FIELD 的组合,这里是事件监听器:
SensorEventListener sensorEventListener = 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 orientationData[] = new float[3];
SensorManager.getOrientation(R, orientationData);
azimuth = orientationData[0];
pitch = orientationData[1];
roll = orientationData[2];
// now how to use previous 3 values to calculate orientation
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
};
现在问题是,如何使用 3 个值 azimuth、pitch 和 roll 来检测当前设备方向作为其中之一:
- 横向(旋转 0)
- 纵向(旋转 90)
- 反向横向(旋转 180)
- 反转纵向(旋转 270)
【问题讨论】:
-
@HoanNguyen 看起来不错,但在这种情况下,
getRotationMatrix的参数是什么? -
设备方向与方位角、俯仰角和滚动角无关。如果您只想查找设备方向,则无需查找旋转矩阵,因此无需调用 getRotationMatrix。否则你仍然需要做我发布的计算。
-
但是您之前发布的答案缺少一些“对于平放的情况,您必须使用指南针查看设备从起始位置旋转了多少。”
-
OK,在平放的情况下,你必须传入重力和磁场的参数,并使用方位角来查看设备从原始位置旋转了多少。但是,这不会告诉您设备的方向,因为方向取决于用户握持设备的方式。它只告诉您设备从用户持有设备的原始位置旋转了多少。
标签: android rotation android-sensors