getApplicationContext(), getBaseContext(), getApplication(), getParent()
getApplicationContext()
Application context is associated with the Application and will always be the same throughout the life cycle.
getBasecontext()
should not be used, just use Context
instead of it which is associated with the activity and can be destroyed when the activity is destroyed.
difference and when to use getApplication(), getApplicationContext(), getBaseContext() and someClass.this
Toast and Intent, both requires reference to context. And getApplication, getApplicationContext, LoginActivity.this and getBaseContext, they all offer reference to the context.
Now the thing confuses is the declaration of different contexts and their specific-usage. To make things simple, you should count two types of context available in the Android framework.
- Application Context
- Activity Context
Application context is attached to the application's life-cycle and will always be same throughout the life of application. So if you are using Toast, you can use application context or even activity context (both) because a toast can be raised from anywhere with in your application and is not attached to a window.
Activity context is attached to the Activity's life-cycle and can be destroyed if the activity's onDestroy()
is raised. If you want to launch a new activity, you must need to use activity's context in its Intent so that the new launching activity is connected to the current activity (in terms of activity stack). However, you may use application's context too to launch a new activity but then you need to set flag Intent.FLAG_ACTIVITY_NEW_TASK
in intent to treat it as a new task.
Now referring to your cases:
LoginActivity.this
though its referring to your own class which extends Activity class but the base class (Activity) also extends Context class, so it can be used to offer activity context.
getApplication()
though its referring to Application object but the Application class extends Context class, so it can be used to offer application context.
getApplicationContext()
offers application context.
getBaseContext()
offers activity context.
Tips: Whenever you need to manipulate
Views
then go for
Activity-Context, else Application-Context would be enough.
Diffinitive rules for using Android's getBaseContext, getApplicationContext or using an Activity's this
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.
getApplication() vs. getApplicationContext()
Very interesting question. I think it's mainly a semantic meaning, and may also be due to historical reasons.
Although in current Android Activity and Service implementations, getApplication()
and getApplicationContext()
return the same object, there is no guarantee that this will always be the case (for example, in a specific vendor implementation).
So if you want the Application class you registered in the Manifest, you should never call getApplicationContext()
and cast it to your application, because it may not be the application instance (which you obviously experienced with the test framework).
Why does getApplicationContext()
exist in the first place ?
getApplication()
is only available in the Activity class and the Service class, whereas getApplicationContext()
is declared in the Context class.
That actually means one thing : when writing code in a broadcast receiver, which is not a context but is given a context in its onReceive method, you can only call getApplicationContext()
. Which also means that you are not guaranteed to have access to your application in a BroadcastReceiver.
When looking at the Android code, you see that when attached, an activity receives a base context and an application, and those are different parameters. getApplicationContext()
delegates it's call to baseContext.getApplicationContext()
.
One more thing : the documentation says that it most cases, you shouldn't need to subclass Application:
There is normally no need to subclass
Application
. In most situation,
static singletons can provide the same functionality in a more modular
way. If your singleton needs a global context (for example to register
broadcast receivers), the function to retrieve it can be given a
Context
which internally usesContext.getApplicationContext()
when
first constructing the singleton.
I know this is not an exact and precise answer, but still, does that answer your question?
Android: why must use getBaseContext() instead of this
getApplicationContext ()
returns the application context of the entire application life cycle,when application will destroy then it will destroy also.this
the context returns the current context of the activity, belong to the activity, the activity is destroyed then it will destroy also.but in your case it will refers to theSpinner
instance because we are using this withinonItemSelected(AdapterView<?>arg0, View arg1, int arg2, long arg3)
method which is fromSpinner
class andSpinner
inherit this method fromAdapterView.OnItemSelectedListener
interfacegetBaseContext()
is the method ofContextWrapper
. AndContextWrapper
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)..
and in your case :Spinner
class is not subclass of Context
or ContextWrapper
class*
Toast.makeText(getBaseContext(),"SELECTED", Toast.LENGTH_SHORT).show();
means getBaseContext()
is method of ContextWrapper
and ContextWrapper
is Proxying implementation of Context
so indirectly we are passing an Context Class Object.
or we can also pass 'Activity.this' because Activity
class is subclass of ContextWrapper
class .
if you go with android documention then this method require an Context class object:public static Toast makeText (Context context, int resId, int duration)
so we are not able to pass an activity or class context means this
to Toast.makeText
which don't have a subclass of either Context
or ContextWrapper
class.
Logic Behind Android Context
Context is the main base class in Android Library. Every class extends it. It is just like Object class in Java Library.
There are different ways of getting Context
- getApplicationContext() : It points to application's context.
- getContext() : It points to current running component.
- getBaseContext() : It 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).
- this : It points to current Activity/BroardcastReceiver or Service's context.
- getActivity() : It points to current running activity's Context.
What's the difference between the various methods to get an Android Context?
I agree that documentation is sparse when it comes to Contexts in Android, but you can piece together a few facts from various sources.
This blog post on the official Google Android developers blog was written mostly to help address memory leaks, but provides some good information about contexts as well:
In a regular Android application, you
usually have two kinds of Context,
Activity and Application.
Reading the article a little bit further tells about the difference between the two and when you might want to consider using the application Context (Activity.getApplicationContext()
) rather than using the Activity context this
). Basically the Application context is associated with the Application and will always be the same throughout the life cycle of your app, where as the Activity context is associated with the activity and could possibly be destroyed many times as the activity is destroyed during screen orientation changes and such.
I couldn't find really anything about when to use getBaseContext() other than a post from Dianne Hackborn, one of the Google engineers working on the Android SDK:
Don't use getBaseContext(), just use
the Context you have.
That was from a post on the android-developers newsgroup, you may want to consider asking your question there as well, because a handful of the people working on Android actual monitor that newsgroup and answer questions.
So overall it seems preferable to use the global application context when possible.
Obtain application from ReceiverRestrictedContext as if getApplication was used (not getApplicationContext)
You should definately use some persistent storage, for example SharedPreferences
.
A reason behind this - your application instance can be killed by Android OS almost at any time (while your app in background). So, you can't rely on your variables, even static
. You should save your state in persistent storage instead.
Related Topics
Android: Getting "Manifest Merger Failed" Error After Updating to a New Version of Gradle
Android Background Image Memory Usage
Start Activity Inside Onreceive Broadcastreceiver
How to Make Android Apps Which Support Both 32-Bit and 64-Bit Architecture
Overlap Scrolling View with Appbarlayout
How to Use Autocompletetextview and Populate It with Data from a Web API
Select + Copy Text in a Textview
Android How to Turn on Do Not Disturb (Dnd) Programmatically
How to Represent a "Many to Many" Relation with Android Room When Column Names Are Same
Lazy Load Images on Listview in Android(Beginner Level)
Get Cursor Position in Android in Edit Text
Android: Retrieve Contact Name from Phone Number
Why Mediaplayer Throws Not Present Error When Creating Instance of It
Actionbaractivity Cannot Resolve a Symbol
How to Set Up Dagger Dependency Injection from Scratch in Android Project