Android: Get current device orientation

Kushal picture Kushal · Jan 20, 2015 · Viewed 13.6k times · Source

I have the activity orientation in manifest set as portrait. As i dont want my screen to rotate.

But On Clicking a button, I want to get the current device orientation (portrait or landscape) in Android ? I do not need continuous update from the sensors; just the current device orientation when i click the button is enough.

PS: Device Orientation is the way i am holding my Device. Do not mix this with screen orientation.

This is what i have done so far?

 int PORT=1,LAND=2;

 WindowManager windowService = (WindowManager)getSystemService(Context.WINDOW_SERVICE);

 int rotation = windowService.getDefaultDisplay().getRotation();        

    if (Surface.ROTATION_0 == rotation) {
        rotation = PORT;
    } else if(Surface.ROTATION_180 == rotation) {
        rotation = PORT;
    } else if(Surface.ROTATION_90 == rotation) {
        rotation = LAND;
    } else if(Surface.ROTATION_270 == rotation) {
        rotation = LAND;
    }
 return rotation;

Even using the following method doesnt help

getResources().getConfiguration().orientation

It always return 1 since my activity default is set a portrait.

Sample/example code will be highly appreciated.

Thanks.

Answer

Shirane85 picture Shirane85 · Jan 20, 2015

Use this :)

getResources().getConfiguration().orientation