Search code examples
androidrotationaccelerometerandroid-sensorsportrait

Detect rotation with accelerometer


My application orientation must be limited to portrait.

But I want to detect when I rotate the device twice in one second or less.

How can I detect the rotation movement but without rotating the app?


Solution

  • I finally resolved it like this:

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