tags:

views:

110

answers:

5

How to get the screen density programmatically in android?

I mean How to find the screen dpi of the current device?

A: 

This should work.

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels; //320
int height = dm.heightPixels; //480
BrennaSoft
The size in pixels of the display is not the density.
joshperry
A: 

Use the DisplayMetrics class.

CommonsWare
A: 

You can get info on the display from the DisplayMetrics struct:

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

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).

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.

joshperry
A: 

To get 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;
Jere.Jones
A: 

It doesn't work. if you do the math manually, you'll see that xdpi and yxpi are grossly wrong.

CrazyJay