brief introduction
One of the common requirements in development is to exit the application. Now, there are two situations. One is to click the return key to pop up a prompt box, to exit the application, such as UC browser and Cheetah browser. The other is to double-click within a certain time interval to exit the application. Generally, it is mainly written in baseactivity (parent class)
What we do today is to exit the application in the second way.
Of course, there are many ways to do this. Here are two ways:
code analysis
1. Directly use System.currentTimeMillis() to judge
1. Override the onKeyDown() method
private long exitTime = 0; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { /*Judge whether the user clicks the "return key"*/ if (keyCode == KeyEvent.KEYCODE_BACK) { if ((System.currentTimeMillis() - exitTime) > 2000) { Toast.makeText(this, "Press again to exit the program", Toast.LENGTH_SHORT).show(); exitTime = System.currentTimeMillis(); } else { finishAll(); System.exit(0); Process.killProcess(Process.myPid()); } return true; } return super.onKeyDown(keyCode, event); }
2. Use Timer to judge time interval
2. Override the onKeyDown() method
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode==KeyEvent.KEYCODE_BACK){ exitAPP(); } return false; } private boolean isExitApp; private void exitAPP() { Timer timer = null; if (!isExitApp) { isExitApp = true; Toast.makeText(this, "Press again to exit the program", Toast.LENGTH_SHORT).show(); timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { isExitApp = false;//Cancel exit } }, 2000);// If the return key is not pressed within 2 seconds, start the timer to cancel the task just executed } else { finishAll(); System.exit(0); Process.killProcess(Process.myPid()); } } //finish all when the added parent class exits public static void finishAll() { List<BaseActivity> copy; synchronized (mActivities) { copy = new ArrayList<BaseActivity>(mActivities); } for (BaseActivity activity : copy) { activity.finish(); } }
3. Both of these cases meet the needs of exiting the application. OK, here is to record and add some knowledge to yourself.