Android rotation vector sensor error [closed]

2019-05-04 15:02发布

I'm not asking a question. I'm going to post this in case anyone else runs into this problem. If you follow the Android API guide for the rotation sensor, you will run into an error. Specifically: java.lang.IllegalArgumentException, because some devices return an array with FIVE values. You can probably fix this now that you know this, but anyway here's how to do it:

    private int rotateVectLength;
    private float[] jRotateVectValues = null;
    public void onSensorChanged(SensorEvent event) {
        // we received a sensor event. it is a good practice to check
        // that we received the proper event
        if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
            // convert the rotation-vector to a 4x4 matrix. the matrix
            // is interpreted by Open GL as the inverse of the
            // rotation-vector, which is what we want.
            if(jRotateVectValues == null) {
                rotateVectLength = event.values.length;
                jRotateVectValues = new float[rotateVectLength];
            }
            for(int i = 0; i < rotateVectLength; i++) {
                jRotateVectValues[i] = event.values[i];
            }
            SensorManager.getRotationMatrixFromVector(mRotationMatrix, event.values);
        }
    }

Hope this helps someone. Cheers!

The documentation does point this out:

values[0]: x*sin(θ/2) 
values[1]: y*sin(θ/2) 
values[2]: z*sin(θ/2) 
values[3]: cos(θ/2) 
values[4]: estimated heading Accuracy (in radians) (-1 if unavailable)

values[3], originally optional, will always be present from SDK Level 18 onwards. values[4] is a new value that has been added in SDK Level 18.

0条回答
登录 后发表回答