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.
The space for the static variable is allocated only one time and this is used for the entirety of the program. Once this variable is declared, it exists till the program executes. So, the lifetime of a static variable is the lifetime of the program.
A static variable stays in the memory and retains its value until the program execution ends irrespective of its scope. Scope is of four types: file, block, function and prototype scope. Lifetime is of three types: static, auto and dynamic lifetime.
static is a variable. The value can change, but the variable will persist throughout the execution of the program even if the variable is declared in a function.
A variable which is declared inside a class, outside all the blocks and is marked static is known as a class variable. The general scope of a class variable is throughout the class and the lifetime of a class variable is until the end of the program or as long as the class is loaded in memory.
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
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.
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