I have a Java class that takes a context, the constructor looks like this:
private MyClass(Context context){
// some initialization work
}
When I try to create this class in Unity, if I do
AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
AndroidJavaObject context = activity.Call<AndroidJavaObject>("getApplicationContext");
var object = new AndroidJavaObject("com.packnage.name.MyClass", context);
I end up with NoSuchMethodException:
no non-static method “Lcom/packnage/name/MyClass;.(Landroid.app.Application;)V”
This is because JNI cannot find the method id of the constructor.
However, if I manually provide the constructor method id like this:
IntPtr javaClass = AndroidJNI.FindClass(“com/packnage/name/MyClass”);
IntPtr javaConstructor = AndroidJNI.GetMethodID(javaClass,“”,“(Landroid/app/Application;)V”);
jvalue[ ] intentParameters = new jvalue[1];
intentParameters[0].l = context.GetRawObject();
IntPtr intentObject = AndroidJNI.NewObject(javaClass, javaConstructor, intentParameters);
[/code]
I’m able to create the object successfully.
I think the mismatch comes from the internal code GetSignature
It is supposed to return Landroid/app/Application; as the signature but it returns Landroid.app.Application;.
When I analyze the dex file of the apk, the method signature is like “(Landroid/app/Application;)V”, not “(Landroid.app.Application;)V”. That’s why it cannot find the constructor method.
Does anyone have similar experience?