Saturday, August 6, 2011

Exiting the Android Application Safely

Myblog.doc

Android don't have a proper option to exit the complete application with a single line code. The only option we can do is, just calling the finish in all the activities. Even after calling finish(), the static variables wont go, will be there even after restarting the application. In order to exit the application completely we have to follow the bottom trick. We should call “addActivityInstance” method from all the activities. This method will save all the activitiy instances in _list_screens which is nothing but a ArrayList<Activity>. Whenevr you want to exit the application, just call the method “closeAllScreens”. Where we just called the finish of all the activities and after that we are calling “android.os.Process.killProcess” to kill the whole process including all the static data.

public static void addActivityInstance(Activity _activity)

{

if( _list_screens == null )

{

_list_screens = new ArrayList<Activity>();

}

_list_screens.add(_activity);

}

public static void closeAllScreens()

{

if(_list_screens!=null)

for(int i=0;i<_list_screens.size();i++)

if(_list_screens.get(i)!=null)

_list_screens.get(i).finish();

try{

android.os.Process.killProcess(android.os.Process.myPid());

}catch(Exception e){

}

}

No comments:

Post a Comment