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);
}
本文首发于我的微信公众号,更多干货文章,请扫描二维码订阅哦: