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

1

43

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?

Conjunctivitis answered 28/3, 2011 at 11:13 Comment(0)
U
13

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.

Uppity answered 28/3, 2011 at 11:19 Comment(6)
You may well have answered my question there but, just to clarify, which is the better/recommended way to create a new Intent. And can you give any examples of when to use getBaseContext?Conjunctivitis
Look at this question : #1027473Uppity
Thanks for getting back to me so quickly, Karan. That's one of the pages I've looked at. It mentions "don't use getBaseContext - just use the context you have". Obviously I value Diane's comments very much, but that doesn't explain why getBaseContext is used so often while creating intentsConjunctivitis
AFAIK, getBaseContext is only used before Activity onCreate is called. it is mostly used by ActivityThread.Uppity
@Uppity [this] does not work for me in an anonymous inner class, but getBaseContext does.Subclimax
@Subclimax because you have to qualify 'this' with your activity's class name, e.g. MyActivity.this. getBaseContext worked for you because your nested class didn't have such method so it was automatically resolved to your activity's class.Cinerary

© 2022 - 2024 — McMap. All rights reserved.