app开发中,经常需要按下两次退出apk,以下是实现方式:
private static Boolean isExit = false;
private static Boolean hasTask = false;
Timer tExit = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
isExit = false;
hasTask = true;
}
};
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if(isExit == false ) {
isExit = true;
Toast.makeText(this, "再点击返回键,退出程序", Toast.LENGTH_SHORT).show();
if(!hasTask) {
tExit.schedule(task, 2000);
}
} else {
finish();
System.exit(0);
}
}
if (keyCode==KeyEvent.KEYCODE_MENU) {
openOptionsMenu();
}
return true;
}