Which android context should i use in singletons?

Viewed 1546

When i write my singletons i always provide a getInstance(Context) method in the singleton Class. But which context object should i pass to that method: Activity context (the this in the Activity class) or the Application Context? And what differences it would make if i pass one or another?

To illustrate, i have a database manager that have the getInstance method defined like:

public static Database getInstance(Context context) {
    if (Database.instance == null)
        instance = new Database(context);
    return instance;
}

And the constructor looks like:

private Database(Context context) { 
    this.sqLiteDatabase = context.openOrCreateDatabase(...);
}
1 Answers

What you pass in does not matter much. What you use should be the Application context:

public static Database getInstance(Context context) {
    if (Database.instance == null)
        instance = new Database(context.getApplicationContext());
    return instance;
}

Now, if you want to force the caller to supply the Application, you could do that:

public static Database getInstance(Application context) {
    if (Database.instance == null)
        instance = new Database(context);
    return instance;
}

Personally, I like to consider that an implementation detail, hidden by the API.

The Application is a global object, created when the process is created. Therefore it is "pre-leaked", in effect. You cannot leak it further. Other types of Context (e.g., Activity), referenced from some singleton, may result in memory leaks.

See Dave Smith's epic blog post on the roles of different Context objects for more.

Related