Android DisplayMetrics returns incorrect screen size in pixels on ICS

dell116 picture dell116 · Jun 12, 2012 · Viewed 34.2k times · Source

I've tried this....

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int fullscreenheight = metrics.heightPixels;
int fullscreenwidth = metrics.widthPixels;

and....

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;

The Gnex has a display of 720×1280. The returned result for width/height (depending on orientation of course) is never 1280. I thought this might have something to do with the on screen navigation bar in Ice Cream Sandwich, so I hide that with :

getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);

...and then started a thread which continuously logs the screen size height/width. Even after the ICS navigation bar was completely gone....the screen size would never report the 1280 value. I would get numbers like this:

width  = 720
height = 1184

How do you get the true device screen resolution in ICS?

The reason why I need this value is because my app plays video and I would like for the video to take up the entire screen when the device is in landscape orientation. Now I know what you're thinking, why not just give the videoview a value of "match_parent" for the height/width? The reason is because my videos have multiple aspect ratios and I'd like to be able to calculate the correct video size depending on the entire width of the screen.

Answer

dell116 picture dell116 · Jun 12, 2012

I found this hidden treasure for ICS ONLY......if you're targeting API's higher than ICS see the comment by Chris Schmich below.

How to hide and display the navigation bar on Android ICS build

In case the link dies....here's how to get the actual device screen size.....

Display display = getWindowManager().getDefaultDisplay();     
Method mGetRawH = Display.class.getMethod("getRawHeight");
Method mGetRawW = Display.class.getMethod("getRawWidth");
int rawWidth = (Integer) mGetRawW.invoke(display);
int rawHeight = (Integer) mGetRawH.invoke(display);

EDIT (11/19/12)

The above code WILL NOT WORK on Android 4.2 and an exception will be thrown....I have yet to find a way to get the full screen size of a device in Android 4.2. When I do, I will edit this answer, but for now, you should code with contingency for android 4.2!!