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).