Application Class: Application-wide data sharing #android

Read Time 2 minutes
There are cases when we need to share same data to all application components and we want anyone to be able to update that data. Example of this use-case can be application settings e.g shared preferences.

Application class instance is initiated before any other component and remained there till the application terminate. You can think of application class as parent of all other application component (activities, services and broadcast receivers).

We can use application class as a global space available for all application components.We can get application object with getApplication() and call its public methods and variables where ever we like.

Lets see how can we create application class and use it:


1- Create new java class lets say MyApplication and extend it from Application

public class MyApplication extends Application {

int myGlobal;

@Override
public void onTerminate() {
// TODO Auto-generated method stub 
super.onTerminate();

@Override
public void onCreate() {

// TODO Auto-generated method stub super.onCreate();

myGlobal=0;

Log.d("sohail","MyApplication created, calling initSingleton");
}

public int getGlobal {

// TODO Auto-generated method stub
return myGlobal;
}

public void setGlobal(int in){

myGlobal=in;

}

}


2. Set application name = MyApplication in manifest.xml. like


<application

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:name=".MyApplication"

>
.....
.....

 

3- Now we can set and get our Global variable from any activity, service or broacast receiver like:

MyApplication appObj= (MyApplication) getApplication(); 

appObj.setGlobal(123);

appObj.getGlobal();


There are various useful methods which can be override in application class e.g

onConfigurationChanged() : called when device configuration changes while this application is running.

 onLowMemory(): “called when system is going in low memory and applications may get killed”. We can override this function to release application resources and gracefully terminate the application before system terminate it.

Application class is good place for application centric data sharing, however normal intents should be used to pass data between application components and one should not abuse this space to make android a procedural language.

Note: Android application are not actually terminated when user close/exit the app (calling finish()), rather android System push the application on stack and decides itself when to actually terminate (kill process) the application. So Do not rely on application OnCreate and OnTerminate methods to initialize or de-initialize any variables. If application is not actually terminated by System, neither OnTerminate will be called nor OnCreate (on Second launch).

Leave a Comment

Your email address will not be published. Required fields are marked *