1利用线程延时实现
private static boolean mBackKeyPressed = false;//记录是否有首次按键
@Override
public void onBackPressed() {
if(!mBackKeyPressed){
Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
mBackKeyPressed = true;
new Timer().schedule(new TimerTask() {//延时两秒,如果超出则擦错第一次按键记录
@Override
public void run() {
mBackKeyPressed = false;
}
}, 2000);
}
else{//退出程序
this.finish();
System.exit(0);
}
}
2通过计算时间差实现
private long mPressedTime = 0;
@Override
public void onBackPressed() {
long mNowTime = System.currentTimeMillis();//获取第一次按键时间
if((mNowTime - mPressedTime) > 2000){//比较两次按键时间差
Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
mPressedTime = mNowTime;
}
else{//退出程序
this.finish();
System.exit(0);
}
}