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 -
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?
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.
getBaseContext() is the method of ContextWrapper . And ContextWrapper is, "Proxying implementation of Context that simply delegates all of its calls to another Context.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With