开发者

Which sensor for rotating android phone?

Imagine you are pointing at the TV. You have your phone gripped in your hand. Now, rotate your wrist.

Which sensor would I need to manage to detect such a movement?

Gyroscope? 开发者_运维百科Orientation? Accelerometer?


The sensors TYPE_MAGNETIC_FIELD and TYPE_ACCELEROMETER are fine to detect that (as TYPE_ORIENTATION is now deprecated).

You will need:

a few matrix:

private float[] mValuesMagnet      = new float[3];
private float[] mValuesAccel       = new float[3];
private float[] mValuesOrientation = new float[3];

private float[] mRotationMatrix    = new float[9];

a listener to catch the values the sensors send (this will be an argument of SensorManager.registerListener() that you will have to call to setup your sensors):

private final SensorEventListener mEventListener = new SensorEventListener() {
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    public void onSensorChanged(SensorEvent event) {
        // Handle the events for which we registered
        switch (event.sensor.getType()) {           
            case Sensor.TYPE_ACCELEROMETER: 
                System.arraycopy(event.values, 0, mValuesAccel, 0, 3); 
                break; 

            case Sensor.TYPE_MAGNETIC_FIELD: 
                System.arraycopy(event.values, 0, mValuesMagnet, 0, 3); 
                break; 
    }
};

And you'll need to compute the azimuth, pitch, and roll:

    SensorManager.getRotationMatrix(mRotationMatrix, null, mValuesAccel, mValuesMagnet);
    SensorManager.getOrientation(mRotationMatrix, mValuesOrientation);  

mValuesOrientation is then filled with:

  • mValuesOrientation[0]: azimuth, rotation around the Z axis.
  • mValuesOrientation[1]: pitch, rotation around the X axis.
  • mValuesOrientation[2]: roll, rotation around the Y axis.

Check the documentation of getOrientation() to know how the axis are defined. You may need to use SensorManager.remapCoordinateSystem() to redefine these axis.


It depends on what you want to detect, if you want to detect that the phone has been moved in a rotation then accelerometer is probably your best bet. If you want to detect that the phone is now rotated then Orientation.


The gyroscope is for detecting rotations if you don't care about your position relative to the Earth.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜