Diffinitive rules for using Android's getBaseContext, getApplicationContext or using an Activity's "this"

Rok picture Rok · Mar 28, 2011 · Viewed 23.6k times · Source

I've googled this question a lot and have found many differing recommendations on when to use getBaseContext, getApplicationContext or an Activity's own this pointer.

Three rules that come up often and seem to make a lot of sense are -

  1. For a long-lived reference to a context activity getApplicationContext should be used as this exists as long as your application exists
  2. For contexts whose life-cycles are bound to their activities, their own activity context (this) should be used
  3. Store context pointers statically only with great caution (and, if possible, not at all)

Assuming these are correct, what is the use of getBaseContext?

I've seen a great many examples where new intents are created using -

Intent intent = new Intent(getBaseContext(), myClass.class);

As opposed to -

Intent intent = new Intent(this, myClass.class);

Which is the correct, or recommended, method and why?

Answer

Karan picture Karan · Mar 28, 2011

The getBaseContext() is the method of ContextWrapper. And ContextWrapper is, "Proxying implementation of Context that simply delegates all of its calls to another Context. Can be subclassed to modify behavior without changing the original Context." (as per javadocs)

So this is used to delegate the calls to another context.