Call to JAVA from a secondary thread

Hi all,

Is there some particular way to make calls to JAVA from secondary threads?

Simple example posted by Rancs recently won’t work on a secondary thread (example pasted below). It seems the FindClass call raises an exception.

Example: in the ofApp.cpp:

std::string ofApp::getJavaString() {

    //"getStringToCppSide" is the name of a Java function of
    jmethodID midCallBack = ofGetJNIEnv()->GetMethodID(ofGetJavaOFAndroid(), "getStringToCppSide", "()Ljava/lang/String;"); 

    jstring resultJNIStr = (jstring)ofGetJNIEnv()->CallObjectMethod(ofGetJavaOFAndroid(), midCallBack);
    const char *resultCStr = ofGetJNIEnv()->GetStringUTFChars(resultJNIStr, NULL);
    std::string resultStr(resultCStr);

    ofGetJNIEnv()->ReleaseStringUTFChars(resultJNIStr, resultCStr);
    return resultStr;

in the

private String getStringToCppSide() {
    return requiredstring;

Is there a way we can do this? I’ve tried registering GlobalRefs for the Class and Activity, however, it results in random crashes (one in 10 very quick runs will crash ~90% of the time). On the main thread however, calls into Java work flawlessly 100% of the time.

Appreciate any help.

Hi all,

Just an update that I most likely went wrong somewhere in my implementation, and it’s difficult to trace it now. However, calling into JAVA from secondary threads works fine. Registering objects and classes globally in the correct manner is key, and I suppose doing it for the first time I most likely messed something up.

Sorry about the noise!

1 Like