Sofia Clover
Sofia Clover

Reputation: 679

Java method called twice from C++ JNI NDK function

I have some C++ NDK code calling a Java method via JNI. The problem I have is that my Java method is getting called twice. It seems once I get a handle to the method using GetMethodID and then call env->NewObject w/ that method ID, my java function is called.

It is again, obviously called when I call env->CallVoidMethod(obj, mid) which is expected. I just am not sure why it is called when I create a NewObject?

C++ Code: 
---------
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
{
    jvm = vm;
    start();
    return JNI_VERSION_1_6;
}

void start() {    
    JNIEnv *env = NULL;
    jvm->GetEnv((void**)&env, JNI_VERSION_1_6);
    jclass cls = env->FindClass("com/test/Test");
    jmethodID mid = env->GetMethodID(cls, "StartApp", "()V");
    jobject obj = env->NewObject(cls, mid);

    if (mid != 0){
       env->CallVoidMethod(obj, mid);
    }
}       

Java Code:
----------
 public void StartApp(){
     android.util.Log.e("Test", "Java Method Called from Native");
 }

Upvotes: 1

Views: 1014

Answers (1)

Non-maskable Interrupt
Non-maskable Interrupt

Reputation: 3911

NewObject take the constructor as parameter, so

jobject obj = env->NewObject(cls, mid);

This will invoke the first StartApp(), but note that since it's not a proper constructor, this will cause you trouble.

For the constructor, according to the manual, This ID must be obtained by calling GetMethodID() with < init > as the method name and void (V) as the return type.

Upvotes: 3

Related Questions