gpt4 book ai didi

Android:从 Azimuth、roll & pitch 获取设备方向

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:19:52 28 4
gpt4 key购买 nike

我需要获取更新的设备方向,但我必须将我的 Activity 固定为纵向(我在布局 xml 文件中所做的),这阻止了我使用它:

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

因为它总是给我纵向旋转,

所以,我尝试依靠传感器。我发现 Sensor.TYPE_ORIENTATION 已被弃用,所以我使用了 Sensor.TYPE_ACCELEROMETERSensor.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个值azimuth, pitch & roll来检测当前设备方向作为其中之一:

  • 横向(旋转 0)
  • 纵向(旋转 90)
  • 反向横向(旋转 180)
  • 反向纵向(旋转 270)

最佳答案

我已经找到了,这里是计算函数,在读取 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实现

-- 更新--

添加此图像以帮助可视化方位角俯仰滚动: Visualizing azimuth, pitch and roll

关于Android:从 Azimuth、roll & pitch 获取设备方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25972519/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com