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 –
- For a long-lived reference to a
context activity
getApplicationContext should be used
as this exists as long as your
application exists - For contexts whose life-cycles are
bound to their activities, their own
activity context (this) should be
used - 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?
Best Answer
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.