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;
}