Android click the Back button twice to monitor and exit the program

This blog records the writing of clicking the Back button twice to exit the program

The effect is as follows
Insert picture description here

We use this method to achieve

	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    
    
   		return super.onKeyDown(keyCode, event);
    }

Then explain the function of these two methods
onKeyDown():
It will be triggered when a key is pressed, but it will not be processed by any view in the Activity.
By default, pressing the KEYCODE_BACK key will return to the previous Activity.

onKeyUp():
When a key is pressed, it is triggered when it is released, but it will not be processed by any view in the Activity.
By default, no operation is performed, but a false value is simply given as the return value.

Implementation code

	/**
     * First time click on back
     */
    private Long mExitTime = 0L;


	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    
    
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
    
    
            if (System.currentTimeMillis() - mExitTime > 2000) {
    
    
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
    
    
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

Generally it is achieved in this way

Guess you like

Origin blog.csdn.net/A_Intelligence/article/details/110387546