Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art
Finding the Orientation of an Android Device Using an Orientation SensorBack to Android Cookbook Home | Up to Chapter: Accelerometer and other Sensors

Author: Rachee Singh ('racheesingh')
In Published Edition? Yes
FormatLanguage: WikiFormat

Finding the Orientation of an Android Device Using an Orientation Sensor


Being able to detect which side of the android device is higher up compared to the rest (Top/Bottom/Right/Left side)


By checking if the pitch and roll values of the Orientation sensor of an android device lie within certain intervals, it can be determined that which side if higher.


Like in case of every other sensor supported by Android, we first require to instantiate the SensorManager class.

SensorManager sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);

Using the object of SensorManager class we can get a handle on the sensors available on the device. The getSensorListe() method returns a list of all sensors of a particular type (in this case Orientation). We need to check if Orientation sensor is supported by the device, if it is, we get the first sensor from the list of sensors. In case the sensor is not supported, an appropriate message is displayed.

List<android.hardware.Sensor> sensorList = sensorManager.getSensorList(Sensor.TYPE_ORIENTATION);
if (sensorList.size() > 0) {
	sensor = sensorList.get(0);
else {
  	orient.setText("Orientation sensor not present");

To register a SensorEventListener with this sensor:

sensorManager.registerListener(orientationListener,sensor, 0, null);

Now, we define the SensorEventListener. This would require implementing 2 methods: onAccuracyChanged() and onSensorChanged(). onSensorChanged is called when the sensor values change. In this case its the orientation sensor values that change on moving the device. Orientation sensor returns 3 values: azimuth, pitch and roll angles. Now we check the returned values, if they lie within particular range and depending upon the range they lie in, appropriate text is displayed.

private SensorEventListener orientationListener = new SensorEventListener() {

	public void onAccuracyChanged(Sensor arg0, int arg1) {

	public void onSensorChanged(SensorEvent sensorEvent) {
		if (sensorEvent.sensor.getType() == Sensor.TYPE_ORIENTATION) {
			float azimuth = sensorEvent.values[0];
			float pitch = sensorEvent.values[1];
			float roll = sensorEvent.values[2];
			if (pitch < -45 && pitch > -135) {
				orient.setText("Top side of the phone is Up!");
	                } else if (pitch > 45 && pitch < 135) {

	            	        orient.setText("Bottom side of the phone is Up!");

	                 } else if (roll > 45) {
				orient.setText("Right side of the phone is Up!");
	                 } else if (roll < -45) {

	            	        orient.setText("Left side of the phone is Up!");

See Also