Is it wrong to use an application context instance?

From my point of view, the application in Android is singleton (correct me if I am wrong), and we always have only one instance of the application.

So, from this point of view, is it inconvenient to keep the application context in my Application class? Could this 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 for this is access to global classes, such as the PreferencesManager, which basically have static methods that always need context. Therefore, instead of passing it each time (or even storing it in an instance, which may be bad), I thought about keeping the application context. What disadvantages do I not see?

+8
source share
1 answer

Is it really inconvenient to save the Context application in my application class?

This is the smell of code.

Could this lead to a massive memory leak?

Having a static data member will not cause a massive memory leak. Whether your excessive use of the Application object Application massive memory leak depends on where and how you use it.

What are the flaws that I do not see?

Not all Context are created equal. Generally speaking, use Application when you know , namely, why the Application context is needed , and not for everything.

DoubleEncore's Dave Smith has an amazing blog post that describes the differences between Context types and when to use one over the other.

+10
source

Source: https://habr.com/ru/post/959084/


All Articles