android 按两次返回键退出程序

单击返回键两次退出,单击一次返回键Toast提示,在其后2s内再单击一次返回键就退出。

方法一:

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) {

// TODO Auto-generated method stub

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);

}

}

return false;

}


方法二:

private long mExitTime;

public boolean onKeyDown(int keyCode, KeyEvent event) {

if (keyCode == KeyEvent.KEYCODE_BACK) {

if ((System.currentTimeMillis() - mExitTime) > 2000) {

Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();

mExitTime = System.currentTimeMillis();


} else {

finish();

}

return true;

}

return super.onKeyDown(keyCode, event);

}

}


你可能感兴趣的:(android)