Android双击返回键退出Activity的方法
第一种:利用线程延时实现:
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();
}
第二种:利用计算时间差实现 (个人觉得这种方式较为简单,而且不容易发生异常,代码较为安全)
private long exitTime = 0;
public void ExitApp()
{
if ((System.currentTimeMillis() - exitTime) > 2000)
{
Toast.makeText(this.activity, "再按一次退出程序", Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else
{
this.activity.finish();
}
}
第三种方法
- /**
- * 菜单、返回键响应
- */
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- // TODO Auto-generated method stub
- if(keyCode == KeyEvent.KEYCODE_BACK)
- {
- exitBy2Click(); //调用双击退出函数
- }
- return false;
- }
- /**
- * 双击退出函数
- */
- private static Boolean isExit = false;
- private void exitBy2Click() {
- Timer tExit = null;
- if (isExit == false) {
- isExit = true; // 准备退出
- Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
- tExit = new Timer();
- tExit.schedule(new TimerTask() {
- @Override
- public void run() {
- isExit = false; // 取消退出
- }
- }, 2000); // 如果2秒钟内没有按下返回键,则启动定时器取消掉刚才执行的任务
- } else {
- finish();
- System.exit(0);
- }
- }