Needing Context in non-Activity classes

前端 未结 7 1669
轻奢々
轻奢々 2020-12-14 06:10

I have some classes within my application that need to call Android functions that require the Context as a parameter. I don\'t have it as the class is not a subclass of the

相关标签:
7条回答
  • 2020-12-14 06:36

    I'm pretty much always going with a constructor parameter approach. I pass it in the instantiation and keep a private reference in the instantiated class.

    You have to think about one important thing. If the class you pass the Context will exist longer than the Activity instantiating it then you should use the application context. If that class is doing UI stuff you will need an activity context.

    Make sure that the class you are passing an activity context to won't last longer than the Activity or you'll leak the entire activity.

    If you don't do UI stuff then go with the application context.

    0 讨论(0)
  • 2020-12-14 06:39

    I've answered this question here also.

    You can do that using ContextWrapper, as described here.

    For example:

    public class MyContextWrapper extends ContextWrapper {
    
        public MyContextWrapper(Context base) {
          super(base);
       }
    
    }
    

    and use that class as it were Context

    0 讨论(0)
  • 2020-12-14 06:46

    Pass it at class instantiation and keep it.

    One typical example is when you create a db helper. See this link

    0 讨论(0)
  • 2020-12-14 06:47

    It depends on the role of the class. But anyway pass ApplicationContext but not Activity one. If you pass Activity context gc can't remove it from the memory when after you don't need activity anymore. But application context is used while application was not finished by OS.Refer Avoid Memory Leaks

    0 讨论(0)
  • 2020-12-14 06:47

    I pass it as a parameter, i think its de best form to do it

    0 讨论(0)
  • 2020-12-14 06:56

    Pass it as a parameter. Or better yet, get the application context to avoid memory leaks.

    public class Example {
        protected Context context;
    
        public Example(Context context){
            this.context = context.getApplicationContext();
        }
    }
    
    0 讨论(0)
提交回复
热议问题