方法1
private boolean isQuit =false;
@Override
public void onBackPressed() {
if (!isQuit) {
Toast.makeText(this,"再按一次退出程序", Toast.LENGTH_SHORT).show();
isQuit =true;
//这段代码意思是,在两秒钟之后isQuit会变成false
new Thread(()->{
try {
Thread.sleep(2000);
}catch (InterruptedException e) {
e.printStackTrace();
}finally {
isQuit =false;
}
}).start();
}else {
System.exit(0);
}
}
方法2
private long firstTime =0;
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
long secondTime = System.currentTimeMillis();
if (keyCode == KeyEvent.KEYCODE_BACK) {
if ( secondTime -firstTime <2000) {
System.exit(0);
}else {
Toast.makeText(HomeActivity.this,"再按一次退出程序", Toast.LENGTH_SHORT).show();
firstTime = System.currentTimeMillis();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
网友评论