Search code examples
androidandroid-ndkjava-native-interface

Android JNI: Cannot call functions in non-Activity class


I am using jni and I can call java functions in regular activity from c++ class but when I try to call java functions in non activity class, my code does not work.

I mean

 jclass activityclass = env->FindClass("com/example/test/MyActivity);
 jmethodID methodID = env->GetMethodID(activityclass,"FunctionName","()V");
 env ->CallVoidMethod(obj,methodID);

This works. When I try to call same function(with same name) from non activity regular java class, it doesnt work.

 jclass regularclass = env->FindClass("com/example/test/MyRegularClass);
 jmethodID methodID = env->GetMethodID(regularclass ,"FunctionName","()V");
 env ->CallVoidMethod(obj,methodID);

Why I cannot call function in non activity class? What is my mistake?

My MyRegularClass

public class MyRegularClass{

  public static void FunctionName(){
 Log.i("Java Worked","Java Worked");
 }
}

My Activity classs

 public class MyActivity{

 system.load.library("mylib");

 @Override
 public void onCreate(Bundle savedInstanceState){
 ....
 ....
 testJNI();
 }

  public static void FunctionName(){
 Log.i("Activity Worked","Activity  Worked");
 }

 public native void testJNI();
 }

Solution

  • You need to use GetStaticMethodID() and CallStaticVoidMethod() for static methods. This has nothing to do with the methods being in activities or not.