Android Displaymetrics Returns Incorrect Screen Size in Pixels on Ics

Android DisplayMetrics returns incorrect screen size in pixels on ICS

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!!

Android DisplayMetrics display absolute size varies with orientation

Assuming the display is FullHD acording to your logging there's something of 144px (48dp) height in portrait and 126px (42dp) width in landscape occupying the display (when scaling factor is 3 which is xxhdpi). I bet it's the navigation bar with Back, Home and Recent buttons. This is sufficient for choosing layouts.

EDIT:

If you need the full display size the following code is available from API 17:

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
if (Build.VERSION.SDK_INT >= 17) {
display.getRealSize(size);
} else {
display.getSize(size); // correct for devices with hardware navigation buttons
}

EDIT2:

If you want to make sure you get correct result on API 14 through 16 consider following this answer along with its comments
https://stackoverflow.com/a/11004877/2444099 .

How to get real screen height and width?

I think this will work. The trick is you must use:

display.getRealSize(size);

not

display.getSize(size);

To deal with your API 8 coding issue do something like this:

try { 
display.getRealSize(size);
height = size.y;
} catch (NoSuchMethodError e) {
height = display.getHeight();
}

Only more recent API devices will have onscreen navigation buttons and thus need the new method, older devices will throw an exception but will not have onscreen navigation thus the older method is fine.

In case it needs to be said: Just because you have a minimumAPI level of 8 for your project doesn't mean you have to compile it at that level. I also use level 8 for minimum but my project mostly are compiled at level 13 (3.2) giving them access to a lot of new methods.



Related Topics



Leave a reply



Submit