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 t
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.
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
They stay even if you close the app with pressing back button as long as you don't clear them from the recent apps.Proof : well I've tested it you can too it's easy ;).
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().
A static variable is associated with the lifecycle of class. Once an activity is destroyed than that static variable will also be cleaned up.
If you still want to access that variable you have 2 options:-
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.