6

I am working in Unity3D and writing my script in C#. I want to call my java method from c# script which take a parameter of boolean type but i don't know how to pass parameter from C# using JNI. I am able to call methods which does not take any parameter. This is what i have tried for calling methods which does not take any parameter and it is working fine.

private int BtnMyAppWall;
// create a JavaClass object...
        IntPtr cls_JavaClass    = JNI.FindClass("com/example/unitybuttontry/MainActivity");
        int mid_JavaClass       = JNI.GetMethodID(cls_JavaClass, "<init>", "(Landroid/app/Activity;)V");
        IntPtr obj_JavaClass    = JNI.NewObject(cls_JavaClass, mid_JavaClass, obj_Activity);
        Debug.Log("JavaClass object = " + obj_JavaClass);

        // create a global reference to the JavaClass object and fetch method id(s)..
        JavaClass           = JNI.NewGlobalRef(obj_JavaClass);

BtnMyAppWall    = JNI.GetMethodID(cls_JavaClass, "myAppWall", "()Ljava/lang/String;");

// get the Java String object from the JavaClass object
        IntPtr str_cacheDir     = JNI.CallObjectMethod(JavaClass, BtnMyAppWall);

Now if i want to pass a parameter of boolean type then i need to change my last two statement something like this:

  Stmt 1:  BtnMyAppWall = JNI.GetMethodID(cls_JavaClass, "myAppWall", "(Z)Ljava/lang/String;");

  Stmt 2:  // get the Java String object from the JavaClass object
            IntPtr str_cacheDir     = JNI.CallObjectMethod(JavaClass, BtnMyAppWall,true);

You can see in Stmt 1, i have mentioned 'Z' which means my method will take boolean parameter but in Stmt2 when i pass my value then it gives error:

Error: cannot convert object' expression to typeSystem.IntPtr'

Please help me out.

Lex Li
  • 60,503
  • 9
  • 116
  • 147
Kapil
  • 1,790
  • 1
  • 16
  • 32

3 Answers3

1

You need to use Android.Runtime.JValue:

// get the Java String object from the JavaClass object
IntPtr str_cacheDir = JNI.CallObjectMethod(obj_JavaClass, BtnMyAppWall, new JValue(true));
jonp
  • 13,512
  • 5
  • 45
  • 60
0

Using Unity's JNI wrappers (AndroidJavaObject and AndroidJavaClass), I'd rewrite your code to look like this (not tested, though we use these wrappers in our plugin):

AndroidJavaObject obj = new AndroidJavaObject("com/example/unitybuttontry/MainActivity");
obj.CallMethod<string>("myAppWall", true);
Vladimir Gritsenko
  • 1,669
  • 11
  • 25
0

What Vladimir mentioned is correct. If you are only passing in basic parameters like string, boolean or activity, using Unity's JNI wrappers would be less of a hassle rather than manually dealing with the JNI codes.

However if you are dealing with arrays and dictionaries, it's better to handle them manually as problems may arise during runtime where the parameters maybe not be passed as intended.

KennethLJJ
  • 157
  • 3
  • 12