Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Android device orientation (NOT screen orientation)

Tags:

android

Is there a way to detect the current orientation of an Android device?

I'm not talking about the screen orientation, I'm talking about the way the device is physically being held. All the solutions I've found so far tell me the screen orientation (which is always portrait in my app). I need to know if the user is holding the device horizontally even though I haven't rotated the screen.

Thanks.

like image 659
Flarosa Avatar asked May 22 '14 11:05

Flarosa


People also ask

How do I know what orientation my Android phone is?

getDefaultDisplay(); int rotation = display. getRotation(); From the documentation: Returns the rotation of the screen from its "natural" orientation.

How can we detect the orientation of the screen?

You can detect this change in orientation on Android as well as iOS with the following code: var supportsOrientationChange = "onorientationchange" in window, orientationEvent = supportsOrientationChange ?


1 Answers

You can use the accelerometer. To use it you need to register a listener on the sensor TYPE_ACCELEROMETER.

Once it is done you will receive notifications when the values of this sensor are changing (very very often when the user holds the device in the hand).

Values received from this sensor are the projection of the (vector representing the) gravity on X, Y and Z axis. (well... this is not exactly true: in fact those values represent the projection of the sum of all forces applied to the device) So :

  • positive value on the X axis (SensorEvent.values[0]) : means that the right edge of the device if under the left edge.
  • positive value on the Y axis (SensorEvent.values[1]) : means that the top edge is under the bottom edge
  • positive value on the Z axis (SensorEvent.values[2]) : means that the front of the device if facing the ground and so the 2 previous rules must be inverted.

Here is sample code (Warning : it don't care about the value on the Z-Axis)

/**
 *  Logs the device orientation. Results are not valid when the screen is facing the ground.
 *  (when the discriminant value is low (i.e. device almost horizontal) : no logs)
 */
public void onSensorChanged(SensorEvent event) {
    if (event.sensor == mAccelerometer) {
        if(Math.abs(event.values[1]) > Math.abs(event.values[0])) {
            //Mainly portrait
            if (event.values[1] > 1) {
                Log.d(TAG,"Portrait");
            } else if (event.values[1] < -1) {
                Log.d(TAG,"Inverse portrait");
            }
        }else{
            //Mainly landscape
            if (event.values[0] > 1) {
                Log.d(TAG,"Landscape - right side up");
            } else if (event.values[0] < -1) {
                Log.d(TAG,"Landscape - left side up");
            }
        }
    }
}
like image 81
ben75 Avatar answered Sep 18 '22 20:09

ben75