Android Orientation Changes suggest change

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)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents