Android compass example

nr1 picture nr1 · Jan 4, 2012 · Viewed 25.7k times · Source

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?

Answer

Dan picture Dan · Jan 4, 2012

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.