How to get Screen metrics outside an Activity?

后端 未结 4 1663
名媛妹妹
名媛妹妹 2021-02-04 01:59

I have a Generic Pool that i am making here:

public class FruitPool extends GenericPool {
// ======================================================         


        
4条回答
  •  无人共我
    2021-02-04 02:43

    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)
    

提交回复
热议问题