我的活动锁定在LANDSCAPE模式。但我仍然需要了解设备的方向。因此,我选择使用传感器。我有以下代码:
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_NORMAL);
...
@Override
public void onSensorChanged(SensorEvent event) {
float[] values = event.values;
// Movement
float azimuth = values[0];
float pitch = values[1];
float roll = values[2];
if ((-110 <= pitch && pitch <= -70) || (70 <= pitch && pitch <= 110)) {
//PORTRAIT MODE
portraitPitch = true;
landscapePitch = false;
Log.d(TAG, "portrait mode: pitch = " + pitch);
} else if ((-20 <= pitch && pitch <= 20) || (-200 <= pitch && pitch <= -160) || (160 <= pitch && pitch <= 200)) {
//LANDSCAPE MODE
portraitPitch = false;
landscapePitch = true;
Log.d(TAG, "landscape mode : pitch = " + pitch);
}
if ((-20 <= roll && roll <= 20)) {
//PORTRAIT MODE
portraitRoll = true;
landscapePitch = false;
Log.d(TAG, "portrait mode: roll = " + roll);
} else if ((-110 <= roll && roll <= -70) || (70 <= roll && roll <= 110)) {
//LANDSCAPE MODE
portraitRoll = false;
landscapePitch = true;
Log.d(TAG, "landscape mode : roll = " + roll);
}
if (portraitPitch && portraitRoll && !portrait) {
portrait = true;
landscape = false;
rotateIconsToPortraitMode();
Log.d(TAG, "portrait mode for icons: pitch = " + pitch + ", roll = " + roll);
}
if (landscapePitch && landscapeRoll && !landscape) {
landscape = true;
portrait = false;
rotateIconsToLandscapeMode();
Log.d(TAG, "landscape mode for icons: pitch = " + pitch + ", roll = " + roll);
}
}
我的代码不能可靠地工作,事实上,otateIconsToLandscapeMode()
从未被调用。
如何利用有关方位角
、俯仰角
和滚动角
的信息来确定设备的纵向或横向方向?我希望我的问题足够具体,以便得到具体的答案。谢谢。
configChanges: orientation
,并实现onConfigurationChanged
,然后也许你可以获取newConfig.orientation
。 - undefined