I have a Generic Pool that i am making here:
public class FruitPool extends GenericPool {
// ======================================================
Despite the fact there is an accepted answer here, I'm posting another answer. The reasoning for this is the following. Passing contexts is not always a good idea imho, because in some cases (such as applied libraries, for example) contexts should not build additional and unnecessary dependencies from an application. The code is simple:
DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
It provides a solution for cases when known limitations of this method are not important for a developer. According to Android documentation:
getSystem()
returns a global shared Resources object that provides access to only system resources (no application resources), and is not configured for the current screen (can not use dimension units, does not change based on orientation, etc).
Anyway, all fields of DisplayMetrics
are filled in with meaningful information. In my case, it was DPI which I was after. And the method provides me with DPI without a context.
Here's another way to get the display metrics that is configured for the current screen.
final DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
The simplest thing would be to pass a Context to the FruitPool constructor. It could then retrieve the display metrics by calling Context.getWindowManager()
. (If you want to run that code outside the constructor, save context.getApplicationContext()
, in case it was passed an Activity context.)
EDIT: If you adopt this approach and are passing an Activity
to the FruitPool
object, and the lifetime of the FruitPool
object might exceed the lifetime of the activity, then you must not keep a reference to the activity. You should instead keep a reference to context.getApplicationContext()
. Since getWindowManager()
is only defined for an Activity
, you can instead use this expression to obtain the WindowManager
:
(WindowManager) context.getSystemService(Context.WINDOW_SERVICE)
Here is the api I have written to get the screen width, you need a context to get the window system service. Similarly you can get the height.
int getWindowWidth() {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return size.x;
}