Android Orientation Changes edit

Lock Screens rotation programmatically

It is very common that during development, one may find very useful to lock/unlock the device screen during specific parts of the code.

For instance, while showing a Dialog with information, the developer might want to lock the screen’s rotation to prevent the dialog from being dismissed and the current activity from being rebuilt to unlock it again when the dialog is dismissed.

Even though we can achieve rotation locking from the manifest by doing :

<activity
    android:name=".TheActivity"
    android:screenOrientation="portrait"
    android:label="@string/app_name" >
</activity>

One can do it programmatically as well by doing the following :

public void lockDeviceRotation(boolean value) {
    if (value) {
        int currentOrientation = getResources().getConfiguration().orientation;
        if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
        }
    } else {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_USER);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
        }
    }
}

And then calling the following, to respectively lock and unlock the device rotation

lockDeviceRotation(true)

and

lockDeviceRotation(false)

Table Of Contents
39 ACRA
64 Menu
112 Loader
118 Orientation Changes
119 Xposed
132 Colors
135 Fresco
140 AdMob
147 Button
156 Vk SDK
170 XMPP
176 OpenCV
200 FileIO
203 Moshi
217 Paint
231 AIDL
241 JCodec
243 Okio
255 Looper
  ↑ ↓ to navigate     ↵ to select     Esc to close