Can I rely on statement the Application's Context
is not changing during application's lifecycle? What if I store a context
somewhere using singleton pattern and then use wherever I need?
They are both instances of Context, but the application instance is tied to the lifecycle of the application, while the Activity instance is tied to the lifecycle of an Activity. Thus, they have access to different information about the application environment.
Definition. it's the context of current state of the application/object. It lets newly-created objects understand what has been going on. Typically, you call it to get information regarding another part of your program (activity and package/application).
In order to call startActivity with application context, include the flag FLAG_ACTIVITY_NEW_TASK. Also think about changing the name from context to appContext so it is clear which context you expect.
To answer your second question first: If you need to store some state in a singleton, then you can use the Android Application
class and your Application
becomes your singleton (it is also a Context
). There would be no need to store it.
To the first question, as to whether the Context
can be changed at runtime: sort of related to your other question, I think we can figure that out by looking at ContextWrapper.attachBaseContext
:
protected void attachBaseContext(Context base) {
if (mBase != null) {
throw new IllegalStateException("Base context already set");
}
mBase = base;
}
So, yes, you can rely on it; it can't be changed, and if you try, it will throw an IllegalStateException
.
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