Skip to content Skip to sidebar Skip to footer

How To Kill All Activities In Android Application?

I want to close total application in android when i click on 'NO' Button in Dialog. i have used the following code. protected Dialog onCreateDialog(int id) { switch (id) { case

Solution 1:

Let's do this a bit simply.Suppose you have a class Constants.java where you put all your reused constants of the application.In that declare an activity stack like this:

publicstatic ArrayList<WeakReference<Activity>> activity_stack=new ArrayList<WeakReference<Activity>>();
/**
 * Add the activity as weak reference to activity stack.
 * @param act
 */publicstaticvoid addToActivityStack(Activity act)
{
    WeakReference<Activity> ref = newWeakReference<Activity>(act);
    activity_stack.add(ref);

}

And whenever you create some activity,in it's onCreate at the last line you put something like this:

Constants.addToActivityStack(this);

Now define a method like following in Constants.java

/**
 * Kill all the activities on activity stack except act.
 * To kill all the passed parameter should be null.
 */publicstaticvoidkillAllExcept(Activity act)
{
    for(WeakReference<Activity> ref:Global.activity_stack)
    {
        if(ref != null && ref.get() != null)
        {
            if(act != null && ref.get().equals(act)) 
            {
                continue;//dont finish this up.
            }
            ref.get().finish();
        }
    }
    activity_stack.clear();//but clear all the activity references
}

Now,when you need to finish up all your activities,just call Constants.killAllExcept(null) or Constants.killAllExcept(this) if you want to keep this activity.

This method is convenient when you want to keep one activity but the others/if you want you can finish them up all.

Solution 2:

you can call the finish() method on your activity and call the homescreen (simulate the homebutton) programmatically like this:

privatevoidendApplication() {
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.addCategory(Intent.CATEGORY_HOME);
    startActivity(intent);
}

Solution 3:

You should NOT kill your applications. You should let the ActivityManager handle that.

Specifically if you want the user to leave your application, then send them home via an Intent to the homescreen.

Solution 4:

You should't call onDestroy() yourself.. instead call finish() to close the Activity..

Calling Activity life cycle method by yourself is bad practice (Don't know if its possible). They are handled by Android OS itself..

Solution 5:

It should be highlighted that the suggested Constants.killAll() approach is bad design and will if used incorrectly lead to memory leaks. Preserving static reference to an activity is the most common cause of memory leaks in Android.

Hope this helps.

Post a Comment for "How To Kill All Activities In Android Application?"