How to get screen density in android programmatically
We can get screen density from component called DisplayMetrics as below .
DisplayMetrics metrics = getResources().getDisplayMetrics();
Though Android doesn’t use a direct pixel mapping, it uses a handful of quantized Density Independent Pixel values then scales that to the actual screen size. So the density property will be one of those constants (120, 160, or 240 dpi).
** UPDATE: Android Complete tutorial now available here.
If you need the actual density (perhaps for an OpenGL app) you can get it from the xdpi and ydpi properties for horizontal and vertical density respectively.
densityDpi parameter in DisplayMetrics gives you directly density region the phone belongs.
DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); switch(metrics.densityDpi){ case DisplayMetrics.DENSITY_LOW: break; case DisplayMetrics.DENSITY_MEDIUM: break; case DisplayMetrics.DENSITY_HIGH: break; }
The below code also gives you the density in different region.
0.75 – ldpi
1.0 – mdpi
1.5 – hdpi
2.0 – xhdpi
3.0 – xxdpi
getResources().getDisplayMetrics().density;
Below code gives you directly screen size category .
int screenSize = getResources().getConfiguration().screenLayout ; Configuration.SCREENLAYOUT_SIZE_MASK; switch(screenSize) { case Configuration.SCREENLAYOUT_SIZE_LARGE: Toast.makeText(this, "Large screen",Toast.LENGTH_LONG).show(); break; case Configuration.SCREENLAYOUT_SIZE_NORMAL: Toast.makeText(this, "Normal screen",Toast.LENGTH_LONG).show(); break; case Configuration.SCREENLAYOUT_SIZE_SMALL: Toast.makeText(this, "Small screen",Toast.LENGTH_LONG).show(); break; default: Toast.makeText(this, "Screen size is neither large, normal or small" , Toast.LENGTH_LONG).show(); }
To get parameter in dpi .
DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); // will either be DENSITY_LOW, DENSITY_MEDIUM or DENSITY_HIGH int dpiClassification = dm.densityDpi; // these will return the actual dpi horizontally and vertically float xDpi = dm.xdpi; float yDpi = dm.ydpi;