5

I'm experimenting with some Android functions. Right now, I'm trying to get the rotation angle of the device, so when I show a happy face bitmap on a canvas, it always looks "straight".

All I would need for this, is to get the x-axis rotation angle (I guess) but I can't find how to achieve it. Hope you can help me. Thank you.

  • what happens if I use your app with the phone sitting on a flat surface? Will it still be OK? – Simon MᶜKenzie Aug 23 '12 at 03:21
  • 1
    I have tested it on a "flat" surface. It responses right even with the slightest inclination. Besides, the purpose for what I am making this test, is not probably to be used on flat surfaces, but thanks! –  Aug 23 '12 at 03:41

2 Answers2

25

Found a better answer! (Thanks to forgivegod for helping me starting this!)

ORIENTATION is now deprecated and uses to many resources. Plus, it works with reference to the magnetic north, which gives not the pure rotation of the device, but actually always points to the north.

By using ACCELEROMETER, one can calculate the rotation angle of the device with values [0] and [1] this way:

    public void onSensorChanged(SensorEvent event) {
        // TODO Auto-generated method stub
        if (event.sensor != mSensor)
            return;

        aX= event.values[0];
        aY= event.values[1];
        //aZ= event.values[2];
        angle = Math.atan2(aX, aY)/(Math.PI/180);
    }

Maybe this can help someone else in the future. Thanks a lot!

2

There is azimuth, pitch and roll available to you. Not sure which one relates to your "x-axis" but I think its azimuth.

Time for helpful links:

  1. http://www.workingfromhere.com/blog/2009/03/30/orientation-sensor-tips-in-android/
  2. http://marakana.com/forums/android/examples/43.html
  3. http://marakana.com/static/tutorials/SensorDemo.zip
petey
  • 16,914
  • 6
  • 65
  • 97
  • 1
    It works perfectly! azimuth is a little slow, but does the job! Thanks a lot. Just one thing that worries me, as it says that SensorListener and SENSOR_ORIENTATION are now deprecated... This means there is a new way to do so, right? –  Aug 23 '12 at 03:19
  • 1
    I must add. With Marakana's example in mind, i modified it slightly to use SensorEventListener and Sensor.TYPE_ORIENTATION instead. The response is quite faster, and now the only deprecated object is Sensor.TYPE_ORIENTATION. I'll leave it this way for now, since the new "solution" is quite more complex and gives the same result. Thank you for all! –  Aug 23 '12 at 03:53
  • 1
    Please note SENSOR_ORIENTATION is deprecated – MonoThreaded Apr 16 '15 at 10:14