Android:从Azimuth获取设备方向,roll&沥青

时间:2014-09-22 11:01:41

标签: android rotation android-sensors

我需要获取更新的设备方向,但我必须将我的活动修复为Portrait(我在布局xml文件中执行),这阻止我使用它:

int rotation = getWindowManager().getDefaultDisplay().getRotation();

因为它总是给我画像旋转,

所以,我试图依赖传感器。我发现Sensor.TYPE_ORIENTATION已弃用,因此我使用了Sensor.TYPE_ACCELEROMETER&的组合。 Sensor.TYPE_MAGNETIC_FIELD这里是事件监听器:

SensorEventListener sensorEventListener = new SensorEventListener() {
    float[] mGravity;
    float[] mGeomagnetic;

    @Override
    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 orientationData[] = new float[3];
                SensorManager.getOrientation(R, orientationData);
                azimuth = orientationData[0];
                pitch = orientationData[1];
                roll = orientationData[2];
                // now how to use previous 3 values to calculate orientation
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // TODO Auto-generated method stub

    }
};

现在问题,如何使用3个值azimuthpitch& roll将当前设备方向检测为以下之一:

  • 风景(轮换0)
  • 人像(轮换90)
  • 逆向风景(旋转180)
  • 反转人像(旋转270)

1 个答案:

答案 0 :(得分:12)

我发现它&这是在阅读pitch&之后将在监听器内调用的计算函数。 roll

public static final int ORIENTATION_PORTRAIT = 0;
public static final int ORIENTATION_LANDSCAPE_REVERSE = 1;
public static final int ORIENTATION_LANDSCAPE = 2;
public static final int ORIENTATION_PORTRAIT_REVERSE = 3;
public int orientation = ORIENTATION_PORTRAIT;

private int calculateOrientation(int roll, int pitch) {
    if (((orientation == ORIENTATION_PORTRAIT || orientation == ORIENTATION_PORTRAIT_REVERSE)
            && (roll > -30 && roll < 30))) {
        if (averagePitch > 0)
            return ORIENTATION_PORTRAIT_REVERSE;
        else
            return ORIENTATION_PORTRAIT;
    } else {
        // divides between all orientations
        if (Math.abs(pitch) >= 30) {
            if (pitch > 0)
                return ORIENTATION_PORTRAIT_REVERSE;
            else
                return ORIENTATION_PORTRAIT;
        } else {
            if (averageRoll > 0) {
                return ORIENTATION_LANDSCAPE_REVERSE;
            } else {
                return ORIENTATION_LANDSCAPE;
            }
        }
    }
}

- 更新 -

&安培;这是我的完整utility class实施

- 更新 -

添加此图片以帮助可视化azimuthpitch&amp; rollVisualizing azimuth, pitch and roll