Can Application Context be changed during application lifecycle?
Application is a singleton and I don't know of a way to bypass that without changing core.
However there is a possibility to encounter 2 instances of an Application object if your code starts another process. One example would be starting a remote service; this will create another process which will create it's own instance of the application object.
http://developer.android.com/reference/android/app/Service.html#RemoteMessengerServiceSample
To avoid confusion you must communicate between the remote service and the rest of the app using one of the Parcelable or Serializable android options:
Message - Handler Intent Bundle Intent putExtra
or create one of your own
Yes you can rely on that the context is not changed during application life cycle!
Google say so in the Application class overview.
I think it will be perfect for your case.
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
.
Android Application
class IS your singleton for storing information that should be tracked through applications lifecycle phases. You can checkout this class' description in the manual - http://developer.android.com/reference/android/app/Application.html