1、延时Handler实现
private boolean isExit;
/** 程序是否退出 */
private boolean isFinish;
private final int CODE_NOT_EXIT = 0x000;
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case CODE_NOT_EXIT:
// 程序退出后不再做操作
if(isFinish) break;
isExit = false;
break;
default:
break;
}
};
};
@Override
protected void onDestroy() {
super.onDestroy();
isFinish = true;
}
@Override
public void onBackPressed() {
if(isExit){
super.onBackPressed();
}else{
// 两秒内再次点击退出
Toast.makeText(getApplicationContext(), "再按一次后退键退出程序",Toast.LENGTH_SHORT).show();
isExit = true;
handler.sendEmptyMessageDelayed(CODE_NOT_EXIT, 2 * 1000);
}
}
2、计算当前时间实现
//记录第一次点击的时间
private long clickTime = 0;
@Override
public void onBackPressed() {
if ((System.currentTimeMillis() - clickTime) > 2000) {
Toast.makeText(getApplicationContext(), "再按一次后退键退出程序",Toast.LENGTH_SHORT).show();
clickTime = System.currentTimeMillis();
} else {
super.onBackPressed();
}
}