Search code examples
androidandroid-sensorsandroid-orientation

SCREEN_ORIENTATION_LANDSCAPE upside down - Why?


I am using the following code to set orientation locking per user preference:

 private void doLock(boolean locked) {
     if (locked) {
       int o = getResources().getConfiguration().orientation;
       if (o == Configuration.ORIENTATION_LANDSCAPE)
         setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);       
       else if (o == Configuration.ORIENTATION_PORTRAIT)
         setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);       
     } 
     else {
       setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
     }
 }

It works, except for the case in which I am in unlocked mode (SCREEN_ORIENTATION_SENSOR) with the screen showing LANDSCAPE correctly (!), then invoke doLock(true) and...

instead of the screen locking to LANDSCAPE in its current (correct) landscape view, it locks to an upside down landscape view. i.e. same exact but flip vertically (y becomes -y).

Why is that and how do I approach this problem in order to fix it?

My initial inquiry reveals that there are quite a few possibilities other than the common two (portrait, landscape), including reverseLandscape, but my hunch tells me that this problem may be device-dependent and so by using it I might be fixing the problem only for my phone but not for all other devices.

Is there a way to force correct landscape orientation (when switched from sensor) in all devices?

To make this clearer and easier to reproduce, here are the steps that exhibit the problem:

  1. Start with phone rotated to the right (clockwise), in unlocked mode (SCREEN_ORIENTATION_SENSOR) with the screen showing LANDSCAPE correctly (!),
  2. Then invoke doLock(true)
  3. Instead of the screen locking to LANDSCAPE in its current (correct) landscape view, it locks to an upside down landscape view. i.e. same exact but flip vertically (y becomes -y).

Solution

  • What you are describing is not a bug but rather the expected behavior from Android 2.2 or lower.

    @forgivegod provided a theoretically correct approach, except that for Android 2.2 or lower the screenOrientation.reverseLandscape and screenOrientation.reversePortrait values are not recognized, even if faked (as @forgivegod's code does).

    I bet you are seeing this problem when you rotate the phone clockwise (rotation=3) but not counter-clockwise (rotation=1).

    Try with Android 2.3 or higher and see what happens.