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.
getDefaultDisplay(); int rotation = display. getRotation(); From the documentation: Returns the rotation of the screen from its "natural" orientation.
You can detect this change in orientation on Android as well as iOS with the following code: var supportsOrientationChange = "onorientationchange" in window, orientationEvent = supportsOrientationChange ?
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 :
SensorEvent.values[0]
) : means that the right edge of the device if under the left edge.SensorEvent.values[1]
) : means that the top edge is under the bottom edgeSensorEvent.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");
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With