Singleton with context in Android
I want to create a Singleton class that will be callable from all points in my application. The problem is this class will need a context for its operations.
I don’t want to have to recreate the singleton in every activity because that way it looses all sense, so I thought about creating it in my MainActivity, with an init method where I pass the context as an argument. From that point on, my Singleton would be useable, but I think this is bad design because that way my MainActivity reference will always be held and thus I might run into memory leaks.
Am I right here?
One Solution collect form web for “Singleton with context in Android”
You are right not to save main activity context into the singleton because of memory leaks. If you need constant context inside your singleton, use getApplicationContext(). This can be safely saved. Note though that this context is not useable for most gui-related functions. In rare cases you need activity level context inside singleton, pass calling activity context to singleton’s method without saving