Search code examples
androidscreen-rotation

Android landscape screen 180° rotation


I need to know when my Android device screen is rotated from one landscape to another (rotation_90 to rotation_270). In my Android service, I reimplemented onConfigurationChanged(Configuration newConfig) to be aware of the rotation of the device. But this method is only called by the system if the device is rotated from ORIENTATION_PORTRAIT to ORIENTATION_LANDSCAPE, and not if it is rotated from ORIENTATION_LANDSCAPE (90°) to the other ORIENTATION_LANDSCAPE (270°) !!

How can I be called in this case? Thanks.


Solution

  • You can enable an OrientationEventListener to your activity.

    OrientationEventListener mOrientationListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL) {
    
            @Override
            public void onOrientationChanged(int orientation) {
                Log.v(TAG, "Orientation changed to " + orientation);
    
                if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) {
                    return;
                }
    
                int degrees = -1;
                if (orientation < 45 || orientation > 315) {
                    Log.i(TAG, "Portrait");
                } else if (orientation < 135) {
                    degrees = 90;
                    Log.i(TAG, "Landscape");    // This can be reverse landscape
                } else if (orientation < 225) {
                    degrees = 180;
                    Log.i(TAG, "Reverse Portrait");
                } else {
                    degrees = 270;
                    Log.i(TAG, "Reverse Landscape"); // This can be landscape
                }
            }
        };
    
        if (mOrientationListener.canDetectOrientation() == true) {
            Log.v(TAG, "Can detect orientation");
            mOrientationListener.enable();
        } else {
            Log.v(TAG, "Cannot detect orientation");
            mOrientationListener.disable();
        }