In Android, if you want to exit the Android program, you generally call finish (), System. exit (0), android. OS. process. killProcess (android. OS. process. myPid () and other methods to exit the program, but in actual development, it cannot completely exit the application, because it calls finish (), System. exit (0), android. OS. process. killProcess (android. OS. process. myPid () can only kill the current activity and cannot kill all the activities. To achieve this, we will use a case:
1. Create an Activity management object in singleton mode. This object has an Activity container (which can be implemented by yourself and used in the shortlist) to store each newly opened Activity, easy to understand, easy to operate, very good!
MyApplication class (stores every Activity and closes all activities)
Package com. hrtx. dd. activity; import java. util. using list; 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 external List <Activity> ();} /*** obtain the unique MyApplication instance in singleton mode ** @ return */public static MyApplicatio N getInstance () {if (null = instance) {instance = new MyApplication ();} return instance;} // Add the Activity to the container public void addActivity (Activity activity) {if (activitys! = Null & activitys. size ()> 0) {if (! Activitys. contains (activity) {activitys. add (activity) ;}} else {activitys. add (activity) ;}}// traverse all activities and finishpublic void exit () {if (activitys! = Null & activitys. size ()> 0) {for (Activity activity: activitys) {activity. finish () ;}} System. exit (0 );}}
2. Add the Activity to the container of the MyApplication object instance in the onCreate method of each Activity.
MyApplication.getInstance().addActivity(this);
3. Call the exit method when you need to end all activities
MyApplication.getInstance().exit();