如何从jni端调用java方法?

use*_*503 1 java java-native-interface pthreads android-ndk

我在jni方面做了一些c代码函数,所有工作都很好.

public native String getMessage() 
Run Code Online (Sandbox Code Playgroud)

函数返回从jni端到java端的字符串,它工作正常,所有其他jni代码也可以正常工作.但问题是如何在不使用return的情况下返回jni函数中的字符串,所以

public native void getMessagewithoutReturn()
Run Code Online (Sandbox Code Playgroud)

应该能够返回字符串.然后我,但getMessagewithoutReturn()函数永远不会使用pthread结束循环,如下所示,你可以看到:(它有效)

pthread_t native_thread;
pthread_create(&native_thread, NULL, native_thread_start_reading, env);
Run Code Online (Sandbox Code Playgroud)

并且每个循环迭代时间我都必须能够返回字符串,所以我不能使用return,因为它会停止函数运行.

pthread_t native_thread;
pthread_create(&native_thread, NULL, native_thread_start_reading, env);sted out that 
Run Code Online (Sandbox Code Playgroud)

我已经测试了那个posix线程,并且在android方面一切正常,因为它一直不是启动工作线程,但现在只是在每个迭代时间获取字符串的问题,而不使用函数返回.

小智 9

我的建议 :

创建一个将接收字符串的类(您也可以使用接口或抽象类):

class ResultHandler { 
    public void onReturnedString(String str) 
    { 
        /* Do something with the string */ 
    } 
}
Run Code Online (Sandbox Code Playgroud)

然后更改函数的原型:

public native void getMessagewithoutReturn(ResultHandler handler);
Run Code Online (Sandbox Code Playgroud)

并且本机功能将变为:

void  Java_com_foo_bar_getMessagewithoutReturn(JNIEnv *env, jobject thiz, jobject handler);
Run Code Online (Sandbox Code Playgroud)

现在你必须调用处理程序的onReturnedString,所以你必须使用JNI函数:

 jmethodID mid;
 jclass handlerClass = (*env)->FindClass(env, "com/foo/bar/ResultHandler");
 if (handlerClass == NULL) {
     /* error handling */
 }
 mid = (*env)->GetMethodID(env, handlerClass, "onReturnedString", "(Ljava/lang/String;)V");
 if (mid == NULL) {
     /* error handling */
 }
Run Code Online (Sandbox Code Playgroud)

然后当你需要调用函数时:(我想resultString是一个jstring)

 (*env)->CallVoidMethod(env, handler, mid, resultString);
Run Code Online (Sandbox Code Playgroud)

我没有测试过代码,但你有基本的想法.

这里有一些参考和示例代码