Better Orientation Readings in Android

The orientation sensor is deprecated. The new suggested method of determining orientation is a bit more complex, but produces better results. The following example should be enough to get you started. For help with interpreting the results, consult the SensorEvent documentation.
private class SensorValuesCollector implements SensorEventListener {
  private float[] mMagneticValues;
  private float[] mAccelerometerValues;

  private final float mAzimuth;
  private final float mPitch;
  private final float mRoll;

  public void onAccuracyChanged(Sensor sensor, int accuracy) {

  public void onSensorChanged(SensorEvent event) {
    synchronized (TiltController.this) {
      switch (event.sensor.getType()) {
      case Sensor.TYPE_MAGNETIC_FIELD:
        mMagneticValues = event.values.clone();
      case Sensor.TYPE_ACCELEROMETER:
        mAccelerometerValues = event.values.clone();

      if (mMagneticValues != null && mAccelerometerValues != null) {
        float[] R = new float[MATRIX_SIZE];
        SensorManager.getRotationMatrix(R, null, mAccelerometerValues, mMagneticValues);
        float[] orientation = new float[3];
        SensorManager.getOrientation(R, orientation);
        mAzimuth = orientation[0];
        mPitch = orientation[1];
        mRoll = orientation[2];

1 comment:

  1. Does the given example work in all hardware back to 1.5?