Android 读取硬件罗盘的正确方法是什么?

Android 读取硬件罗盘的正确方法是什么?,android,android-sensors,Android,Android Sensors,Android API演示中有一个指南针活动,但在我的Google Nexus One上,只有在纵向模式下,它才能显示向北的正确方向 我在这里找到了以下代码: private float[] magneticValues; private float[] accelerometerValues; @Override public void onSensorChanged(SensorEvent event) { switch (event.sensor.getType()) {

Android API演示中有一个指南针活动,但在我的Google Nexus One上,只有在纵向模式下,它才能显示向北的正确方向

我在这里找到了以下代码:

private float[] magneticValues;
private float[] accelerometerValues;

@Override
public void onSensorChanged(SensorEvent event)
{
    switch (event.sensor.getType())
    {
        case Sensor.TYPE_MAGNETIC_FIELD:
            magneticValues = event.values.clone();
            break;
        case Sensor.TYPE_ACCELEROMETER:
            accelerometerValues = event.values.clone();
            break;
    }

    if (magneticValues != null && accelerometerValues != null)
    {
        float[] R = new float[16];
        SensorManager.getRotationMatrix(R, null, accelerometerValues, magneticValues);
        float[] orientation = new float[3];
        SensorManager.getOrientation(R, orientation);

        orientation[0] = (float) Math.toDegrees(orientation[0]);
        orientation[1] = (float) Math.toDegrees(orientation[1]);
        orientation[2] = (float) Math.toDegrees(orientation[2]);

        if (orientation[0] >= 360) orientation[0] -= 360;
        if (orientation[0] < 0) orientation[0] = 360 - orientation[0];
        if (orientation[1] >= 360) orientation[1] -= 360;
        if (orientation[1] < 0) orientation[1] = 360 - orientation[1];
        if (orientation[2] >= 360) orientation[2] -= 360;
        if (orientation[2] < 0) orientation[2] = 360 - orientation[2];

        azimuth = orientation[0];
        pitch = orientation[1];
        roll = orientation[2];

        updateView();
    }
}
private float[]磁性值;
私人浮动[]加速计值;
@凌驾
传感器更改时的公共无效(传感器事件)
{
开关(event.sensor.getType())
{
外壳传感器。类型\u磁场:
magneticValues=event.values.clone();
打破
外壳传感器.U型加速计:
accelerometerValues=event.values.clone();
打破
}
if(磁性值!=null和加速度计值!=null)
{
浮动[]R=新浮动[16];
SensorManager.getRotationMatrix(R、null、加速度计值、磁性值);
浮动[]方向=新浮动[3];
SensorManager.getOrientation(R,方向);
方向[0]=(浮点)数学到方向(方向[0]);
方向[1]=(浮点)数学到方向(方向[1]);
方向[2]=(浮点)数学到方向(方向[2]);
如果(方向[0]>=360)方向[0]=360;
如果(方向[0]<0)方向[0]=360-方向[0];
如果(方向[1]>=360)方向[1]=360;
如果(方向[1]<0)方向[1]=360-方向[1];
如果(方向[2]>=360)方向[2]=360;
如果(方向[2]<0)方向[2]=360-方向[2];
方位角=方向[0];
螺距=方向[1];
滚动=方向[2];
updateView();
}
}
但它并没有显示出任何合理的迹象。我不明白如何使API演示程序在横向模式下正确工作,或者上面的代码有什么问题。

请看这里:

您需要根据重力矢量重新映射地磁矢量,即您需要同时打开加速计和磁场传感器并发送事件