我尝试创建从 jni 到 java 的回调,但是当从 cpp 线程执行我的代码时,findClass 方法返回 null,但是从 jni 线程(本机线程)正确执行的相同类路径和方法。
static JavaVM * s_Jvm;
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
{
s_Jvm = vm;
return JNI_VERSION_1_4;
}
void callbackToJava() {
JNIEnv *env;
res = s_Jvm->GetEnv((void**) &env, JNI_VERSION_1_4);
LOGI("status:%d",res);
if(res < 0) {
LOGI("callback_handler: failed to get JNI environment, "
"assuming native thread");
res = s_Jvm->AttachCurrentThreadAsDaemon(&env, NULL);
LOGI("res:%d",res);
if(res == JNI_OK) {
LOGI("JNI_ok");
}
if(res < 0) {
LOGI("callback_handler: failed to attach "
"current thread");
return;
}
}
if (res < 0) {
LOGI("Can't create Java VM\n");
return;
}
cls = (env)->FindClass("com/test/controller/NativeTest");
if (cls == NULL) {
LOGI("Class is null"); //**Error Line**
goto destroy;
}
mid = (env)->GetStaticMethodID(cls, "display",
"()V");
if (mid == NULL) {
LOGI("Mid is null");
goto destroy;
}
(env)->CallStaticVoidMethod(cls, mid, "()V");
destroy:
if ((env)->ExceptionOccurred()) {
(env)->ExceptionDescribe();
}
(jvm)->DestroyJavaVM();
}