Android – How to Lock screen orientation when displaying reverse landscape in android

androidscreen-orientation

im trying to Lock screen orientation in android application.I used following code to lock screen orientation when specific button click fire.

// Inside button click

Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
 if (display.getOrientation() == 1) {
                   setRequestedOrientation(0);
 } else if (display.getOrientation() == 0) {
                   setRequestedOrientation(1);
 } else if (display.getOrientation() == 3) {
                   setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
 }

Above code working for both landscape and portrait screen orientations but its not working for reverse landscape mode.In that case always my activity change it's orientation to default landscape mode.Also i notice,when device in reverse landscape mode , display.getOrientation() always return 3.
How can i find solution for this problem?

Best Answer

I've been dealing with the same problem using API 8. Looks like while in reserseLandscape mode, if you call

getResources().getConfiguration().orientation 

Android will return 2 (SCREEN_ORIENTATION_USER), which won't lock the orientation at all. In fact the constant SCREEN_ORIENTATION_REVERSE_LANDSCAPE is not even defined for the ActivityInfo class, even though the value actually exists. For my app I ended up creating this method:

public void lockScreenOrientation() {
    switch (((WindowManager) getSystemService(WINDOW_SERVICE))
        .getDefaultDisplay().getRotation()) {
    case Surface.ROTATION_90: 
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); 
        break;
    case Surface.ROTATION_180: 
        setRequestedOrientation(9/* reversePortait */); 
        break;          
    case Surface.ROTATION_270: 
        setRequestedOrientation(8/* reverseLandscape */); 
        break;
    default : 
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 
    }
}

I call this method whenever I need to lock the orientation, and then I can simply release it calling

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);

Hope it helps.