Android calling Java function from another activity class in C++ JNI code

872 Views Asked by At

As the title suggested, How can I call Java function from C++ if the function is from a different java activity class?

All of the sample and tutorials calls C++ function and java back and forth but the caller is the class and the JNIEnv and jobject are passed from java thru JNI. But what if the function that needed to be called is from a different java activity class? How to do this? passing the "this" of the activity did not work

Here is sample layout of classes

Activity class

public class MainActivity extends Activity {
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);

          JNIAdapter.launch(); 
      }

      private void DisplayLoginDialog() 
      {
          //...
      }
}

JNIAdapter.class

public class JNIAdapter {
    static {
       System.loadLibrary("jnisample-lib");
    }

     public static native void launch();
}

jnisample.cpp

extern "C"
JNIEXPORT void JNICALL
Java_com_JNIAdapter_launch(JNIEnv *env,jobject object)
{
       jclass dataClass = env->FindClass("com/game/ramo/MainActivity");
       jmethodID javaMethodRef = env->GetMethodID(dataClass, "DisplayLoginDialog", "()V");
       env->CallVoidMethod(object, javaMethodRef);
}

In the above code, using the jobject, refers to the JNIAdapter class and not the Activity hence the DisplayLoginDialog() is not called. How to do this?

1

There are 1 best solutions below

2
On

Your small example (I understand that you reduced all details not relevant to the specific problem, that's very nice!) could run without native method. JNIAdaptor.launch() could be pure Java. So, to begin with, rewrite it in Java and make sure it works.

The issues could be that MainActivity.DisplayLoginDialog() may expect its parent activity to be in the foreground, or in some specific state. This is easier to fix in pure Java.

After that, the JNI code you wrote should run without problems.