2s内点击两次返回键退出应用
实现思路:监听返回按键,添加一个状态如果在2s内在此点击了返回键就改变状态然后消费事件即可
private static final int MESSAGE_BACK = 1;
private boolean isFlag = true;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_BACK:
isFlag = true; // 在2s时,恢复isFlag的变量值
break;
}
}
};
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && isFlag) {
isFlag = false;
Toast.makeText(MainActivity.this, "再点击一次返回键退出应用", Toast.LENGTH_SHORT).show();
handler.sendEmptyMessageDelayed(MESSAGE_BACK, 2000);
return true;
}
return super.onKeyUp(keyCode, event);
}
@Override
protected void onDestroy() {
super.onDestroy();
// 保证在activity退出前,移除所有未被执行的消息和回调方法,避免出现内存泄漏!
handler.removeCallbacksAndMessages(null);
}
复制