35

If I put this in some activity class it works perfectly but, when I put it in my App class the method getWindowManager() can not be found. Is there some way to get the WindowManager in app class?

My app class is defined like this:

public class myApp extends Application {

and in on create method I have this:

DisplayMetrics dm = new DisplayMetrics(); 
getWindowManager().getDefaultDisplay().getMetrics(dm); 
int width = dm.widthPixels;
Sergey Glotov
  • 19,939
  • 11
  • 82
  • 96
Lukap
  • 30,736
  • 61
  • 153
  • 243

6 Answers6

72

Here, Context.getResource()

DisplayMetrics dm = getResources().getDisplayMetrics(); 
int densityDpi = dm.densityDpi;
Dmytro Danylyk
  • 19,482
  • 10
  • 60
  • 68
13

You can also try this:

WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
final DisplayMetrics displayMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
Thuong
  • 584
  • 5
  • 12
1

hope this will work for you

DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
int pxWidth = displayMetrics.widthPixels;
int pxHeight = displayMetrics.heightPixels;
shubham m
  • 11
  • 1
1

Without Context use -

Resources.getSystem().displayMetrics.widthPixels

With Context -

context?.resources?.displayMetrics?.widthPixels

Note : getWindowManager().getDefaultDisplay().getMetrics(dm); returns void in the new API.

Anoop M Maddasseri
  • 9,497
  • 3
  • 49
  • 68
1

Try this:

Display display = getWindowManager().getDefaultDisplay();
Log.e("", "" + display.getHeight() + " " + display.getWidth());
Sergey Glotov
  • 19,939
  • 11
  • 82
  • 96
Nitesh Khosla
  • 881
  • 8
  • 20
  • 3
    You can`t get getWindowManager in Application class. – Dmytro Danylyk Feb 02 '12 at 15:23
  • @NiteshKhosla could you point any doc showing us that Application class contains a method getWindowManager() ? I can't find it here: http://developer.android.com/reference/android/app/Application.html – rolgalan Dec 09 '15 at 15:01
0
final DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);

int width = dm.widthPixels;
int height = dm.heightPixels;

getWindow().setLayout((int) (width * .8), (int) (height * .5));