Search code examples
c#unity-game-enginejava-native-interfaceandroid-unity-plugin

What is defference between "AndroidJNI.FindClass" And "AndroidJavaClass" in Unity3D


I Just started to Learn about How to Connect my SDK Developed in Android to My Unity3D Project. But JNI and Unity classes like AndroidJNI still is very vague to me. For example, see bellow code that uses AndroidJNI.FindClass: (From This Post)

        cls_Activity = AndroidJNI.FindClass("com/unity3d/player/UnityPlayer");
        fid_Activity = AndroidJNI.GetStaticFieldID(cls_Activity, "currentActivity", "Landroid/app/Activity;");

        obj_Activity = AndroidJNI.GetStaticObjectField(cls_Activity, fid_Activity);
        kdataActivityClass = AndroidJNI.FindClass("com/kdata/unitytest/UnityUrlPlugin");
startAdsMethod = AndroidJNI.GetMethodID(kdataActivityClass,"getURL","(I)Ljava/lang/String;");

        jvalue[] myArray = new jvalue[1];
        myArray[0].i =testvalue;
        gui.text=   AndroidJNI.CallStaticStringMethod(obj_Activity, startAdsMethod, myArray);

Compare it to This Code Snippet That Uses AndroidJavaClass: (From This Link)

 private AndroidJavaClass ajc;
 private AndroidJavaObject ajo;

 AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
 ajo = jc.GetStatic<AndroidJavaObject>("currentActivity");

 var exampleSDK = new AndroidJavaClass("com.example.sdk.ExampleSDK");

 var videoObj = new AndroidJavaObject("com.example.sdk.VidoSchema");

 exampleSDK.CallStatic("lanuchSDKMethod", ajo, SERIAL, videoObj);

It looks like both of these do same thing. What is the difference between them?

Also if you can give me anything I can read about these, that'd be great.


Solution

  • AndroidJavaClass is just a convenience class. Of course it uses AndroidJNI and AndroidJNIHelper internally.

    AndroidJavaClass has GetRawClass() method and this will return the exactly same IntPtr value as AndroidJNI.FindClass()'s.

    So why use AndroidJavaClass? Because it's a lot easier, short, and readable. Also, if you want to keep a reference of a return value of AndroidJNI.FindClass(), you may want to call NewGlobalRef() but with AndroidJavaClass, you don't have to worry about it at all.

    There's one thing you should keep in mind with AndroidJavaClass. You need to call Dispose() when you are done with it. It implements a dispose pattern, so you can just leave it and Dispose() will be called automatically before Mono's GC, but it is not recommended. If you use AndroidJNI.FindClass() directly yourself, you need to call DeleteLocalRef() anyway.