android设备角度到垂直轴

时间:2011-08-31 18:34:37

标签: android orientation device

我正在开发一个应用程序,我需要检索设备和垂直轴(指向地球中心的轴)之间的角度。

到目前为止,我发现的所有文档和教程都不是很有说服力。

请您解释一下我该怎么做或者提供一个明确的教程链接,以帮助我找到解决这个问题的方法?

1 个答案:

答案 0 :(得分:1)

首先,我创建了一个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
}