Back按键的方法是onKeyDown()方法,重写该方法就可以改变back按键的作用。
实现点击两次Back按键退出app,有两种方法:
方法1.
1 private static boolean isAppExit=false; //定义一个变量,标示是否退出 2 private static Handler mHandler = new Handler() { 3 @Override 4 public void handleMessage(Message msg) { 5 super.handleMessage(msg); 6 isAppExit = false; 7 } 8 };
1 @Override 2 public boolean onKeyDown(int keyCode, KeyEvent event) { //重写onKeyDown()方法 3 // TODO Auto-generated method stub 4 if (keyCode==KeyEvent.KEYCODE_BACK&&event.getRepeatCount()==0) { 5 exit(); 6 return true; 7 } 8 return super.onKeyDown(keyCode, event); 9 } 10 11 private void exit() { 12 if (!isAppExit) { 13 isAppExit = true; 14 Toast.makeText(getApplicationContext(), "再按一次后退键退出程序", 15 Toast.LENGTH_SHORT).show(); 16 // 利用handler延迟发送更改状态信息 17 mHandler.sendEmptyMessageDelayed(0, 2000); 18 } else { 19 this.finish(); 20 } 21 }
方法2.
1 private long clickTime = 0; //记录第一次点击的时间 2 @Override 3 public boolean onKeyDown(int keyCode, KeyEvent event) { 4 if (keyCode == KeyEvent.KEYCODE_BACK) { 5 exit(); 6 return true; 7 } 8 return super.onKeyDown(keyCode, event); 9 } 10 11 private void exit() { 12 if ((System.currentTimeMillis() - clickTime) > 2000) { 13 Toast.makeText(getApplicationContext(), "再按一次后退键退出程序", 14 Toast.LENGTH_SHORT).show(); 15 clickTime = System.currentTimeMillis(); 16 } else { 17 Log.e(TAG, "exit application"); 18 this.finish(); 19 } 20 }