Calculate phone angle (Android)

I know this was asked before, but I did not find the answer I'm looking for.

All I want to do is keep my phone in the sky and know the angle at which I hold it relative to the horizon. Therefore, if I hold it directly above me (the screen is on the ground), then it should read 90 degrees, and if I hold it in front of me (the screen is looking at me), it should read 0 degrees.

I tried some basics of getting data from the accelerometer, and I believe that I have values ​​of X, Y and Y. How can I take these glasses and find my angle? Below is my OnSensorChanged event, from where I collect the coordinate.

    public void onSensorChanged(SensorEvent event) {
    // TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
   mGravity = event.values;
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
   mGeomagnetic = event.values;
if (mGravity != null && mGeomagnetic != null) {
   float R[] = new float[9];
   float I[] = new float[9];

  boolean success = SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic);
   if (success) {
       float orientation[] = new float[3];
       SensorManager.getOrientation(R, orientation);
       playerAngle = (float) Math.toDegrees(Math.atan2(orientation[1], orientation[0]));

    }
+5
source share

All Articles