由于我在搜索网络时没有找到任何相关答案,所以我发布了一个问题,询问如何使用加速计检测Android设备绕其轴的360度旋转。例如,在横屏模式下绕y轴旋转:假设在起始位置,y值为0(设备平放在地面上)。当手机向前旋转90度时,y = -10
,180度向前倾斜会导致y = 0
,270度倾斜会导致y = +10
,而360度则是y = 0
。那么如何编写代码以仅在预定方向上检测设备的完整旋转呢?
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
// assign directions
x = event.values[1];
y = event.values[0];
z = event.values[2];
???
}
}
编辑:通过使用getRotationMatrix()方法已成功解决。
private float[] r = new float[9];
private float[] i = new float[9];
private float[] v = new float[3];
private float[] accValues = new float[3];
private float[] geoValues = new float[3];
private int azimuth, pitch, roll;
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
accValues = event.values.clone();
}
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
geoValues = event.values.clone();
}
boolean success = SensorManager.getRotationMatrix(r, i, accValues,
geoValues);
if (success) {
SensorManager.getOrientation(r, v);
azimuth = v[0] * (180 / Math.PI);
pitch = v[1] * (180 / Math.PI);
roll = v[2] * (180 / Math.PI);
}
}