Function that returns screen resolution

Asked

Viewed 4,369 times

6

I need a Java function that returns the resolution of my Android device.

2 answers

5


You can use this way from API 13:

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

I put in the Github for future reference.

For the previous versions:

DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int wwidth = displaymetrics.widthPixels;

I put in the Github for future reference.

You need to be in a Activity to use this way, but probably is. If not, the code will need to be changed to take the context.

1

You can use the DisplayMetrics:

DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int height = displayMetrics.heightPixels;
int widht = displayMetrics.widthPixels;

Note: the heightPixels returns the total size of your screen along with its status bar. If you want to ignore the bar status size (useful for animations operations etc), you simply:

public int getStatusBarHeight() {
    int result = 0;
    int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
        result = getResources().getDimensionPixelSize(resourceId);
    }
    return result;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.