锁定Android屏幕方向到景观

时间:2012-09-04 15:05:27

标签: android screen-orientation

我正在开发一个Android应用程序,其中一个功能是将屏幕方向锁定到Landscape,我想将此方向更改应用于手机中的所有Android应用程序。我正在使用此代码

private void lockScreenOrientation() {
if (!mScreenOrientationLocked) {
    final int orientation = getResources().getConfiguration().orientation;
    final int rotation = getWindowManager().getDefaultDisplay().getOrientation();
    if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90) {
        if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }
    else if (rotation == Surface.ROTATION_180 || rotation == Surface.ROTATION_270) {
        if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
        }
        else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
        }
    }

    mScreenOrientationLocked = true;
}
}

private void unlockScreenOrientation() {
 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
 mScreenOrientationLocked = false;
}

但这是临时更改,并未对所有应用程序生效,是否有人知道将锁定方向应用于所有应用程序的方法?谢谢

1 个答案:

答案 0 :(得分:4)

您链接的应用程序通过修改与旋转关联的全局系统设置值来执行此操作。查看Settings.System类,了解应用程序可用的常量。具体而言,ACCELEROMETER_ROTATIONUSER_ROTATION值可能会引起关注。

您还需要在清单中声明android.permission.WRITE_SETTINGSandroid.permission.WRITE_SECURE_SETTINGS权限。

相关问题