1 private static boolean isExit = false; 2 3 Handler mHandler = new Handler(){ 4 5 @Override 6 public void handleMessage(Message msg) { 7 // TODO Auto-generated method stub 8 super.handleMessage(msg); 9 isExit = false; 10 } 11 }; 12 13 @Override 14 public boolean onKeyDown(int keyCode, KeyEvent event){ 15 if (keyCode == KeyEvent.KEYCODE_BACK ) { 16 exit(); 17 return false; 18 } 19 return super.onKeyDown(keyCode, event); 20 21 } 22 23 24 private void exit() { 25 // TODO Auto-generated method stub 26 if(!isExit){ 27 isExit = true; 28 Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show(); 29 mHandler.sendEmptyMessageDelayed(0, 2000); 30 } 31 else{ 32 finish(); 33 System.exit(0); 34 } 35 }
第二种方式是计算点击按钮的时间差
1 @Override 2 public boolean onKeyDown(int keyCode, KeyEvent event) { 3 if (keyCode == KeyEvent.KEYCODE_BACK) { 4 exit(); 5 return false; 6 } 7 return super.onKeyDown(keyCode, event); 8 } 9 10 public void exit() { 11 if ((System.currentTimeMillis() - exitTime) > 2000) { 12 Toast.makeText(getApplicationContext(), "再按一次退出程序",Toast.LENGTH_SHORT).show(); 13 exitTime = System.currentTimeMillis(); 14 } 15 else { 16 finish(); 17 System.exit(0); 18 } 19 }
原文:http://www.cnblogs.com/pngcui/p/4335811.html