How do I detect screen rotation

ぃ、小莉子 提交于 2019-11-27 05:02:22
hackbod

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.

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

Just take a look at the SensorManager Documentation, there you can get the best examples and explanations of how to use the accelerometer to get the most precise informations. Instead of making the things just by detecting the phone orientation, with that API you can get the exactly rotation, just like used by racing games like Asphalt and Need For Speed.

As Monchote said, in order to make your needle rotate as expected on the compass, it's better to lock your UI to portrait or landscape, and change your needle angle according to the device rotation angle, which can be gained easily from OrientationListener.

In this way, no matter the auto rotation feature is opened or not by user, you can always get rotation angle change notification. Here's a good example for your reference.

Have a look at the OnConfigurationChanged method to track down the orientation change and re-arrange your UI as needed.

See some sample code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!