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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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?
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
AFAIK, getBaseContext is only used before Activity onCreate is called. it is mostly used by ActivityThread.
@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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.