ANDROID perfectly exits the instance code of APP

  • 2020-05-17 06:26:03
  • OfStack

Everyone knows that Android's Activity stores the history stack, for example, from A - > B - > C, C, finish, finish, B, Activity, finish. Of course, finish also requires other resources for its own program. So you need to find a way to save Activity. They then call their finish () method at the exit of the program.

Use global variables. By the way, the first thing that comes to mind is inheritance from Application.

public class AgentApplication extends Application {  

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

        public void addActivity(Activity activity) {  
            activities.add(activity);  
        }  

        @Override  
        public void onTerminate() {  
            super.onTerminate();  

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

            onDestroy();  

            System.exit(0);  
        }  
    }

Then you call addActivity () at Activity onCreate, and one might think that this Application would need to be used at all Activity onCreate times, and you would need to do a singleton. Not really. Use this.getApplication () in Activity.

Finally, call application.onTerminate () where you need to push out the program. Remember: super.onTerminate () must be called, and onDestroy () in the code is my own way of releasing other resources, not the system's.

After running the above code, 1 line prompt will appear in LogCat:
Process package name (pid xxxxx) has died.

Related articles: