Android连续点击两次Back键退出程序
思路1:记录上次点击的时间,与本次点击的时间比较,当两次时间间隔小于一定值时,退出,否则提示“再按一次退出程序”,同时更新上次点击时间
- private long firstTime = 0;
- @Override
- public boolean onKeyUp(int keyCode, KeyEvent event) {
- // TODO Auto-generated method stub
- switch(keyCode)
- {
- case KeyEvent.KEYCODE_BACK:
- long secondTime = System.currentTimeMillis();
- if (secondTime - firstTime > 2000) { //如果两次按键时间间隔大于2秒,则不退出
- Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
- firstTime = secondTime;//更新firstTime
- return true;
- } else { //两次按键小于2秒时,退出应用
- System.exit(0);
- }
- break;
- }
- return super.onKeyUp(keyCode, event);
- }
private long firstTime = 0;
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
long secondTime = System.currentTimeMillis();
if (secondTime - firstTime > 2000) { //如果两次按键时间间隔大于2秒,则不退出
Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
firstTime = secondTime;//更新firstTime
return true;
} else { //两次按键小于2秒时,退出应用
System.exit(0);
}
break;
}
return super.onKeyUp(keyCode, event);
}
思路2:开线程延时处理
- private int mBackKeyPressedTimes = 0;
- @Override
- public void onBackPressed() {
- if (mBackKeyPressedTimes == 0) {
- Toast.makeText(this, "再按一次退出程序 ", Toast.LENGTH_SHORT).show();
- mBackKeyPressedTimes = 1;
- new Thread() {
- @Override
- public void run() {
- try {
- Thread.sleep(2000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- mBackKeyPressedTimes = 0;
- }
- }
- }.start();
- return;
- else{
- this.activity.finish();
- }
- }
- super.onBackPressed();
- }