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

23,688

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.

Share:
23,688
Rok
Author by

Rok

Professional contract programmer with over 20 years experience - 15+ years in the games industry before also embracing other areas in the IT industry

Updated on July 09, 2022

Comments

  • Rok
    Rok almost 2 years

    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
    Rok over 13 years
    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?
  • Karan
    Karan over 13 years
    Look at this question : stackoverflow.com/questions/1026973/…
  • Rok
    Rok over 13 years
    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
  • Karan
    Karan over 13 years
    AFAIK, getBaseContext is only used before Activity onCreate is called. it is mostly used by ActivityThread.
  • JAL
    JAL over 13 years
    @Karan [this] does not work for me in an anonymous inner class, but getBaseContext does.
  • JBM
    JBM over 13 years
    @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.