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
  • 20,200
  • 11
  • 84
  • 98
Lukap
  • 31,523
  • 64
  • 157
  • 244

6 Answers6

74

Here, Context.getResource()

DisplayMetrics dm = getResources().getDisplayMetrics(); 
int densityDpi = dm.densityDpi;
Dmytro Danylyk
  • 19,684
  • 11
  • 62
  • 68
12

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
  • 602
  • 6
  • 13
3

hope this will work for you

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

With Context -

context.resources.displayMetrics.widthPixels

Without Context use -

Resources.getSystem().displayMetrics.widthPixels // but this doesn't work well on foldables

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

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
Anoop M Maddasseri
  • 10,213
  • 3
  • 52
  • 73
0

Try this:

Display display = getWindowManager().getDefaultDisplay();
Log.e("", "" + display.getHeight() + " " + display.getWidth());
Sergey Glotov
  • 20,200
  • 11
  • 84
  • 98
Nitesh Khosla
  • 875
  • 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
-1
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));