Android completely exits the program by pressing the return key twice. android returns
Almost all applications now have the ability to exit the application by pressing two return keys. At the beginning, I thought that this function can be implemented only by using finish, later, we found that this only destroys the current page and does not exit the program. The process is still running in the background. Later, when System. exit (0) is used, the function of this method ends the process, and the result still does not work. After searching, we finally found a better method to implement this function. The principle of this method is to add all the activities to a linked list set. When you press the return key twice, destroy all the activities first, and then use System. exit (0); the Code is as follows:
1. First write a MyApplication
Private List <Activity> mList = new synchronized List <Activity> (); private static MyApplication instance; public synchronized static MyApplication getInstance () {if (null = instance) {instance = new MyApplication ();} return instance;} // call this method to add the current Acitivyt to the mList set public void addActivity (Activity activity) {mList. add (activity);} // when calling the exit method, destroy all activities not empty, and then exit the application public void exit () {try {for (Activity Ctiist: mList) {if (activity! = Null) activity. finish () ;}catch (Exception e) {e. printStackTrace () ;}finally {System. exit (0 );}}
2. Then add this line of code to each Activity you write and add the current Activity to the set.
protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);MyApplication.getInstance().addActivity(this);setContentView(R.layout.activity_about_mth);}
3. When you press the return key twice, call exit ();
/*** Press the return key twice to exit the application **/@ Overridepublic boolean onKeyDown (int keyCode, KeyEvent event) {if (keyCode = event. KEYCODE_BACK) {if (System. currentTimeMillis ()-time & gt; 2000) {Toast. makeText (MainActivity. this, "Quit again", 0 ). show (); time = System. currentTimeMillis ();} else {MyApplication. getInstance (). exit ();} return true;} return super. onKeyDown (keyCode, event );}
By now, the entire function has been completed, and the second code must be added to each Activity.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.