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?

Rok
  • 2,568
  • 4
  • 26
  • 28

1 Answers1

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.

Karan
  • 12,724
  • 6
  • 40
  • 33
  • 4
    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? – Rok Mar 28 '11 at 11:26
  • Look at this question : http://stackoverflow.com/questions/1026973/android-whats-the-difference-between-the-various-methods-to-get-a-context – Karan Mar 28 '11 at 11:32
  • 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 intents – Rok Mar 28 '11 at 11:40
  • AFAIK, getBaseContext is only used before Activity onCreate is called. it is mostly used by ActivityThread. – Karan Mar 28 '11 at 11:51
  • @Karan [this] does not work for me in an anonymous inner class, but getBaseContext does. – JAL Mar 28 '11 at 19:40
  • 6
    @JAL 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. – JBM Mar 30 '11 at 12:18