Search code examples
androidsizescreenresolution

Get the size of the screen not using getMetrics


I'd like to get the size of the screen of the phones but it keeps giving me wrong values, I already used

WindowManager windowmanager = (WindowManager)      
getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
Display display = windowmanager.getDefaultDisplay();
DisplayMetrics displayMetrics = new DisplayMetrics();
display.getMetrics(displayMetrics);

float deviceWidth = displayMetrics.widthPixels;
float deviceHeight = displayMetrics.ydpi;

I tried this code too :

Resources resources = getResources();
Configuration config = resources.getConfiguration();
DisplayMetrics dm = resources.getDisplayMetrics();
// Note, screenHeightDp isn't reliable
// (it seems to be too small by the height of the status bar),
// but we assume screenWidthDp is reliable.
// Note also, dm.widthPixels,dm.heightPixels aren't reliably pixels
// (they get confused when in screen compatibility mode, it seems),
// but we assume their ratio is correct.
double screenWidthInPixels = (double)config.screenWidthDp *dm.density;
double screenHeightInPixels = screenWidthInPixels * dm.heightPixels     / dm.widthPixels;
deviceWidth = (int)(screenWidthInPixels + .5);
deviceHeight = (int)(screenHeightInPixels + .5);

And also that :

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
    Point realSize = new Point();
    display.getRealSize(realSize);
    deviceWidth= realSize.x;
    deviceHeight = realSize.y;
}

But on my Samsung S7 on sdk 7.0 I got 1920x1080 that is wrong because on a S7 on sdk 6.0.1 I got 2560x1440 that is the real value. I tried a lot of solution but found nothing good.

Thanks


Solution

  • Your code is correct. Just in case if you wondering why you get that values, it is because your phone will automatically set the default resolution size to 1920x1080 after updated to 7.0 (Nougat) to conserve the battery life. One of the new features in Nougat is display scaling option, where you can set your phone (in this case, S7) to 3 available modes (WQHD (2560x1440), FHD (1920x1080), and HD (1280x720)). Try go to Settings -> Display and change the settings to your needs. You can read more here: Galaxy S7 on Nougat defaults to 1080p