Best practice to pass Context to non-activity classes?

北战南征 提交于 2019-11-27 10:44:12
ET-CS

You can do that using ContextWrapper, as described here.

For example:

public class MyContextWrapper extends ContextWrapper {

    public MyContextWrapper(Context base) {
      super(base);
   }

    public void makeMyAppAwesome(){
        makeBaconAndEggsWithMeltedCheese(this);
    }
}

And call the non activity class like this from an Activity

new MyContextWrapper(this);

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;

You could also create a static instance reference to your MainActivity initialized in the onCreate() method

public class MainActivity extends AppCompatActivity {

    public static MainActivity mMainActivity;

    @Override
    private onCreate(Bundle savedInstanceState){

    //...

    mMainActivity = this;

    }
}

and call the context like this:

MainActivity.mMainActivity;

or write a method getInstanceOf() if it's clearer and/or you prefer using an accessor

MainActivity.getInstanceOf();

This strategy might provide you with some flexibility if you decide later that you would like to call an instance method contained in your main activity like so:

MainActivity.mMainActivity.myInstanceMethod();

Just a suggestion. Criticism is welcome and encouraged.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!