如何在Unity3d中创建Java对象(使用AndroidJavaObject或AndroidJNI.NewObject)?

时间:2018-07-20 08:52:44

标签: android unity3d java-native-interface

使用AndroidJavaObjectAndroidJNI.NewObject创建对象有什么区别?

new AndroidJavaObject("android.content.Intent", ACTION_SEND);

vs

IntPtr intentClass = AndroidJNI.FindClass("android.content.Intent");
IntPtr intentConstructor = AndroidJNI.GetMethodID(IntentClass,"<init>","(Ljava/lang/String;)V");


jvalue[] intentParameters = new jvalue[1];
intentParameters[0] = ACTION_SEND;
IntPtr intentObject = AndroidJNI.NewObject(intentClass, intentConstructor, intentParameters);

AndroidJavaObject只是一个较短的版本,还是有缺点?

1 个答案:

答案 0 :(得分:1)

如果您反编译此类,您将看到它具有相同的作用:

private void _AndroidJavaObject(string className, params object[] args)
{
  this.DebugPrint("Creating AndroidJavaObject from " + className);
  if (args == null)
    args = new object[1];
  using (AndroidJavaObject @class = AndroidJavaObject.FindClass(className))
  {
    this.m_jclass = new GlobalJavaObjectRef(@class.GetRawObject());
    jvalue[] jniArgArray = AndroidJNIHelper.CreateJNIArgArray(args);
    try
    {
      IntPtr num = AndroidJNISafe.NewObject((IntPtr) this.m_jclass, AndroidJNIHelper.GetConstructorID((IntPtr) this.m_jclass, args), jniArgArray);
      this.m_jobject = new GlobalJavaObjectRef(num);
      AndroidJNISafe.DeleteLocalRef(num);
    }
    finally
    {
      AndroidJNIHelper.DeleteJNIArgArray(args, jniArgArray);
    }
  }
}