Important: Please read the Qt Code of Conduct -

Register native Function in Java Activity leads to crash

  • I tried to register a c++ function to the NotificationClient example (Qt 5.9).
    Following code was added to the NotificationClient constructor to register the c++ function.

    QAndroidJniEnvironment env;
    JNINativeMethod methods[] {{"test", "()V", reinterpret_cast<void*>(test)}};
    QAndroidJniObject javaClass("org/qtproject/example/notification/NotificationClient");
    jclass objectClass = env->GetObjectClass(javaClass.object<jobject>());
    env->RegisterNatives(objectClass, methods, sizeof(methods)/sizeof(methods[0]));

    This lead to uncought exceptions saying, I can't register any handlers in a Thread before calling Looper.prepare(). After several failed attempts I found out, that registering a c++ function inside a Java Activity lead to this exception.
    So the next Idea was to call android/os/Looper prepare from the c++ part where I try to register the function. Indeed that prevented this exception, leading to the next one when trying to create a notification by tapping on the smileys:

    java.lang.IllegalStateException: System service not available to Activities before onCreate()

    You may note, that the Documentation about Looper.prepare advises you to call loop() (and quit() when finished), but doing this leads to a blanc ui. Interestingly, just calling looper.prepare without registering the native function does NOT lead to any exception.

    So I'm very confused right now. Any suggestions to fixing this?

    (btw. I'm actually trying to access the android stepsensor and wanted to add a callback in an activity implementing a sensorEventHandler, but I could narrow it down to the situation described above, but feel free to give me a working implementation for a QStepSensor =D )

    Edit: solved it by using this tutorial, solution was to register the function in the JNIEXPORT JNI_OnLoad in the main.cpp

Log in to reply