Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 571
user1744012 Avatar asked Jun 12 '26 20:06

user1744012


1 Answers

"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

like image 102
marcinj Avatar answered Jun 14 '26 08:06

marcinj