[Switch] for Android, click the return key twice to exit. for android, click
In Android applications, we often need to determine the user's operation on the Return key. Generally, to prevent misoperation, the user is prompted whether to exit the application when the user presses the return key twice consecutively.
The basic principle of the first implementation is that when the BACK key is pressed, it will be captured by onKeyDown. If it is determined to be the BACK key, the exit method is executed.
1 2 3 4 5 6 7 8 910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
Package com. gaolei. exitdemo; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. view. keyEvent; import android. widget. toast; public class MainActivity extends Activity {// defines a variable to identify whether to exit private static boolean isExit = false; Handler mHandler = new Handler () {@ Override public void handleMessage (Message msg) {super. handleMessage (msg ); IsExit = false ;}}; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main) ;}@ Override public boolean onKeyDown (int keyCode, KeyEvent event) {if (keyCode = KeyEvent. KEYCODE_BACK) {exit (); return false;} return super. onKeyDown (keyCode, event);} private void exit () {if (! IsExit) {isExit = true; Toast. makeText (getApplicationContext (), "exit the program again", Toast. LENGTH_SHORT ). show (); // use handler to send the change status message mHandler. sendEmptyMessageDelayed (0, 2000);} else {finish (); System. exit (0 );}}}
The second method is to calculate the time difference by recording the key time:
1 2 3 4 5 6 7 8 91011121314151617181920212223242526272829303132333435363738 |
Package com. gaolei. exitdemo; import android. app. activity; import android. OS. bundle; import android. view. keyEvent; import android. widget. toast; public class MainActivity extends Activity {private long exitTime = 0; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main) ;}@ Override public boolean onKeyDown (int keyCode, KeyEvent event) {if (keyCode = KeyEvent. KEYCODE_BACK) {exit (); return false;} return super. onKeyDown (keyCode, event);} public void exit () {if (System. currentTimeMillis ()-exitTime)> 2000) {Toast. makeText (getApplicationContext (), "exit the program again", Toast. LENGTH_SHORT ). show (); exitTime = System. currentTimeMillis ();} else {finish (); System. exit (0 );}}} |
Disclaimer: The copyright of the eoe article belongs to the author and is protected by law. The following information must be included in the hyperlink for reprinting.
Author: gaolei_xj
Address: http://my.eoe.cn/leigo/archive/2146.html