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);
}
}
通过 mBackKeyPressed 来记录是否有首次按返回键的记录,如果不存在首次按键记录,则Toast提示,并记录首次按键记录,并启动线程在2秒后擦除该按键记录。如果在线程海内擦除mBackKeyPressed 时又按下返回键,则执行else里面的语句退出程序。
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);
}
}
方法很多,当然也可以用下面的方法,
3.//记录用户首次点击返回键的时间
private longfirstTime =0;/** *
通过监听keyUp *@paramkeyCode *@paramevent *@return*/@OverridepublicbooleanonKeyUp(intkeyCode, KeyEvent event) {if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {longsecondTime = System.currentTimeMillis();if(secondTime - firstTime >2000) {
Toast.makeText(MainActivity.this,"再按一次退出程序", Toast.LENGTH_SHORT).show();
firstTime = secondTime;returntrue;
}else{
System.exit(0);
}
}returnsuper.onKeyUp(keyCode, event);
}
4.
/* *@paramkeyCode *@paramevent *@return*/@OverridepublicbooleanonKeyDown(intkeyCode, KeyEvent event) {if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {longsecondTime = System.currentTimeMillis();if(secondTime - firstTime >2000) {
Toast.makeText(MainActivity.this,"再按一次退出程序", Toast.LENGTH_SHORT).show();
firstTime = secondTime;returntrue;
}else{
System.exit(0);
}
}returnsuper.onKeyDown(keyCode, event);
}