Search code examples
androidandroid-ndknative-code

Android NDK: How to override onBackPressed in NativeActivity without java?


My app is written entirely in C/C++ using NativeActivity, it has no Java code (based on "native-activity" NDK example). Pressing "back" button closes it (destroys activity), but I need other behaivor of this button because I have my own UI and menus which are displayed via OpenGL.

As I read, In order to change behaivor of "back" button, I need to override onBackPressed() method of Java activity class. But I don't use Java, can I reach this method from C/C++ to override it?

If no, is there another way to handle with "back" button using NDK, without java code?


Solution

  • Solved: to prevent default "Back" button behaivor it is enough to return 1 while handling key event:

    int32_t app_handle_event(struct android_app* app, AInputEvent* event) {
        if (AKeyEvent_getKeyCode(event) == AKEYCODE_BACK) {
            // actions on back key
            return 1; // <-- prevent default handler
        };
        // ...
        return 0;
    }