0x03 多线程使用JNIEnv指针

JNIEnv因线程不同而不同,不能直接 globalRef 或者 static extern,
每次从JavaVM *vm中获取,因为线程独立。JavaVM从JNI_OnLoad中获取

bool getCurEnv(JNIEnv **env_jni, bool *shouldDetach_jni) {
    *shouldDetach_jni = false;
    JNIEnv *env = NULL;
    if (vm_btalk->GetEnv((void **)&env, JNI_VERSION_1_4) != JNI_OK) {
        // LOGD("GetEnv failed -> AttachCurrentThread");
        if (vm_btalk->AttachCurrentThread(&env, NULL) < 0) {
            LOGE("call AttachCurrentThread error! vm_btalk = %p, env = %p", vm_btalk, env);
            return false;
        }
        else
            // LOGD("AttachCurrentThread success");
            *shouldDetach_jni = true;
    }
    env = NULL;
    vm_btalk->GetEnv((void **)&env, JNI_VERSION_1_4);
    *env_jni = env;
    return true;
}

使用后释放,如下

    //detach thread
    if (env != NULL && shouldDetach) {
        vm_btalk->DetachCurrentThread();
        LogUtils::getInstance()->logD("D DetachCurrentThread() finished in " + fun);
    }

你可能感兴趣的:(0x03 多线程使用JNIEnv指针)