How to detect the BACK button input on Android device


In Cocos Creator 3.8 we would like to detect the BACK button input in order to close the app.

I know that we can patch the but the onBackPressed seems deprecated on Android API 33.

I modified this method but the method is never called:

    public void onBackPressed() {

Handle the input like a keyboard event and get the keycode. Cocos api defults KeyCode.MOBILE_BACK to 6 and KeyCode.BACKSPACE to 8 (docs[dot]cocos[dot]com/creator/3.8/api/en/enumeration/KeyCode?id=MOBILE_BACK).
I had to do it manually, because both Android phones here (8.1 and 13) return 8 for both back and backspace.

input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
onKeyDown(event: EventKeyboard) {
  if (sys.isMobile) {// just in case
    if (event.keyCode == 8) {
      // finish and exit here
1 Like

Thanks you @coimbra

I also found this to add in the

public boolean onKeyDown(int keyCode, KeyEvent event) {
   if (keyCode == KeyEvent.KEYCODE_BACK) {
       // Kill the application

       // Move the task containing this activity to the back of the activity stack.
       return true;
   return super.onKeyDown(keyCode, event);
1 Like