11

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?

Dan
  • 10,531
  • 2
  • 36
  • 55
nr1
  • 777
  • 3
  • 12
  • 31

3 Answers3

21

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.

Siddharth
  • 9,349
  • 16
  • 86
  • 148
Dan
  • 10,531
  • 2
  • 36
  • 55
  • 4
    Sorry i forgot to attach the example: http://www.codingforandroid.com/2011/01/using-orientation-sensors-simple.html So this one is the correct way? – nr1 Jan 04 '12 at 21:31
  • Obviously how you use the data is up to you, `onSensorChanged` is where the interesting math is. – Dan Jan 04 '12 at 21:40
  • One more question: How do i get the correct bearing in degrees out of the "azimut = orientation[0];" line? – nr1 Jan 05 '12 at 10:22
  • 1
    @nr1 Math.toDegrees(orientation[0]) – Bill Mote Apr 02 '13 at 12:42
5

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.

gezdy
  • 3,292
  • 2
  • 14
  • 14
0

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. :)

Czechnology
  • 14,832
  • 10
  • 62
  • 88
M. Usman Khan
  • 3,689
  • 1
  • 59
  • 69
  • 3
    Fix your code then. The code sample seems to be working fine (http://www.codingforandroid.com/2011/01/using-orientation-sensors-simple.html paired with gezdy's comment) – Vaiden Jun 13 '13 at 14:09
  • 1
    Or maybe you need to recalibrate your device – Vaiden Jun 17 '13 at 08:35