在开发应用程序的时候,有一种功能是非常常用到的,那就是迅速双击返回按钮,然后实现退出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(); }
第三
private long lastPressedTime; private static final int PERIOD = 2000; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) { switch (event.getAction()) { case KeyEvent.ACTION_DOWN: if (event.getDownTime() - lastPressedTime < PERIOD) { finish(); } else { Toast.makeText(getApplicationContext(), "Press again to exit.", Toast.LENGTH_SHORT).show(); lastPressedTime = event.getEventTime(); } return true; } } return false; }