This Blog has documented how to exit the program by clicking the Back key twice
The effect is as follows:
Let’s do it this way
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return super.onKeyDown(keyCode, event);
}
Copy the code
Then explain what these two methods do: onKeyDown() is triggered when a key is pressed, but not handled by any view within the Activity. By default, pressing KEYCODE_BACK returns to the previous Activity.
OnKeyUp () : Emitted when a key is pressed and released, but not handled by any view within the Activity. By default, nothing is done, simply giving false as the return value.
The 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."Press exit again.", Toast.LENGTH_SHORT).show();
mExitTime = System.currentTimeMillis();
} else {
finish();
System.exit(0);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
Copy the code
This is generally done in this way
The above