我需要获得更新的设备方向,但我必须将我的活动修复为Portrait(我在布局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)