JNI - 正确连接/分离线程

时间:2018-03-04 09:48:55

标签: multithreading kotlin java-native-interface

我有这段代码:

JNIEXPORT void package_MyAPI_callback(JNIEnv *env, jobject thiz, jobject caller) {
    JavaVM *vm;
    env->GetJavaVM(&vm);
    jclass callbackClass = (jclass) env->NewGlobalRef(env->FindClass("package/TimeLoadedListenerUIThread"));
    jobject cachedCaller = (jobject) env->NewGlobalRef(caller);
    jmethodID javaCallback = env->GetMethodID(callbackClass, "onTimeLoaded", "(Z)V");

    CppSetCallback([=] {
        JNIEnv *bgEnv;
        vm->AttachCurrentThread(&bgEnv, NULL);        
        bgEnv->CallVoidMethod(cachedCaller, javaCallback, false);

        bgEnv->DeleteGlobalRef(callbackClass);
        bgEnv->DeleteGlobalRef(cachedCaller);
        //vm->DetachCurrentThread();
    });
}

在Kotlin代码的某处:

override fun onTimeLoaded(resetToCurrentTime: Boolean) {
    activity.runOnUiThread { 
        activity.updateTimeSelector(resetToCurrentTime) }
    }
}

CppSetCallback将回调(功能性)设置为app的内部核心。在那里,功能从std::thread调用。

此代码运行,但我不确定它是否正确,因为如果我调用vm->DetachCurrentThread();应用程序崩溃。我该如何调用detach,或何时调用?

0 个答案:

没有答案