How to detect the BACK button input on Android device

Hello,

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 AppActivity.java but the onBackPressed seems deprecated on Android API 33.

I modified this method but the method is never called:

  @Override
    public void onBackPressed() {
        SDKWrapper.shared().onBackPressed();
        super.onBackPressed();
        Log.i("AppActivity","QUIT");
        finish();
        System.exit(0);
    }

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.
ie.

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 AppActivity.java

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
   if (keyCode == KeyEvent.KEYCODE_BACK) {
       // Kill the application
       //finish();
       //System.exit(0);


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