以编程方式启用和禁用自动旋转?

25

有很多很酷的小部件可以让你在手机上启用和禁用自动旋转功能。禁用后,所有应用程序上的自动旋转功能都会关闭。

有什么想法是他们如何实现的吗?

4个回答

50

这应该能为你解决问题:

    import android.provider.Settings;
    public static void setAutoOrientationEnabled(Context context, boolean enabled)
    {
          Settings.System.putInt( context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, enabled ? 1 : 0);
    }

在AndroidManifest.xml中添加权限。

<uses-permission android:name="android.permission.WRITE_SETTINGS" />

你可以在这里找到文档。


2
这似乎可以工作,但它会锁定方向为横屏,即使我在竖屏模式下。我正在Honeycomb平板上测试,所以我不确定是否有区别... 这是预期的行为吗? - christoff
能否仅通过配置完成,而无需权限?我正在尝试寻找这个问题的答案:https://stackoverflow.com/questions/44196296/application-enables-orientation-change-button-is-status-bar。 - Lyubimov Roman

10

始终使用用户指定的屏幕方向,这将应用用户选择的任何方向,并且如果禁用,则不会旋转屏幕。

activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);

最佳答案!谢谢 - ΩlostA

3

这是我为这个问题实现的解决方案。我必须实现一个按钮,它具有与设置菜单中的锁定按钮相同的功能。

您可以使用setRotationScreenFromSettings来解决您的问题。

public static boolean getRotationScreenFromSettingsIsEnabled(Context context)
{

    int result = 0;
    try
    {
        result = Settings.System.getInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION);
    }
    catch (Settings.SettingNotFoundException e)
    {
        e.printStackTrace();
    }

    return result == 1;
}



public static void setRotationScreenFromSettings(Context context, boolean enabled)
{
    try
    {
        if (Settings.System.getInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION) == 1)
        {
            Display defaultDisplay = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
            Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, defaultDisplay.getRotation());
            Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
        }
        else
        {
            Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 1);
        }

        Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, enabled ? 1 : 0);

    }
    catch (Settings.SettingNotFoundException e)
    {
        e.printStackTrace();
    }
}

 private void regirsterLockScreenOrientationChangedListner()
{
    ContentObserver rotationObserver = new ContentObserver(new Handler())
    {
        @Override
        public void onChange(boolean selfChange)
        {
            refreshLockScreenOrientationBtn();
        }
    };

    context.getContentResolver().registerContentObserver(Settings.System.getUriFor(Settings.System.ACCELEROMETER_ROTATION),
            true, rotationObserver);
}`

在 AndroidManifest.xml 中添加权限。
<uses-permission android:name="android.permission.WRITE_SETTINGS" />

2
您需要在onCreate()函数中使用以下代码来修复它。 已解决...
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接