Singleton with context in Android

I want to create a Singleton class that will be available to all points of my application. The problem is that this class will need context for its operations.

I don’t need to recreate a singleton in every action because it loses all meaning, so I thought about creating it in my MainActivity, using the init method, in which I pass the context as an argument. From now on, my singleton will be useful, but I think this is a bad design, because my MainActivity link will always be kept, and therefore I may run into memory leaks.

I'm here?

+7
source share
1 answer

You are right to not keep the main activity context in singleton due to memory leaks. If you need a constant context inside your singleton, use getApplicationContext (). It can be safely saved. Note that this context is not applicable to most gui-related functions. In rare cases, you need an activity level context inside a singleton, pass the call activity context to the singleton method without saving

+11
source

All Articles