1枪狂、延時(shí)Handler實(shí)現(xiàn)
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{
// 兩秒內(nèi)再次點(diǎn)擊退出
Toast.makeText(getApplicationContext(), "再按一次后退鍵退出程序",Toast.LENGTH_SHORT).show();
isExit = true;
handler.sendEmptyMessageDelayed(CODE_NOT_EXIT, 2 * 1000);
}
}
2碳想、計(jì)算當(dāng)前時(shí)間實(shí)現(xiàn)
//記錄第一次點(diǎn)擊的時(shí)間
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();
}
}