Best practice to pass Context to non-activity classes?

前端 未结 3 1489
暖寄归人
暖寄归人 2020-12-02 07:51

So, my first major application is almost coded and I\'m doing optimizations on my code. The app works fine, but I\'m not sure about my way of passing the context to other cl

3条回答
  •  时光说笑
    2020-12-02 08:18

    It is usually in your best interest to just pass the current context at the moment it is needed. Storing it in a member variable will likely lead to leaked memory, and start causing issues as you build out more Activities and Services in your app.

    public void iNeedContext(Context context) {...
    

    Also, in any class that has context, I'd recommend making a member variable for readability and searchability, rather than directly passing or (ClassName.)this. For example in MainActivity.java:

    Context mContext = MainActivity.this;
    Activity mActivity = MainActivity.this;
    

提交回复
热议问题