Android compass example

若如初见. 提交于 2019-11-27 12:31:02

问题


I'm searching for a compass example for Android. All I need to do is to get the correct bearing (in portrait & landscape mode).

I already found several samples, some use only Sensor.TYPE_ORIENTATION, some use a combination of Sensor.TYPE_ACCELEROMETER & Sensor.TYPE_MAGNETIC_FIELD.

Which is the correct & common way to get the bearing for let's say Android 1.6 - 4.0?


回答1:


Sensor.TYPE_ORIENTATION is deprecated.

The documentation says you should use SensorManager.getOrientation() instead.

So you should read from Sensor.TYPE_ACCELEROMETER as well as from Sensor.TYPE_MAGNETIC_FIELD, and then call SensorManager.getRotationMatrix() and finally SensorManager.getOrientation() which will return you the orientation of the phone.

From there if you see this diagram it is trivial to get the phone's orientation. This is probably what your second example does, but I don't know because you didn't show me what it is.




回答2:


Thanks to Dan for his sample code.

But there is just a little correction : change event.values to event.values.clone() according to this discussion.
It works for me now after this modification.




回答3:


Using a combination of Sensor.TYPE_ACCELEROMETER and Sensor.TYPE_MAGNETIC_FIELD and SensorManager.getOrientation() method doesn't give me precise values. The deprecated method Sensor.TYPE_ORIENTATION works well. :)



来源:https://stackoverflow.com/questions/8734190/android-compass-example

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