我正在开发一个需要检索设备与垂直轴(指向地球中心的轴)之间的角度的应用程序。
到目前为止,我发现的所有文档和教程都不是很确定。
您能给我解释一下我该怎么做,或者提供一个指向清晰教程的链接,以帮助我找到解决该问题的方法吗?
最佳答案
首先,我创建了一个SensorEventListener实现
private SensorEventListener sensorEventListener =
new SensorEventListener() {
/** The side that is currently up */
//private Side currentSide = null;
//private Side oldSide = null;
private float azimuth;
private float pitch;
private float roll;
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
public void onSensorChanged(SensorEvent event) {
azimuth = event.values[0]; // azimuth
pitch = event.values[1]; // pitch
roll = event.values[2]; // roll
//code to deal with orientation changes;
//pitch is the angle between the vertical axis and the device's y axis (the one from the center of the device to its top)
}
};
然后,我将此监听器注册到方向传感器
SensorManager sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
Sensor sensor;
List<Sensor> sensors = sensorManager.getSensorList(
Sensor.TYPE_ORIENTATION);
if (sensors.size() > 0) {
sensor = sensors.get(0);
sensorManager.registerListener(
sensorEventListener, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
} else {
//notify the user that there's no orientation sensor
}