Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android compass example

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?

like image 524
nr1 Avatar asked Jan 04 '12 21:01

nr1


People also ask

Does Google have a compass app?

Google Maps receives features like indoor AR Live View, Air and Weather information with the latest update. Google Maps is relaunching the Compass feature for Android users.

Is there a compass app that works?

This free Android app promises to work anywhere in the world, making it ideal for adventuresome globetrotters. Get Compass 360 Pro Free on Google Play Store.


2 Answers

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.

like image 196
Dan Avatar answered Nov 15 '22 12:11

Dan


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.

like image 22
gezdy Avatar answered Nov 15 '22 12:11

gezdy