android: why getrotationmatrix return false?

泄露秘密 提交于 2019-12-01 05:32:36

I've try again and get the solution but I change the code to become like below

    public void onSensorChanged(SensorEvent event) {
    // TODO Auto-generated method stub
    switch (event.sensor.getType()) {
    case Sensor.TYPE_ACCELEROMETER:
        for(int i=0; i<3; i++){
            accelValues[i] =  event.values[i];
        }
        if(compassValues[0] != 0)
            ready = true;

        break;

    case Sensor.TYPE_MAGNETIC_FIELD:
        for(int i=0; i<3; i++){
            compassValues[i] = event.values[i];
        }
        if(accelValues[2] != 0)
            ready = true;

        break;
    }

    if(!ready)
        return;

    boolean cek = SensorManager.getRotationMatrix(inR, inclineMatrix, accelValues, compassValues);

    if(cek){
        SensorManager.getOrientation(inR, prefValues);
        mInclination = SensorManager.getInclination(inclineMatrix);

        //display every 30th values
        if(counter++ % 30 == 0){
            //do your code, what you want to do to the result
            counter = 1;
        }
    }

and everything work well

Make sure that you have registered your listeners to listen to the accelerometer, magmetic field and gyro (optional). You do this in the onResume method. If you forget to do this you will get "false" return value when calling getRotationMatrix.

I hope this helps!

   protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

   mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);

   // do more staff here..
   }


   protected void onResume() {
    super.onResume();

    mSensorManager.registerListener(
            this, 
            mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
             SensorManager.SENSOR_DELAY_NORMAL );
          mSensorManager.registerListener(
            this, 
            mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), 
            SensorManager.SENSOR_DELAY_NORMAL );
          mSensorManager.registerListener(
                this, 
                mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE), 
                SensorManager.SENSOR_DELAY_NORMAL );


}

protected void onPause() {
    super.onPause();
    mSensorManager.unregisterListener(this);
}

The problem is with this part of code:

if(event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE)
    return;

For accelerometer event.accuracy return SensorManager.SENSOR_STATUS_UNRELIABLE that is why gravity is always null.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!