简单的记录项目中使用的一个小功能 :点击返回按钮两次退出当前程序
方法一:
//重写onKeyup(),实现连续两次点击方可退出当前程序
private boolean flag = true;
private static final int WHAT_RESET_BACK = 1;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case WHAT_RESET_BACK:
flag = true;//复原
break;
}
}
};
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode==KeyEvent.KEYCODE_BACK&&flag){
Toast.makeText(MainActivity.this,"再点击一次,退出当前程序",Toast.LENGTH_SHORT).show();
flag = false;
//发送延迟消息
handler.sendEmptyMessageDelayed(WHAT_RESET_BACK,2000);
return true;
}
return super.onKeyUp(keyCode, event);
}
//为了避免内存溢出,需要在onDestroy()中,移除所有未被执行的消息
@Override
protected void onDestroy() {
super.onDestroy();
//方式一:移除指定id的所有消息
// handler.removeMessages(WHAT_RESET_BACK);
//方式二:移除所有的未被执行的消息
handler.removeCallbacksAndMessages(null);
}
方法二:
//重写onKeyDown(),实现连续两次点击方可退出当前应用
private long firstTime = 0;
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
long secondTime = System.currentTimeMillis();
if (keyCode == KeyEvent.KEYCODE_BACK) {
if ( secondTime - firstTime < 2000) {
System.exit(0);
} else {
Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
firstTime = System.currentTimeMillis();
}
return true;
}
return super.onKeyDown(keyCode, event);
}