Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a bad practice to hold application Context instance?

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?

like image 624
Bolhoso Avatar asked Nov 30 '13 15:11

Bolhoso


1 Answers

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.

like image 109
CommonsWare Avatar answered Sep 21 '22 03:09

CommonsWare