LINUX 多线程 JNI 回调 java static

1.Linux 开启线程

//渲染线程Rendering
void* thread_rendering_process(void *lParam) {

    unsigned int local_wr;
    int index;
    int needsDetach;

    JNIEnv *evn = getJNIEnv(&needsDetach);
    (*evn)->CallStaticVoidMethod(evn, globalJclazz, methodID_ShowLog, 1);

//
    if (needsDetach)
        (*g_VM)->DetachCurrentThread(g_VM);

}

int media_decode_start() {
    gZpvInfo.stream_run_flag = 1;
    createThreadStatus = pthread_create(&thrd_media_rending, NULL,
            thread_rendering_process, NULL);

    if (createThreadStatus) {
        return -1;
    }
    return 0;
}

//全局jev 多线程中需要用到全局的 JNIEnv

jmethodID methodID, methodID_ShowLog;
JavaVM *g_VM;
jclass globalJclazz;
JNIEnv* globalEnv = NULL;
JNIEnv* getJNIEnv(int* needsDetach);

JNIEnv* getJNIEnv(int* needsDetach) {
    JNIEnv* env = NULL;
    jint result = -1;
    if ((*g_VM)->GetEnv(g_VM, (void**) &env, JNI_VERSION_1_4) != JNI_OK) {
        int status = (*g_VM)->AttachCurrentThread(g_VM, &env, 0);
        if (status < 0) {
            return NULL;
        }
        *needsDetach = 1;
    }
    return env;
}

JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) {

    g_VM = vm;
    static const char* const zClassName = "com/xxx/media/xxx";

    if ((*vm)->GetEnv(vm, (void**) &globalEnv, JNI_VERSION_1_4) != JNI_OK)
        return -1;

    jclass clazz = (*globalEnv)->FindClass(globalEnv, zClassName);
    globalJclazz = (*globalEnv)->NewGlobalRef(globalEnv, clazz); //转为全局引用
    if (clazz == NULL) {
        LOGI("OnLoad cannot get class:%s\n", zClassName);
        return -1;
    }

    if ((*globalEnv)->RegisterNatives(globalEnv, clazz, gMethods,
            sizeof(gMethods) / sizeof(gMethods[0])) != JNI_OK) {
        LOGI("OnLoad register native method failed!\n");
        return -1;
    }
    methodID = (*globalEnv)->GetStaticMethodID(globalEnv, clazz,
            "onFrameBuffer", "([BI)V");
    methodID_ShowLog = (*globalEnv)->GetStaticMethodID(globalEnv, clazz,
            "showLog", "(I)V");

    return JNI_VERSION_1_4;
}

猜你喜欢

转载自blog.csdn.net/zdy10326621/article/details/83587915