Android: Get current device orientation [duplicate]
Asked Answered
H

1

9

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.

Haerle answered 20/1, 2015 at 8:56 Comment(9)
#2796333 took me 10 secs. to googleGleich
Bart : Well, i went through the same. but its failing when the screen orientation is fixed.I want the device orientation on button clickHaerle
You can run the code in the ActionListener for your buttonGleich
try this. developer.android.com/reference/android/view/…Abdel
@Kushal, i am seeing the same behaviour, trying to come up with a solution as I'd like to know why this happens also. So apologies for my first comment, it doesn't seem to solve your problem indeedGleich
@Haerle are you testing on device or emulator?Gleich
@Bart : No problem. I am currently testing on a device.Haerle
I think chances on others to help are low, since this has been marked duplicate, you might want to try and rephrase the question, indicating the things you've triedGleich
Yep. Will have to do thatHaerle
D
7

Use this :)

getResources().getConfiguration().orientation
Disoblige answered 20/1, 2015 at 8:59 Comment(7)
This is failing when the screen orientation is fixed.Haerle
if it fails, please update your question, with code and stacktraceGleich
By failing, i mean, it always returns the portrait mode value regardless of how i am holding my device.Haerle
@Haerle probably because you are getting the default orientation windowService.getDefaultDisplay().getRotation(); did you try our suggestion?Gleich
Yes I did. int rot = getResources().getConfiguration().orientation; return rot;Haerle
returns 1 always, regardless how i am holding my deviceHaerle
How does this distinguish between landscape left / landscape right? Or portrait / portrait upside down?Tetrafluoroethylene

© 2022 - 2024 — McMap. All rights reserved.