Best practice to pass Context to non-activity classes?

前端 未结 3 1480
暖寄归人
暖寄归人 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:06

    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);
    
    0 讨论(0)
  • 2020-12-02 08:17

    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.

    0 讨论(0)
  • 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;
    
    0 讨论(0)
提交回复
热议问题