1 @Override 2 public boolean onKeyDown(int keyCode, KeyEvent event) 3 { 4 if(keyCode == KeyEvent.KEYCODE_BACK){ 5 quitApp(); 6 return false; 7 }else{ 8 return super.onKeyDown(keyCode, event); 9 } 10 } 11 /** 12 * 退出APP 13 */ 14 private void quitApp(){ 15 if(isExit){ 16 Intent intent = new Intent(Intent.ACTION_MAIN); 17 intent.addCategory(Intent.CATEGORY_HOME); 18 startActivity(intent); 19 System.exit(0); 20 }else{ 21 isExit = true; 22 Tools.showText(mContext, "再按一次退出应用"); 23 mHandler.sendEmptyMessageDelayed(0, 2000); 24 } 25 } 26 Handler mHandler = new Handler(){ 27 public void handleMessage(android.os.Message msg) { 28 super.handleMessage(msg); 29 isExit = false; 30 }; 31 };
第二种:
1 @Override 2 public boolean onKeyDown(int keyCode, KeyEvent event) 3 { 4 if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) 5 quitApp(); 6 return false; 7 } 8 private long exitTime = 0; 9 private void quitApp(){ 10 if(System.currentTimeMillis() - exitTime > 2000){ 11 Tools.showText(mContext, "再按一次退出应用"); 12 exitTime = System.currentTimeMillis(); 13 }else{ 14 finish(); 15 } 16 }