Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Checking Whether a Device Is Facing Up or Facing Down Based on Screen Orientation Using an Accelerometer

In Chapter: Accelerometer and other Sensors
Author: Rachee Singh ('racheesingh')
Published? true
FormatLanguage: WikiFormat


Check for the orientation (Facing up/Facing Down) of the Android device.


Checking for appropriate Accelerometer values.


We require to listen for changes in the accelerometer values, for this purpose we need to implement a SensorEventListener. The onSensorChanged method is called when sensor values change. Within this method we check if the values lie within a particular range for the device to be facing down or facing up.

To obtain the sensor object for an accelerometer:

List<android.hardware.Sensor> sensorList = deviceSensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
sensor = sensorList.get(0);

Creating the listener:

    private SensorEventListener accelerometerListener = new SensorEventListener() {
        public void onSensorChanged(SensorEvent event) {
            float z = event.values[2];
            if (z >9 && z < 10)
                face.setText("FACE UP");
            else if (z > -10 && z < -9)
                face.setText("FACE DOWN");

		public void onAccuracyChanged(Sensor arg0, int arg1) {


After implementing the listener along with the methods required, we need to register the listener for a particular sensor (which in our case is the accelerometer). 'sensor' is an object of Sensor class, it represents the sensor being used in the application (Accelerometer).

deviceSensorManager.registerListener(accelerometerListener, sensor, 0, null);