简体   繁体   English

android OnSensorChanged()响应慢

[英]android OnSensorChanged() slow response

I have code implemented like this: 我有这样的代码实现:

    //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
        }
    }
}

The above code works fine in Galaxy Nexus cell, but it has problem in nexus tablet (the updating of azimuth, pitch and roll are not well responding, sometimes take 5 to 8 secs). 以上代码在Galaxy Nexus单元格中运行良好,但在nexus平板电脑中存在问题(方位角,俯仰和滚动的更新反应不佳,有时需要5到8秒)。

I have checked that the calling of OnSensorChanged() is working well, but the "if(success)" test is not always success which gets this problem. 我已经检查过调用OnSensorChanged()是否运行良好,但是“if(成功)”测试并不总是成功解决了这个问题。

I tested it by output the boolean variable "success": 我通过输出布尔变量“success”来测试它:

  • In Galaxy Nexus, the rate of false and true is about 1:1. 在Galaxy Nexus中,虚假和真实的比率约为1:1。
  • In Nexus tablet, the rate of false and true varies a lot, can be high as >20 : 1. 在Nexus平板电脑中,虚假和真实的比率变化很大,可以高达> 20:1。

Any help is much appreciated. 任何帮助深表感谢。

The problem lies with the following code: 问题在于以下代码:

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

it should be: 它应该是:

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

Otherwise the "getRotationMatrix" method will frequently return "false". 否则,“getRotationMatrix”方法将频繁返回“false”。 But I am not sure why? 但我不确定为什么?

这可能是因为存在一个固定的SensorEvents池,如果您直接使用它们中的数据,它可以从您的下方更改,但通过克隆它您可以随时使用该数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM