Maintaining global Application state

SDK Version: 

As a possible solutions mentioned in previous article Leaving an Android application the Application object can come handy. If you want to store data, global variables that needs to be accessed from everywhere in the application, from multiple Activities, in other words is you want to maintain a global "state" of the whole application the Application object can help.

For this we must make a class which extends the class add our own methods to it, and define this class in the AndroidManifest.xml as below:

  1. An example for the Application class:
  3. public class HelloApplication extends Application {
  4.         private int globalVariable=1;
  6.         public int getGlobalVariable() {
  7.                 return globalVariable;
  8.         }
  10.         public void setGlobalVariable(int globalVariable) {
  11.                 this.globalVariable = globalVariable;
  12.         }
  13.         @Override
  14.         public void onCreate() {
  15.                 //reinitialize variable
  16.         }
  17. }

After this in any of the Activities you can read and write the global variable like this:

  1. ((HelloApplication)getApplication()).setGlobalVariable(10);
  2. int valiable=((HelloApplication)getApplication()).getGlobalVariable();

The Application object is not destroyed until there are any undestroyed Activity in the application. Even when the whole application is wiped from memory you can reinitialize the variable in the onCreate method if needed.
You can try the same data storing, for example with a simple object with static field and methods, like below, it is a less elegant method, and if the reinitialization is needed after the whole application is killed you must implement the reinitialization in each activity.

  1. public class DataStoreClass {
  2.         private static int globalVariable=1;
  4.         public static int getGlobalVariable() {
  5.                 return globalVariable;
  6.         }
  8.         public static void setGlobalVariable(int newGlobalVariable) {
  9.                 globalVariable = newGlobalVariable;
  10.         }
  11. }

To test how these objects store and reload values when the application is killed try the following:

- leave one of the applications activities with home button
- kill the application with a "task killer" application (you can find a lot on the market)
- by longpressing home button return to the killed application

Normally only the activity you last seen is restored this way. So if you want to restore some application level state, implement the application object's onCreate method, which is called even before the activity.

See Android Application class for more.