Jean
Jean

Reputation: 2625

Android : Device density is returned as zero from some devices

The device density return 0 from some devices. The following code is used to calculate device density:

WindowManager wm = (WindowManager) context
        .getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics metrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(metrics);
density = metrics.density;

This has resulted in some crashes in PlayStore. The users seem to be using: Galaxy Y Plus ; Android version 4.0.3 - 4.0.4. Also a device called wing-k70 had problems. In one crash it was version 4.2.

Please advice.

Upvotes: 11

Views: 455

Answers (3)

JesusS
JesusS

Reputation: 1665

A good way to get the DPI is to generate a string.xml file for every density.

Create folders called values-mdpi, values-hdpi, values-xhdpi... and add a strings.xml in everyone, with a string called density with the value of the density (mdpi for strings.xml located in values-mdpi, etc)

then reading R.string.density will give you the correct density

Upvotes: 4

DKIT
DKIT

Reputation: 3481

There is not much you can do other than handle this gracefully. If density is null or 0 check for it and use a default value in this case.

Upvotes: 5

Murtaza Khursheed Hussain
Murtaza Khursheed Hussain

Reputation: 15336

Try the following , it has some issues device earliar than API level 4

DisplayMetrics metrics = getResources().getDisplayMetrics();
int densityDpi = (int)(metrics.density * 160f);

Upvotes: 1

Related Questions