Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 422
MichelReap Avatar asked May 18 '13 15:05

MichelReap


People also ask

How to get context in singleton class in Android?

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.

What is a singleton in Android?

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.

Are Android services singletons?

Finally, Service in Android is a singleton. There is only one instance of each service in the system.

What is a singleton in programming?

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.


2 Answers

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

like image 51
alexei burmistrov Avatar answered Nov 08 '22 22:11

alexei burmistrov


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;
}
like image 22
Emerson Barcellos Avatar answered Nov 08 '22 23:11

Emerson Barcellos