Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 486
Rok Avatar asked Mar 28 '11 11:03

Rok


People also ask

What is the difference between getContext () getApplicationContext () getBaseContext () and this?

getApplicationContext() - Returns the context for all activities running in application. getBaseContext() - If you want to access Context from another context within application you can access. getContext() - Returns the context view only current running activity.

What is getBaseContext in Android?

getBaseContext() is the method of ContextWrapper . And ContextWrapper is, "Proxying implementation of Context that simply delegates all of its calls to another Context.

Why do we use getContext in Android?

getContext(): It returns the Context which is linked to the Activity from which it is called. This is useful when we want to call the Context from only the current running activity.


1 Answers

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.

like image 100
Karan Avatar answered Sep 21 '22 12:09

Karan