Reputation: 7117
I got the Screen Size by using the following from a activity,
Display display = getWindowManager().getDefaultDisplay();
But the same thing is not working from a service (for obvious reasons, i know!) but i desperately need to get the display size from a service. Can some1 please explain me any other way for getting the ScreenSize??
So i guess as far as i see, there is no way we can get the Screen size from the service. Wat i have done as of now is to start the activity atleast 1ce by default and store the actual screen size in pixels in the shared preferences. I use the shared preferences to get the value when the service starts.
Is this the only way it'll work out??? Cant we by any means get the screen size from the service??
Upvotes: 34
Views: 18955
Reputation: 144
Since getDefaultDisplay()
now is depricated, this works (kotlin):
val window = getSystemService(WINDOW_SERVICE) as WindowManager
val width: Int = window.currentWindowMetrics.bounds.height()
val height: Int = window.currentWindowMetrics.bounds.width()
Upvotes: 0
Reputation: 1550
Try this:
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
DisplayMetrics displayMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
Upvotes: -1
Reputation: 1344
there totally is a way to obtain it from a service:
WindowManager window = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Display display = window.getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
Upvotes: 82
Reputation: 21582
If you are starting the service on boot (or automatically any other way) then shared prefs is a good way. However, if the only way you start the service is thru calling Context.startService() then it actually makes more sense to just place an extra in the Intent that you use to start the service.
Upvotes: 0
Reputation: 181
It worked for me!
DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
You only needed to get the context.
Upvotes: 18