Reputation: 1861
I'm in the process of porting an iOS project to Android. The iOS project makes use of several key singletons to provide global resources for the application, such as a database and an set of web services. Many of these singletons use resources such as files, network, or shared preferences.
I'm running into a lot of problems trying to port this to Android, because I often require a "Context" object when I am writing singleton code that is not part of an Activity. I can usually pass in a Context when I first construct the singleton, but I have heard that I should not store this as a member variable because it could cause memory leaks.
What is the best way to deal with this issue?
Upvotes: 1
Views: 1345
Reputation: 155
If you HAVE to keep singletons in app, you can pass context
to method of singleton which uses context
In MySingleton.java
public class MySingleton {
//private instance, private constructor and getInstance() goes here
public void doSomething(Context context, int foo, int bar) {
//Use context
}
}
Calling from Activity/Service
MySingleton.getInstance().doSomething(this, 1, 2);
Calling from Fragments
MySingleton.getInstance().doSomething(getActivity, 1, 2);
If you can afford changing architecture, please steer clear of singletons. You can use dependency injection as an alternative. This is how you do it.
Upvotes: 1
Reputation: 1006869
I can usually pass in a Context when I first construct the singleton, but I have heard that I should not store this as a member variable because it could cause memory leaks.
Use the Application
object, which you get from getApplication()
(on Activity
) or getApplicationContext()
(on any other Context
). This is itself a singleton, and so it is pre-leaked and cannot be leaked further.
Note, though that the Application
object is not a suitable Context
for anything closely tied to the UI (e.g., inflating layouts); such things should not be in singletons in general.
See Dave Smith's epic blog post on the roles of different types of Context
for more details.
Upvotes: 1