Android Activity completely ends and exits the instance of the program

  • 2020-05-19 05:46:23
  • OfStack

There are plenty of online posts and ways to quit the Android program altogether. Remember to write their own first relatively complete project met the question, when I was owing to lack of understanding of the life cycle of Activity, again use TabActivity makes the hierarchical relationship is complicated and added in the program of "exit" menu items often unable to completely quit, after various search on the net, all kinds of methods are tried, what? System exit (0), the end of the process such as ah, still no results.
This method was discovered later. The train of thought is also very simple, recall oneself at the outset in order to solve this problem when looking for hard, decide to share it then, offer the personage that encounters this problem as reference.
Add a global variable as the exit mark of the program (boolean type), and set it as true when you need to exit the program. Judge this variable in the onStart method of each Activity in the program, and end it as true.
Use Application to save one global variable, isProgramExit. (see related materials if you are not familiar with Application)

public class MyApplication extendsApplication {
 //  Program exit mark 
 private static boolean isProgramExit = false;
 public void setExit(booleanexit) {
  isProgramExit= exit;
 }

 public booleanisExit() {
  return isProgramExit;
 }
}

Add the following code to each Activity onStart method that you need to end when you exit:

protected voidonStart() {
 super.onStart();
 MyApplication mApp = (MyApplication)getApplication();
 if(mApp.isExit()) {
  finish();
 }
}

So when C ends itself, it will go back to B according to the process, and then B will judge, because the exit condition is satisfied, it will end itself; Back to A, which also ends...
As you can see, this method is not very clever, and even a little bit complicated, because you have to add judgments to the onStart of each Activity. But there is no denying that this method is absolutely effective, no matter how your program Activity jump to jump to, as long as 1 command, all end, it works.
So, have the friend that encounters program exit problem can serve as a reference.

Related articles: