Is it a bad practice to hold application Context instance?

时光总嘲笑我的痴心妄想 提交于 2019-11-30 02:54:34

问题


From my understanding, Application in Android is a singleton (correct me if I'm wrong) and we always have just one application Context instance.

So, from this perspective, is it a bad practice to save the application Context in my Application class? Can it lead to a massive memory leak?

Here is an example:

public class MyApp extends Application {
    private static Context appContext = null; // <-- here is the thing!

    @Override
    public void onCreate() {
        appContext = this;
    }

    public static Context getApplicationContextSingleton () {
        return MyApp.appContext;
    }
}

The reason to do this is globally accessed classes, like PreferencesManager, that mostly have static methods always need a context. So, instead of passing it everytime (or even storing it in an instance, which can be bad), I thought about storing the app context. What are the drawbacks I'm not seeing?


回答1:


is it a bad practice to save the application Context in my Application class?

It is a code smell.

Can it lead to a massive memory leak?

Having the static data member will not lead to a massive memory leak. Whether your over-use of the Application object will lead to a massive memory leak depends upon where and how you use it.

What are the drawbacks I'm not seeing?

Not all Contexts are created equal. Generally speaking, only use Application when you know specifically why you need the Application context, not for everything.

Dave Smith of DoubleEncore has an awesome blog post covering the differences between types of Context and when to use one over another.



来源:https://stackoverflow.com/questions/20301989/is-it-a-bad-practice-to-hold-application-context-instance

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