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?
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 Context
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With