简体   繁体   中英

Android: Passing data from a jni thread to java program

I am working on a jni-client-software, which should communicate with a server. I can establish the connection, can read out the information I need and give it back to my java programm. Now I want to to the connection infinite, that means the connection is established and the information should be read out in a infinite loop (I don't want to disconnect and reconnect with every jni-function call). Is it possible to pass a byte array from the working jni tread to a my java programm?

Thank you very much.

Kind regards

Thomas

"Is it possible to pass a byte array from the working jni tread to a my java programm?"

you can create static method in one of your java classes, and then call this method with parameters from within jni code. Here is some code:

java side:

package com.mysuper.game;
public class MyApp {
    public static void callMeFromJNI(byte[] data) {
        // ...
    }
}

and c++ code run on worker thread :

JavaVM *vm;
// use vm->AttachCurrentThread(&env, 0); in thread function to get valid JNI interface pointer, on thread end use DetachCurrentThread().
JNIEnv *env;

void myFunc() {

    // some test data to send
    const int len = 32;
    char data[len] = {0,1,2,3,4};

    jclass app = env->FindClass("com/mysuper/game/MyApp");
    jmethodID sendDataToJava = env->GetStaticMethodID(app, "callMeFromJNI", "([B)V");
    jbyteArray bArray = env->NewByteArray(len);
    char *bytes = (char *)env->GetByteArrayElements(bArray, 0);
    memcpy( bytes, data, len);
    env->ReleaseByteArrayElements(bArray, bytes, JNI_ABORT);
    env->CallStaticVoidMethod(app, sendDataToJava, bArray);
}

for more on how this works look into:

Java Native Interface 6.0 Specification

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM