3

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.

Peter
  • 855
  • 2
  • 15
  • 35
  • Use context.getWindowManager().getDefaultDisplay().getMetrics(metrics); in your class. No need to extends Activity, you just have to initialize your class with Context param. – hardartcore Jan 09 '13 at 09:10
  • a trick that comes to mind is to put specific/different values in the values-hdpi and values-mdpi ... and use context.getResources to get it. – njzk2 Jan 09 '13 at 09:10
  • http://stackoverflow.com/questions/3166501/getting-the-screen-density-programmatically-in-android You dont need activity. – Leonidos Jan 09 '13 at 09:14
  • @Android-Developer i have implemented context but it shows "The method getWindowManager() is undefined for the type PopupNotificationGlobal" error. – Peter Jan 09 '13 at 09:23
  • show us the code you are using – hardartcore Jan 09 '13 at 09:31

1 Answers1

1

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);
Budius
  • 39,391
  • 16
  • 102
  • 144