用加速度计检测旋转

时间:2016-11-01 14:43:29

标签: android rotation accelerometer android-sensors portrait

我的申请方向必须限于肖像。

但我想检测何时在一秒或更短时间内旋转设备两次。

如何在不旋转应用程序的情况下检测旋转运动?

1 个答案:

答案 0 :(得分:1)

我终于解决了这个问题:

boolean vertical, horizontal;
int rotation;
long t1, t2, t;

@Override
    protected void onCreate(Bundle savedInstanceState) {

    rotation = -1;

    senSensorManager =
    (SensorManager)getSystemService(Context.SENSOR_SERVICE);

    senAccelerometer =
    senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

    senSensorManager.registerListener
    (this, senAccelerometer,SensorManager.SENSOR_DELAY_NORMAL);

    //...
}

@Override
public void onSensorChanged(SensorEvent event) {
    Sensor mySensor = event.sensor;
    if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];

        if (rotation == 0) {
            t1 = System.currentTimeMillis();
        }

        if (Math.abs(x)>5 && Math.abs(y)<5 && !horizontal) {
            vertical = false;
            horizontal = true;
            rotation++;
            Log.d(TAG, "horizontal");
        }
        if (Math.abs(x)<5 && Math.abs(y)>5 && !vertical) { 
            vertical = true;
            horizontal = false;
            rotation++;
            Log.d(TAG, "vertical");
        }

        t2 = System.currentTimeMillis();
        t = t2 - t1;
        if (t>1000 && rotation<2) {
            rotation = 0;
        } else if (t<=1000 && rotation==2) {
            Log.d(TAG, "Rotated twice in t <= 1000ms");
            rotation = 0;
        } else if (rotation>2) {
            rotation = 0;
        }
    }
}