3

我有这样的代码实现:

    //register sensor in OnResume
    mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI);
    mSensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_UI);

    public void onSensorChanged(SensorEvent event) {

    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
        mGravity = event.values;
    if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
        mGeomagnetic = event.values;

    if (mGravity != null && mGeomagnetic != null) {
        float R[] = new float[9];
        float I[] = new float[9];
        boolean success = SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic);

        if (success) {
            float orientation[] = new float[3];
            SensorManager.getOrientation(R, orientation);

            azimuth = (int)( Math.toDegrees( orientation[0] ) + 0.5 );    // orientation contains: azimuth, pitch and roll
            pitch = (int)( Math.toDegrees( orientation[1] ) + 0.5 );
            roll = (int)( Math.toDegrees( orientation[2] ) + 0.5 );

            // output azimuth, pitch and roll
        }
    }
}

上述代码在 Galaxy Nexus 单元中运行良好,但在 nexus 平板电脑中出现问题(方位角、俯仰和滚动的更新响应不佳,有时需要 5 到 8 秒)。

我已经检查过 OnSensorChanged() 的调用运行良好,但是“if(success)”测试并不总是成功,这会导致这个问题。

我通过输出布尔变量“成功”来测试它:

  • 在 Galaxy Nexus 中,真假比例约为 1:1。
  • 在 Nexus 平板中,真假率差异很大,可高达 >20 : 1。

任何帮助深表感谢。

4

2 回答 2

1

问题在于以下代码:

if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) mGravity = event.values; if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) mGeomagnetic = event.values; 

它应该是:

if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) mGravity = event.values.clone(); 
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) mGeomagnetic = event.values.clone(); 

否则“getRotationMatrix”方法将频繁返回“false”。但我不确定为什么?

于 2015-05-25T04:08:11.440 回答
0

这可能是因为有一个固定的 SensorEvent 池,如果您直接使用其中的数据,它可能会从您下面更改,但通过克隆它,您可以随时使用该数据。

于 2012-10-14T15:04:42.347 回答