簡體   English   中英

從C ++到Java的Android JNI回調

[英]Android JNI Callback to java from C++

我試圖創建一個從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();

}

我更喜歡在jni線程中創建一個函數,然后從cpp代碼的其他線程中調用它。 參見示例項目https://github.com/NickZt/MyJNACallbackTest將每個偵聽器保存到動態數組

env-> GetJavaVM(JVM); //存儲JVM參考以供以后調用

store_env = env;

jweak store_Wlistener = env->NewWeakGlobalRef(listener);
jclass clazz = env->GetObjectClass(store_Wlistener);

jmethodID store_method = env->GetMethodID(clazz, "onAcceptMessage", "(Ljava/lang/String;)V");
jmethodID store_methodVAL = env->GetMethodID(clazz, "onAcceptMessageVal", "(I)V");

ObserverChain *tmpt = new ObserverChain(store_Wlistener, store_method, store_methodVAL);

store_Wlistener_vector.push_back(tmpt);

它們使用功能test_string_callback_fom_c(char * val)從C ++代碼回調到存儲的偵聽器

void test_string_callback_fom_c(char *val) {
    __android_log_print(ANDROID_LOG_VERBOSE, "GetEnv:", " start Callback  to JNL [%d]  \n", val);
    JNIEnv *g_env;
    if (NULL == jvm) {
        __android_log_print(ANDROID_LOG_ERROR, "GetEnv:", "  No VM  \n");
        return;
    }
    //  double check it's all ok
    JavaVMAttachArgs args;
    args.version = JNI_VERSION_1_6; // set your JNI version
    args.name = NULL; // you might want to give the java thread a name
    args.group = NULL; // you might want to assign the java thread to a ThreadGroup

    int getEnvStat = jvm->GetEnv((void **) &g_env, JNI_VERSION_1_6);

    if (getEnvStat == JNI_EDETACHED) {
        __android_log_print(ANDROID_LOG_ERROR, "GetEnv:", " not attached\n");
        if (jvm->AttachCurrentThread(&g_env, &args) != 0) {
            __android_log_print(ANDROID_LOG_ERROR, "GetEnv:", " Failed to attach\n");
        }
    } else if (getEnvStat == JNI_OK) {
        __android_log_print(ANDROID_LOG_VERBOSE, "GetEnv:", " JNI_OK\n");
    } else if (getEnvStat == JNI_EVERSION) {
        __android_log_print(ANDROID_LOG_ERROR, "GetEnv:", " version not supported\n");
    }

    jstring message = g_env->NewStringUTF(val);//

    txtCallback(g_env, message);

    if (g_env->ExceptionCheck()) {
        g_env->ExceptionDescribe();
    }

    if (getEnvStat == JNI_EDETACHED) {
        jvm->DetachCurrentThread();
    }
}

extern "C"
JNIEXPORT void JNICALL
Java_ua_zt_mezon_myjnacallbacktest_MainActivity_nonNextListener(JNIEnv *env, jobject instance,
                                                                jstring message_) {


    txtCallback(env, message_);

}

void txtCallback(JNIEnv *env, const _jstring *message_) {
    if (!store_Wlistener_vector.empty()) {
        for (int i = 0; i < store_Wlistener_vector.size(); i++) {
            env->CallVoidMethod(store_Wlistener_vector[i]->store_Wlistener,
                                store_Wlistener_vector[i]->store_method, message_);
        }

或從Java代碼使用nonNextListener方法將消息發送到偵聽器

https://dou.ua/lenta/articles/android-jni-callbacks中有完整的解釋

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM