When we want to quit the application, the general use of the physical button (back key), when the user press the Back button two times to exit the application, that is, destroy the current activity ();
Rewrite the onbackpressed () method: The code is as follows: PrivateintClickcount=0; @Override Publicvoidonbackpressed () { //TODOauto-generated Method Stub //super.onbackpressed (); if(Clickcount< 1) {Toast. Maketext ( This,"Press the Back button again to exit the application!" ", Toast.Length_short). Show (); Clickcount++; }Else{finish (); } } Note that the onbackpressed () method of the parent class needs to be removed, otherwise the program exits when the back key is pressed once, regardless of how it is written. but this kind of writing has a bad place, that is, when the user accidentally press the back button two times will exit, so it is not good, there is no user experience. To this end we improve the program, when the user after pressing the second exit key, if and the first time between more than 1s, we do not exit the program as invalid operation. The improved code is as follows:PrivateLongLastclicktime= 0; @Override Publicvoidonbackpressed () { //TODOauto-generated Method Stub //super.onbackpressed (); if(Lastclicktime<= 0) {Toast. Maketext ( This,"Press the Back button again to exit the application!" ", Toast.Length_short). Show (); Lastclicktime= System. Currenttimemillis (); }Else{ Longcurrentclicktime = System. Currenttimemillis (); if(currentclicktime-Lastclicktime< 1000) {finish (); }Else{Toast. Maketext ( This,"Press the Back button again to exit the application!" ", Toast.Length_short). Show (); Lastclicktime= Currentclicktime; } }}
Handling of Android Fallback events