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, as shown below:
1. Throwing an exception and exiting
This method causes the program to Force Close by throwing an exception.
Yes, but the problem to be solved is how to end the program without the Force Close window.
2. Record the opened Activity
Every time an Activity is opened, it is recorded. When you need to exit, close every Activity.
3. Send specific broadcasts
Send a specific broadcast when you need to end the application. After each Activity receives the broadcast, close it.
4. Recursive exit
Use startActivityForResult when opening a new Activity, add a flag on your own, process it in onActivityResult, and disable it recursively.
Method 2
Define an Application class to store reference of Activity objects
Package com. maso. wuye. activity; import java. util. using list; import java. util. list; import android. app. activity; import android. app. application; public class ExitApplication extends Application {private List <Activity> activityList = new external List <Activity> (); private static ExitApplication instance; private ExitApplication () {}// obtain the unique ExitApplication instance public static ExitApplication getInstance () {if (null = instance) {instance = new ExitApplication ();} 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 <application> label in xml implements its own implementation. 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:
ExitApplication.getInstance().addActivity(this);