Android completely exits multiple activity programs

Source: Internet
Author: User

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();


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.