Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect screen rotation

I have an activity that is showing a compass, and I need to know the orientation of the screen to properly rotate the needle. I need to distinguish between 90° and 270° degree rotation to properly handle this.

When I rotate the screen (on my Nexus S at least) the activity's onCreate gets called, e.g. when I rotate from portrait to landscape mode. When I rotate from one landscape mode to the other with the top edge raised, onCreate() gets called twice (once for portrait orientation and once for the target landscape mode).

However, when I rotate with the bottom edge up, the screen rotates 180° and onCreate is not getting called. Is there an event that gets fired in this case?

like image 314
Michael Avatar asked Jan 30 '11 15:01

Michael


People also ask

How can I tell if my screen is rotating?

If the screen rotation is already on try turning it off and then on again. To check this setting, you can swipe down from the top of the display. If it's not there, try going to Settings > Display > Screen rotation.

How do I know my Android phone is rotating?

onConfigurationChanged(newConfig); int orientation = newConfig. orientation; if (orientation == Configuration. ORIENTATION_PORTRAIT) Log. d("tag", "Portrait"); else if (orientation == Configuration.


2 Answers

You are correct that at a 180 degree rotation you will not get restarted or get a configuration change, because the configuration has not actually changed. (It is still in landscape or portrait, and everything else is the same.)

However if you are showing a compass, that must mean you are updating it from sensor events. Thus you can just call Display.getRotation() each time you get a sensor update to get the current rotation of the screen. In fact that you need is rotation of interpreting sensor events (or actually how your drawing of them will be modified when it gets to the screen), not just the orientation.

I found a relevant blog post that is well worth reading.

Be sure to read the SDK documentation.

Also check out the discussion about using Display.getRotation() to correctly remap sensor coordinates.

like image 195
hackbod Avatar answered Sep 21 '22 19:09

hackbod


The helper class OrientationEventListener makes it very easy to get call backs on rotation. I would suggest you give it a try.

like image 41
monchote Avatar answered Sep 20 '22 19:09

monchote