Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Application Context be changed during application lifecycle?

Tags:

android

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?

like image 877
Eugene Avatar asked Jul 15 '12 08:07

Eugene


People also ask

What is the actual differences between A activity context and application context?

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.

What is application context in mobile application development?

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).

Can you start activity from application context?

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.


1 Answers

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.

like image 91
Jon O Avatar answered Oct 01 '22 11:10

Jon O