实现思路1:时间差
private long firstTime=0;
@Override
public void onBackPressed() {
long secondTime=System.currentTimeMillis();
if(secondTime-firstTime>2000){
Toast.makeText(this,"再按一次退出键退出",Toast.LENGTH_SHORT).show();
firstTime=secondTime;
}else{
super.onBackPressed();
}
}```
实现思路2:开启线程,延时处理
private boolean canExit;
private Handler handler=new Handler();
@Override
public void onBackPressed() {
if (canExit){
super.onBackPressed();
}else{
Toast.makeText(this,"再按一次退出键退出",Toast.LENGTH_SHORT).show();
canExit=true;
handler.postDelayed(new Runnable() {
@Override
public void run() {
canExit=false;
}
},2000);
}
}```