Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: get real screen size

Since API 17 it is possible to get the actual screen size of a phone with:

if (android.os.Build.VERSION.SDK_INT >= 17){
            display.getRealSize(size);
            int screen_width = size.x;
            screen_height = size.y;
} else {...}

I want to get the real screen size for APIs 8-16. What is the best way to handle the else condition in this case?

like image 776
liarspocker Avatar asked Sep 05 '25 01:09

liarspocker


1 Answers

The following is my solution for getting the actual screen height on all APIs. When the device has a physical navigation bar, dm.heightPixels returns the actual height. When the device has a software navigation bar, it returns the total height minus the bar. I have only tested on a few devices but this has worked so far.

int navBarHeight = 0;
Resources resources = context.getResources();
int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
    navBarHeight = resources.getDimensionPixelSize(resourceId);
}

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);

boolean hasPhysicalHomeKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_HOME);
if (android.os.Build.VERSION.SDK_INT >= 17){
    display.getRealSize(size);
    int screen_width = size.x;
    screen_height = size.y;
} else if (hasPhysicalHomeKey){
    screen_height = dm.heightPixels;
} else {
    screen_height = dm.heightPixels + navBarHeight;
}
like image 166
liarspocker Avatar answered Sep 06 '25 15:09

liarspocker