Search code examples
androidandroid-sensors

How to detect the turnover motion in android?


If the user turns over the phone I want to react to that by stopping my text to speech reading. It would be a nice feature for my app, but how can I detect this motion? I'm not really familiar with motion sensors and I could not find this specific motion listener anywhere, mostly just screen orientations. Thanks for the help!


Solution

  • This sample activity demonstrates how a device's gravity sensor can be used to detect when the device is turned over. In method onSensorChanged(), term factor determines how complete the "turn over" must be. Typical range might be 0.7 to 0.95.

    Support for Gravity Sensor was added in Android API 9. Not all devices have a gravity sensor.

    public class MainActivity extends AppCompatActivity implements SensorEventListener {
    
        private static final String TAG = "Demo";
    
        private SensorManager mSensorManager;
        private Sensor mGravitySensor;
        private boolean mFacingDown;
    
        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // nothing
        }
    
        @Override
        public void onSensorChanged(SensorEvent event) {
            final float factor = 0.95F;
    
            if (event.sensor == mGravitySensor) {
                boolean nowDown = event.values[2] < -SensorManager.GRAVITY_EARTH * factor;
                if (nowDown != mFacingDown) {
                    if (nowDown) {
                        Log.i(TAG, "DOWN");
                    } else {
                        Log.i(TAG, "UP");
                    }
                    mFacingDown = nowDown;
                }
            }
        }
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
            mGravitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
    
            if (mGravitySensor == null) {
                Log.w(TAG, "Device has no gravity sensor");
            }
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            if (mGravitySensor != null) {
                mSensorManager.registerListener(this, mGravitySensor, SensorManager.SENSOR_DELAY_NORMAL);
            }
        }
    
        @Override
        protected void onPause() {
            super.onPause();
            mSensorManager.unregisterListener(this);
        }
    }