SoFunction
Updated on 2025-03-01

ANDROID The instance code for perfect exit from the APP

Everyone knows that Android's Activity has a historical stack. For example, after completing the finish from A -> B -> C, C, and C, return to B, finish all the activities, the program will naturally exit. Of course, while finishing, you also need other resources for your own program. So we need to find a way to save the Activity. Then call their finish() method where the program exits.

Use global variables. By the way, the first thing that comes to mind is to inherit Application, and the code is as follows:
Copy the codeThe code is as follows:

public class AgentApplication extends Application { 

    private List<Activity> activities = new ArrayList<Activity>(); 

        public void addActivity(Activity activity) { 
            (activity); 
        } 

        @Override 
        public void onTerminate() { 
            (); 

            for (Activity activity : activities) { 
                (); 
            } 

            onDestroy(); 

            (0); 
        } 
    }

Then call addActivity () when Activity  onCreate. Some people may think that this Application needs to be used in all Activity  onCreate and needs to be a singleton instance. Actually, it is not necessary at all. Just use   () in the Activity.

Finally, call () where you need to launch the program. Remember: () must be called, and the onDestroy() in the code is my own way to release other resources, not a system.

After running the above code, a line prompt will appear in LogCat:
Process  Package name (pid  xxxxx)  has died.  Prove that your program has exited.