VanDir
VanDir

Reputation: 2030

Android - is there a way to get statically screen-resolution in pixel?

I tried with:

Resources.getSystem().getDisplayMetrics().widthPixels

and:

Resources.getSystem().getDisplayMetrics().heightPixels

but when my app goes in standby for a long time, on the wake up the two lines above return 0.

EDIT: I would like to place these values into static and final field.

Upvotes: 2

Views: 1645

Answers (2)

Paul de Vrieze
Paul de Vrieze

Reputation: 4918

You can use a static initializer. You do that by embedding a block in your class body:

class MyClass {
   public static final int width;
   public static final int height;

   static {
       DisplayMetrics dm = Resources.getSystem().getDisplayMetrics();
       width = dm.widthPixels;
       height = dm.heightPixels;
   }
}

Upvotes: 4

RyPope
RyPope

Reputation: 2725

Here is what I use to get screen dimensions, you can put the display, screenWidth and screenHeight variables as class variables (outside any methods ie. onCreate) if you want. Then you can put the if statement into onCreate or another method to initialize the variables.

    Display display = getWindowManager().getDefaultDisplay();
    int screenWidth, screenHeight;

    if (android.os.Build.VERSION.SDK_INT >= 13)
    {
        Point size = new Point();
        display.getSize(size);
        screenWidth = size.x;
        screenHeight = size.y;
    }
    else
    {
        screenWidth = display.getWidth();
        screenHeight = display.getHeight();
    }

Upvotes: 0

Related Questions