簡體   English   中英

以編程方式啟用和禁用自動旋轉?

[英]Enable and disable auto rotate programmatically?

有很多很酷的小部件,它們可以在您的手機上啟用和禁用自動旋轉。 禁用它會在手機上的所有應用程序中將其關閉。

任何想法他們如何完成它?

這應該為您解決問題:

    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" />

您可以在這里找到文檔

始終使用用戶指定的屏幕方向,這將應用用戶選擇的任何方向,並且在禁用屏幕時不會旋轉屏幕。

activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);

這是我對這個問題的重視。 我必須實現一個按鈕,其功能與設置菜單中的lockbutton相同。

您可以使用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" />

您必須使用onCreate()函數中的以下代碼對其進行修復。 工作中...

setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM