During project development, we may encounter the scenario of safely exiting the application. How can we safely exit multiple activities? There are many methods on the Internet. The following method is my favorite, simple and easy to understand. As follows: every time an Activity is opened, it is recorded. When you need to exit, close every Activity. Create an Activity management object in singleton mode, which contains an Activity container. Define an Application class to store reference of Activity objects. The Code is as follows:
Public class ExitAppliation extends Application {private List activityList = new extends List (); private static ExitAppliation instance; private ExitAppliation () {}// obtain the unique MyApplication instance public static ExitAppliation getInstance () {if (null = instance) {instance = new ExitAppliation ();} return instance;} in singleton Mode ;} // Add the Activity to the container public void addActivity (Activity activity) {activityList. add (activity);} // traverse all activities and finishpublic void exit () {for (Activity: activityList) {activity. finish ();} System. exit (0 );}}
Note: The Application class is designed to save global variables. the result is that when your application or package is created, the class will be created. That is to say, the application is used to save global variables and will exist when the package is created. So when we need to create a global variable, we do not need to create a static variable with the public permission as j2se, but directly implement it in the application. You only need to call the getApplicationContext of Context or the getApplication method of Activity to obtain an application object and then process it accordingly.
Then add the following code to the onCreate () method of each Activity:
ExitAppliation.getInstance().addActivity(this);
Call the exit method when you need to end all the activities:
ExitAppliation.getInstance().exit();