Get device angle by using getOrientation() function Get device angle by using getOrientation() function android android

Get device angle by using getOrientation() function


You now use two sensors (ACCELEROMETER and MAGNETIC_FIELD) to get that information. See blog post for more detail.

public class CompassActivity extends Activity implements SensorEventListener {  private SensorManager mSensorManager;  Sensor accelerometer;  Sensor magnetometer;  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(mCustomDrawableView);    // Register the sensor listeners    mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);    accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);    magnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);  }  protected void onResume() {    super.onResume();    mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI);    mSensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_UI);  }  protected void onPause() {    super.onPause();    mSensorManager.unregisterListener(this);  }  public void onAccuracyChanged(Sensor sensor, int accuracy) {  }  float[] mGravity;  float[] mGeomagnetic;  public void onSensorChanged(SensorEvent event) {    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);        azimut = orientation[0]; // orientation contains: azimut, pitch and roll      }    }  }}

Permissions:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>


Regarding your second question. When you are registering your sensor listeners, change your code to read:

protected void onResume() {              super.onResume();              mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);              mSensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_NORMAL);          }


Google has a great demo app for orientation in their google-developer-training series called TiltSpot. Because it has an Apache license, I've taken the liberty of turning it into a small library called johnnylambada-orientation that makes getting orientation as simple adding this to your activity:

        getLifecycle().addObserver(new OrientationReporter(this, (a, p, r) -> {            Log.i("orientation","a="+a+" p="+p+" r="+r);        }));