Created
September 16, 2015 10:47
-
-
Save SammyVimes/92c0627195c4c55ea800 to your computer and use it in GitHub Desktop.
Get REAL orientation in android
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private int getScreenOrientation() { | |
final WindowManager wm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE); | |
int rotation = wm.getDefaultDisplay().getRotation(); | |
DisplayMetrics dm = new DisplayMetrics(); | |
wm.getDefaultDisplay().getMetrics(dm); | |
int width = dm.widthPixels; | |
int height = dm.heightPixels; | |
int orientation; | |
// if the device's natural orientation is portrait: | |
if ((rotation == Surface.ROTATION_0 | |
|| rotation == Surface.ROTATION_180) && height > width || | |
(rotation == Surface.ROTATION_90 | |
|| rotation == Surface.ROTATION_270) && width > height) { | |
switch(rotation) { | |
case Surface.ROTATION_0: | |
orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; | |
break; | |
case Surface.ROTATION_90: | |
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; | |
break; | |
case Surface.ROTATION_180: | |
orientation = | |
ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT; | |
break; | |
case Surface.ROTATION_270: | |
orientation = | |
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE; | |
break; | |
default: | |
Log.e(LOG_TAG, "Unknown screen orientation. Defaulting to " + | |
"portrait."); | |
orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; | |
break; | |
} | |
} | |
// if the device's natural orientation is landscape or if the device | |
// is square: | |
else { | |
switch(rotation) { | |
case Surface.ROTATION_0: | |
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; | |
break; | |
case Surface.ROTATION_90: | |
orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; | |
break; | |
case Surface.ROTATION_180: | |
orientation = | |
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE; | |
break; | |
case Surface.ROTATION_270: | |
orientation = | |
ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT; | |
break; | |
default: | |
Log.e(LOG_TAG, "Unknown screen orientation. Defaulting to " + | |
"landscape."); | |
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; | |
break; | |
} | |
} | |
return orientation; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment