据我所知,在 Android 上用于传感器融合的最佳方法是 TYPE_ROTATION_VECTOR。我在我的增强现实应用程序中使用它来定位。它是一种复合传感器,其输出是使用来自加速度、磁力计和陀螺仪的最佳可用数据自动生成的。如果您想要漂亮的 Roll-Pitch-Azimuth 类型坐标而不是 RotationVector 输出,假设您只有 RotationVector 传感器,您可以执行以下操作:
public void onSensorChanged(SensorEvent event) {
float[] lastRotVal = new float[3];
try{
System.arraycopy(event.values, 0, lastRotVal, 0, event.values.length);
} catch (IllegalArgumentException e) {
//Hardcode the size to handle a bug on Samsung devices running Android 4.3
System.arraycopy(event.values, 0, lastRotVal, 0, 3);
}
SensorManager.getRotationMatrixFromVector(rotation, lastRotVal);
SensorManager.getOrientation(rotation, orientation);
double pitch = orientation[1];
double roll = orientation[2];
double azimuth = orientation[3];
//Use them for something!
}
如果您想支持不支持 RotationVector 的旧设备,您可以使用新 API 版本中已弃用的 TYPE_ORIENTATION 传感器。在这种情况下,您应该测试 API 版本并在此基础上选择要使用的版本。
如果您想编写自己的自定义融合传感器,这当然是可能的。我想说的是,除非您对最佳实践进行自己的个人研究,否则它不太可能击败这些人的稳健性。