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:
Note that this question is not about changes to the device orientation. It's only about the screen orientation/rotation.
Configuration
changes via ACTION_CONFIGURATION_CHANGED
. This only covers changes between portrait and landscape, so 180° changes don't trigger this.I'm developing a custom screen orientation management app.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With