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?
If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context. getApplicationContext() when first constructing the singleton.
The Singleton Pattern is a software design pattern that restricts the instantiation of a class to just “one” instance. It is used in Android Applications when an item needs to be created just once and used across the board. The main reason for this is that repeatedly creating these objects, uses up system resources.
Finally, Service in Android is a singleton. There is only one instance of each service in the system.
A singleton is a class that allows only a single instance of itself to be created and gives access to that created instance. It contains static variables that can accommodate unique and private instances of itself. It is used in scenarios when a user wants to restrict instantiation of a class to only one object.
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
Try the WeakReference<Context>
:
private WeakReference<Context> context;
public static synchronized OsControler getInstance(Context context, int numero) {
if (mInstance == null) {
mInstance = new OsControler(context, numero);
}
return mInstance;
}
private OsControler(Context context, int numero) {
this.context = new WeakReference<>(context);
NUMERO = numero;
}
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