Peter
Peter

Reputation: 859

How to check an Android device is HDPI or MDPI without extending Activity in class?

I have one class which does not extends any Activity. i want to find out that user uses LDPI,MDPI,HDPI or XHDPI screen using code. any idea? I have used DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); but it needs an Activity to extend. i want that without extending activity.

Upvotes: 3

Views: 1479

Answers (1)

Budius
Budius

Reputation: 39856

The problem with window manager is that it needs the activity context, read the name again window manager it manages stuff on the scree, ergo, the activity.

There're some different tricks you can try: You will need the context for this solution, but it doesn't have to be the activity context, it can be the application context. Actually, to be honest you'll need the resources, which can be accessed through the application context.

on your res folder create a value.xml for the all the parameters you want to find out:

  // res
      |- values-hdpi
             |- values.xml
      |- values-ldpi
              |- values.xml
      |- values-mdpi
              |- values.xml
      |- values-xhdpi
              |- values.xml

now on each one of those xml you put the following code:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <item name="is_ldpi" format="boolean" type="bool">true</item>
    <item name="is_hdpi" format="boolean" type="bool">false</item>
    <item name="is_mdpi" format="boolean" type="bool">false</item>
    <item name="is_xhdpi" format="boolean" type="bool">false</item>

</resources>

only changing the true or false as appropriate. now it's just as simple as calling:

  boolean is_hdpi = context.getResources().getBoolean(R.bool.is_hdpi);

Upvotes: 1

Related Questions