ndk多线程需要获取JNIEnv 或c通过类名+包名创建对象使用如下方法

JavaVM* mJavaVM;
static pthread_key_t mThreadKey;

static void Android_JNI_ThreadDestroyed(void* value) {

JNIEnv *env = (JNIEnv*) value;
if (env != NULL) {
    mJavaVM->DetachCurrentThread();
    pthread_setspecific(mThreadKey, NULL);
}

}

jint JNI_OnLoad(JavaVM* vm, void* reserved) {
JNIEnv *env;
mJavaVM = vm;

if (mJavaVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
    return -1;
}

if (pthread_key_create(&mThreadKey, Android_JNI_ThreadDestroyed) != 0) { //程序结束时执行
    __android_log_print(ANDROID_LOG_ERROR, "cody", "Error initializing pthread key");
}
Android_JNI_SetupThread();

return JNI_VERSION_1_4;

}

JNIEnv* Android_JNI_GetEnv(void) {
JNIEnv *env;
int status = mJavaVM->AttachCurrentThread(&env, NULL);
if (status < 0) {
__android_log_print(ANDROID_LOG_ERROR, “cody”,”failed to attach current thread”);
return 0;
}
pthread_setspecific(mThreadKey, (void*) env);

return env;

}

int Android_JNI_SetupThread(void) {
Android_JNI_GetEnv();
return 1;
}

你可能感兴趣的:(jni)