Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get screen display metrics in application class

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;
like image 328
Lukap Avatar asked Feb 02 '12 14:02

Lukap


5 Answers

Here, Context.getResource()

DisplayMetrics dm = getResources().getDisplayMetrics(); 
int densityDpi = dm.densityDpi;
like image 196
Dmytro Danylyk Avatar answered Oct 20 '22 15:10

Dmytro Danylyk


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;
like image 37
Thuong Avatar answered Oct 20 '22 16:10

Thuong


Try this:

Display display = getWindowManager().getDefaultDisplay();
Log.e("", "" + display.getHeight() + " " + display.getWidth());
like image 1
Nitesh Khosla Avatar answered Oct 12 '22 13:10

Nitesh Khosla


hope this will work for you

DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
int pxWidth = displayMetrics.widthPixels;
int pxHeight = displayMetrics.heightPixels;
like image 1
shubham m Avatar answered Oct 20 '22 16:10

shubham m


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.

like image 1
Anoop M Maddasseri Avatar answered Oct 20 '22 14:10

Anoop M Maddasseri