Tuesday, April 1, 2025
spot_img

Unable to Seize Android Again Button Occasion in Cocos Creator 3.8.2 – Cocos Creator


I’m making an attempt to seize the Android again button occasion in my Cocos Creator 3.8.2 venture, however it isn’t working as anticipated.

I’m utilizing the next TypeScript code:

import { enter, Enter, KeyCode } from 'cc';

enter.on(Enter.EventType.KEY_DOWN, this.onKeyDown, this);

onKeyDown(occasion: EventKeyboard) {
    console.log("Key Pressed: ", occasion.keyCode);
    if (occasion.keyCode === KeyCode.MOBILE_BACK) {
        console.log("Android Again Button Pressed!");
        this.onBackPressed();
    }
}

However the occasion doesn’t set off in any respect when urgent the again button.

Java Code in AppActivity.java

To make sure the occasion is shipped from native Android, I added:

@Override
public boolean onKeyDown(int keyCode, android.view.KeyEvent occasion) {
    if (keyCode == android.view.KeyEvent.KEYCODE_BACK) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                CocosJavascriptJavaBridge.evalString("cc.director.emit('back-button-pressed');");
            }
        });
        return true;
    }
    return tremendous.onKeyDown(keyCode, occasion);
}

And in Cocos Script, I added:

import { director } from 'cc';

director.on('back-button-pressed', this.onBackPressed, this);

onBackPressed() {
    console.log("Android Again Button Pressed - Dealt with in Cocos!");
}

Situation Noticed:

  1. The app closes instantly when urgent the again button as an alternative of executing onBackPressed().
  2. The onKeyDown() methodology in Java is triggered (confirmed through logs), however Cocos doesn’t appear to intercept the occasion earlier than the app closes.

How can I correctly intercept and deal with the again button occasion inside Cocos 3.8.2 with out the app closing instantly?
@Tom_k

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisement -spot_img

Latest Articles