Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lifetime of a static variable in Android

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.

like image 828
maysi Avatar asked Jul 27 '13 17:07

maysi


People also ask

What is the lifetime of a static variable?

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.

What is scope and lifetime of static variable?

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.

Are static variables permanent?

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.

What is the lifetime of static variable in Java?

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.


2 Answers

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

like image 200
T_V Avatar answered Sep 22 '22 03:09

T_V


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.

like image 23
JNL Avatar answered Sep 24 '22 03:09

JNL