Lifetime of a static variable in Android

2019-01-18 09:40发布

问题:

when I declare and initialize a variable as static in my main activity and the activity gets destroyed. Can I still access the content of the variable?

For example to always access a AsyncTask which I store to this variable? What I want is to be able to access to it also after an orientation change.

回答1:

Static variables are associated with a class and they will live as long as the class is in the memory,and destroy when class gets unloaded (which very rarely happens).

In Android you have seen that when we close any application it does not close completely, It remains in the recent application stack, That you can see by holding in the home button(On Most Devices).

Android itself kicked out those recent app when the other app needs memory



回答2:

Can I still access the content of the variable?

Assuming that by "destroyed" you mean something like the user pressing BACK, yes.

Static data members live for the life of the process.

For example to always access a AsyncTask which I store to this variable? What I want is to be able to access to it also after an orientation change.

That is not an appropriate solution. Use a retained fragment, or use onRetainNonConfigurationInstance().



回答3:

If the process is killed then all static variables will be reinitialized to their default values.

This is mainly because, when you restart the application, a new instance is created and the static variable will be reinitialized.



回答4:

Android has concept of empty process which says your app may not be removed from memory if it is frequently used by the user even if all its components are destroyed(activities, services, and/or broadcast receivers) , in which case static variables will not be cleared of completely.

Application class is the best way to share some temporary variables between components because application class will be created properly on application startup time and will be cleared of once user exits app.

Reference: http://skillgun.com/question/9849/android-provab/face-to-face-round/if-i-close-the-application-will-it-destroy-all-the-static-variables



回答5:

Static variables or static blocks are not associated with object. These are class level variable not object associated. If we destroy object, static variable will not destroy which is defined in same class. Static variable initialize once in memory.

so when we close app objects destroy but static variable not destroy. But when we clear app then class destroy and so static variable also. Sometime android kill class due to free memory space in that case static variable destroy.