Method for Android to exit the application completely

  • 2020-08-22 22:46:32
  • OfStack

This article illustrates how Android can exit the application completely. Share to everybody for everybody reference. The details are as follows:

In Android, if you want to exit the Android program, 1 kind is called finish (), System. exit. (0), android os. Process. killProcess (android. os. Process. myPid () method to implement exit the program function, but in actual development, and can't achieve complete withdrawal from the effect of application, . This is because the call finish (), System exit. (0), android os. Process. killProcess (android. os. Process. myPid ()) can kill the current activity, cannot kill all activity, perfect in order to achieve this effect, then through a case:

1. Use singleton mode to create 1 Activity management object, in which there is 1 Activity container (to implement its own processing, using LinkedList, etc.) specially responsible for storing each newly opened Activity, and easy to understand, easy to operate, very good!

The MyApplication class (stores every Activity and closes all Activity operations


package com.hrtx.dd.activity;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import android.app.Application;
public class MyApplication extends Application {
  private List<Activity> activitys = null;
  private static MyApplication instance;
  private MyApplication() {
    activitys = new LinkedList<Activity>();
  }
  /**
   *  In singleton mode, obtain only 1 the MyApplication The instance 
   * 
   * @return
   */
  public static MyApplication getInstance() {
    if (null == instance) {
      instance = new MyApplication();
    }
    return instance;
  }
  //  add Activity Into the container 
  public void addActivity(Activity activity) {
    if (activitys != null && activitys.size() > 0) {
      if(!activitys.contains(activity)){
        activitys.add(activity);
      }
    }else{
      activitys.add(activity);
    }
  }
  //  Iterate over all Activity and finish
  public void exit() {
    if (activitys != null && activitys.size() > 0) {
      for (Activity activity : activitys) {
        activity.finish();
      }
    }
    System.exit(0);
  }
}

2. Add this Activity to the MyApplication object instance container in every onCreate method in Activity

MyApplication.getInstance().addActivity(this);

3. Call the exit method when you need to end all Activity
MyApplication.getInstance().exit();

I hope this article has been helpful for your Android programming.


Related articles: