Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I globally detect when the screen rotation changes?

Question

In an Android service, I want to detect whenever the screen rotation changes. By rotation, I don't just mean portrait versus landscape; I mean any change to the screen rotation. Examples of such changes are changes to:

  • Portrait
  • Reverse portrait
  • Landscape
  • Reverse landscape

Note that this question is not about changes to the device orientation. It's only about the screen orientation/rotation.

What I've Tried

  • Listening for Configuration changes via ACTION_CONFIGURATION_CHANGED. This only covers changes between portrait and landscape, so 180° changes don't trigger this.

Why I'm Doing This

I'm developing a custom screen orientation management app.

like image 250
Sam Avatar asked May 20 '15 12:05

Sam


1 Answers

The approved answer will work, but if you want a higher resolution of detection (or support further back to API 3), try OrientationEventListener, which can report the orientation of the phone in degrees.

mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);

OrientationEventListener orientationEventListener = new OrientationEventListener(this,
        SensorManager.SENSOR_DELAY_NORMAL) {
    @Override
    public void onOrientationChanged(int orientation) {
        Display display = mWindowManager.getDefaultDisplay();
        int rotation = display.getRotation();
        if(rotation != mLastRotation){
             //rotation changed
             if (rotation == Surface.ROTATION_90){} // check rotations here
             if (rotation == Surface.ROTATION_270){} //
        }
        mLastRotation = rotation;
    }
};

if (orientationEventListener.canDetectOrientation()) {
    orientationEventListener.enable();
}
like image 162
Andrew Avatar answered Sep 29 '22 14:09

Andrew