-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathAndroidJava.cs
More file actions
2248 lines (2069 loc) · 101 KB
/
Copy pathAndroidJava.cs
File metadata and controls
2248 lines (2069 loc) · 101 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Unity.Scripting.LifecycleManagement;
using UnityEngine.Scripting;
namespace UnityEngine
{
public delegate void AndroidJavaRunnable();
public sealed class AndroidJavaException : Exception
{
private string mJavaStackTrace;
internal AndroidJavaException(string message, string javaStackTrace) : base(message)
{
mJavaStackTrace = javaStackTrace;
}
public override string StackTrace
{
get
{
return mJavaStackTrace + base.StackTrace;
}
}
}
internal class GlobalJavaObjectRef
{
public GlobalJavaObjectRef(IntPtr jobject)
{
m_jobject = (jobject == IntPtr.Zero) ? IntPtr.Zero : AndroidJNI.NewGlobalRef(jobject);
}
#pragma warning disable UA5000 // The Avoid Finalizer Analyzer produces compile errors for any new finalizers. This pre-existing finalizer declaration has been suppressed, but should be rewritten if possible.
~GlobalJavaObjectRef()
{
Dispose();
}
#pragma warning restore UA5000
public static implicit operator IntPtr(GlobalJavaObjectRef obj)
{
return obj.m_jobject;
}
private bool m_disposed = false;
public void Dispose()
{
if (m_disposed)
return;
m_disposed = true;
if (m_jobject != IntPtr.Zero)
{
AndroidJNISafe.QueueDeleteGlobalRef(m_jobject);
}
}
protected IntPtr m_jobject;
}
internal class AndroidJavaRunnableProxy : AndroidJavaProxy
{
private AndroidJavaRunnable mRunnable;
public AndroidJavaRunnableProxy(AndroidJavaRunnable runnable) : base("java/lang/Runnable") { mRunnable = runnable; }
public void run() { mRunnable(); }
public override IntPtr Invoke(string methodName, IntPtr javaArgs)
{
int arrayLen = 0;
if (javaArgs != IntPtr.Zero)
arrayLen = AndroidJNISafe.GetArrayLength(javaArgs);
if (arrayLen == 0 && methodName == "run")
{
run();
return IntPtr.Zero;
}
return base.Invoke(methodName, javaArgs);
}
}
///<summary>This class can be used to implement any java interface. Any java vm method invocation matching the interface on the proxy object will automatically be passed to the c# implementation.</summary>
///<remarks>**Note**: this API can be used from custom thread, but requires that thread to be attached to JVM first, see <see cref="AndroidJNI.AttachCurrentThread" />.</remarks>
///<example>
/// <code><![CDATA[
/// // Opens an android date picker dialog and grabs the result using a callback.
///using UnityEngine;
///using System;
///
///class ExampleClass : MonoBehaviour
///{
/// private static DateTime selectedDate = DateTime.Now;
///
/// class DateCallback : AndroidJavaProxy
/// {
/// public DateCallback() : base("android.app.DatePickerDialog$OnDateSetListener") {}
/// void onDateSet(AndroidJavaObject view, int year, int monthOfYear, int dayOfMonth)
/// {
/// selectedDate = new DateTime(year, monthOfYear + 1, dayOfMonth);
/// // If you have no longer any uses for the object, it must be disposed to prevent a leak
/// view.Dispose();
/// }
/// }
///
/// void OnGUI()
/// {
/// if (GUI.Button(new Rect(15, 15, 450, 75), string.Format("{0:yyyy-MM-dd}", selectedDate)))
/// {
/// var activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity");
/// activity.Call("runOnUiThread", new AndroidJavaRunnable(() =>
/// {
/// new AndroidJavaObject("android.app.DatePickerDialog", activity, new DateCallback(), selectedDate.Year, selectedDate.Month - 1, selectedDate.Day).Call("show");
/// }));
/// }
/// }
///}
///]]></code>
///</example>
public class AndroidJavaProxy
{
///<summary>Java interface implemented by the proxy.</summary>
public readonly AndroidJavaClass javaInterface;
///<param name="javaInterface">Java interface to be implemented by the proxy.</param>
public AndroidJavaProxy(string javaInterface) : this(new AndroidJavaClass(javaInterface)) { }
///<param name="javaInterface">Java interface to be implemented by the proxy.</param>
public AndroidJavaProxy(AndroidJavaClass javaInterface)
{
this.javaInterface = javaInterface;
}
#pragma warning disable UA5000 // The Avoid Finalizer Analyzer produces compile errors for any new finalizers. This pre-existing finalizer declaration has been suppressed, but should be rewritten if possible.
~AndroidJavaProxy()
{
AndroidJNISafe.DeleteWeakGlobalRef(proxyObject);
}
#pragma warning restore UA5000
///<summary>Called by the java vm whenever a method is invoked on the java proxy interface. You can override this to run special code on method invocation, or you can leave the implementation as is, and leave the default behavior which is to look for c# methods matching the signature of the java method.</summary>
///<param name="methodName">Name of the invoked java method.</param>
///<param name="args">Arguments passed from the java vm - converted into AndroidJavaObject, AndroidJavaClass or a primitive.</param>
public virtual AndroidJavaObject Invoke(string methodName, object[] args)
{
Exception error = null;
BindingFlags binderFlags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
int NullArgs = 0;
Type[] argTypes = new Type[args.Length];
for (int i = 0; i < args.Length; ++i)
{
if (args[i] == null)
{
argTypes[i] = null;
NullArgs ++;
}
else
{
argTypes[i] = args[i].GetType();
}
}
try
{
MethodInfo methodResult = null;
if (NullArgs > 0)
{
MethodInfo[] methods = this.GetType().GetMethods(binderFlags);
var matches = 0;
foreach (var method in methods)
{
//exit loop if dont have same name
if (methodName != method.Name)
continue;
ParameterInfo[] methodParameters = method.GetParameters();
//exit loop of dont have same number of paramters
if (methodParameters.Length != args.Length)
continue;
var isOk = true;
for (int j = 0; j < methodParameters.Length; j++)
{
if (argTypes[j] == null)
{
if (methodParameters[j].ParameterType.IsValueType)
{
isOk = false;
break;
}
}
else if (!methodParameters[j].ParameterType.IsAssignableFrom(argTypes[j]))
{
isOk = false;
break;
}
}
if (!isOk)
continue;
else
matches++;
methodResult = method;
}
if (matches > 1)
throw new Exception($"Ambiguous overloads found for {methodName} with given parameters");
}
else
methodResult = GetType().GetMethod(methodName, binderFlags, null, argTypes, null);
if (methodResult != null)
return _AndroidJNIHelper.Box(methodResult.Invoke(this, args));
}
catch (TargetInvocationException invocationError)
{
error = invocationError.InnerException;
}
catch (Exception invocationError)
{
error = invocationError;
}
//Log Error
string[] argTypeNames = new string[args.Length];
for (int i = 0; i < argTypeNames.Length; ++i)
{
if (argTypes[i] == null)
argTypeNames[i] = "null";
else
argTypeNames[i] = argTypes[i].ToString();
}
if (error != null)
throw new TargetInvocationException(GetType() + "." + methodName + "(" + string.Join(",", argTypeNames) + ")", error);
var ex = new Exception("No such proxy method: " + GetType() + "." + methodName + "(" + string.Join(",", argTypeNames) + ")");
var nativeError = AndroidReflection.CreateInvocationError(ex, methodNotFound: true);
return nativeError == IntPtr.Zero ? null : new AndroidJavaObject(nativeError);
}
///<summary>Called by the java vm whenever a method is invoked on the java proxy interface. You can override this to run special code on method invocation, or you can leave the implementation as is, and leave the default behavior which is to look for c# methods matching the signature of the java method.</summary>
///<param name="methodName">Name of the invoked java method.</param>
///<param name="javaArgs">Arguments passed from the java vm - all objects are represented by AndroidJavaObject, int for instance is represented by a java.lang.Integer object.</param>
public virtual AndroidJavaObject Invoke(string methodName, AndroidJavaObject[] javaArgs)
{
object[] args = new object[javaArgs.Length];
for (int i = 0; i < javaArgs.Length; ++i)
{
args[i] = _AndroidJNIHelper.Unbox(javaArgs[i]);
if (!(args[i] is AndroidJavaObject))
{
// If we're not passing a AndroidJavaObject/Class to the proxy, we can safely dispose
// Otherwise the GC would do it eventally, but it might be too slow and hit the global ref limit
if (javaArgs[i] != null)
javaArgs[i].Dispose();
}
}
return Invoke(methodName, args);
}
///<summary>Called by the java vm whenever a method is invoked on the java proxy interface. You can override this to run special code on method invocation, or you can leave the implementation as is, which will convert argument array to AndroidJavaObject[] and call other Invoke.</summary>
///<param name="methodName">Name of the invoked java method.</param>
///<param name="javaArgs">A reference to Java object array with arguments passed to this method.</param>
///<returns>A local reference to Java object, representing the return value.</returns>
public virtual IntPtr Invoke(string methodName, IntPtr javaArgs)
{
int arrayLen = 0;
if (javaArgs != IntPtr.Zero)
arrayLen = AndroidJNISafe.GetArrayLength(javaArgs);
if (arrayLen == 1 && methodName == "equals")
{
IntPtr o = AndroidJNISafe.GetObjectArrayElement(javaArgs, 0);
AndroidJavaObject obj = o == IntPtr.Zero ? null : new AndroidJavaObject(o);
return AndroidJNIHelper.Box(equals(obj));
}
else if (arrayLen == 0 && methodName == "hashCode")
{
return AndroidJNIHelper.Box(hashCode());
}
AndroidJavaObject[] args = new AndroidJavaObject[arrayLen];
for (int i = 0; i < arrayLen; ++i)
{
IntPtr objectRef = AndroidJNISafe.GetObjectArrayElement(javaArgs, i);
args[i] = objectRef != IntPtr.Zero ? AndroidJavaObject.AndroidJavaObjectDeleteLocalRef(objectRef) : null;
}
using (AndroidJavaObject result = Invoke(methodName, args))
{
if (result == null)
return IntPtr.Zero;
return AndroidJNI.NewLocalRef(result.GetRawObject());
}
}
// implementing equals, hashCode and toString which should be implemented by all java objects
// these methods must be in camel case, because that's how they are defined in java.
///<summary>The equivalent of the java.lang.Object <c>equals()</c> method.</summary>
///<returns>Returns true when the objects are equal and false if otherwise.</returns>
public virtual bool equals(AndroidJavaObject obj)
{
IntPtr anotherObject = (obj == null) ? IntPtr.Zero : obj.GetRawObject();
return AndroidJNI.IsSameObject(proxyObject, anotherObject);
}
///<summary>The equivalent of the java.lang.Object <c>hashCode()</c> method.</summary>
///<returns>Returns the hash code of the java proxy object.</returns>
public virtual int hashCode()
{
Span<jvalue> jniArgs = stackalloc jvalue[1];
jniArgs[0].l = GetRawProxy();
return AndroidJNISafe.CallStaticIntMethod(s_JavaLangSystemClass, s_HashCodeMethodID, jniArgs);
}
///<summary>The equivalent of the java.lang.Object <c>toString()</c> method.</summary>
///<returns>Returns C# class name + " <c# proxy java object>".</returns>
public virtual string toString()
{
return this + " <c# proxy java object>";
}
internal IntPtr proxyObject = IntPtr.Zero;
internal AndroidJavaObject GetProxyObject()
{
return AndroidJavaObject.AndroidJavaObjectDeleteLocalRef(GetRawProxy());
}
internal IntPtr GetRawProxy()
{
IntPtr ret = IntPtr.Zero;
if (proxyObject != IntPtr.Zero)
{
ret = AndroidJNI.NewLocalRef(proxyObject);
if (ret == IntPtr.Zero)
{
AndroidJNI.DeleteWeakGlobalRef(proxyObject);
proxyObject = IntPtr.Zero;
}
}
if (ret == IntPtr.Zero)
{
ret = AndroidJNIHelper.CreateJavaProxy(this);
proxyObject = AndroidJNI.NewWeakGlobalRef(ret);
}
return ret;
}
[NoAutoStaticsCleanup]
private static readonly GlobalJavaObjectRef s_JavaLangSystemClass = new GlobalJavaObjectRef(AndroidJNISafe.FindClass("java/lang/System"));
private static readonly IntPtr s_HashCodeMethodID = AndroidJNIHelper.GetMethodID(s_JavaLangSystemClass, "identityHashCode", "(Ljava/lang/Object;)I", true);
}
///<summary>AndroidJavaObject is the Unity representation of a generic instance of java.lang.Object.</summary>
///<remarks>It can be used as type-less interface to an instance of any Java class.
///**Note**: this API can be used from custom thread, but requires that thread to be attached to JVM first, see <see cref="AndroidJNI.AttachCurrentThread" />.</remarks>
public class AndroidJavaObject : IDisposable
{
// Construct an AndroidJavaObject based on the name of the class.
public AndroidJavaObject(string className, string[] args) : this()
{
_AndroidJavaObject(className, (object)args);
}
public AndroidJavaObject(string className, AndroidJavaObject[] args) : this()
{
_AndroidJavaObject(className, (object)args);
}
public AndroidJavaObject(string className, AndroidJavaClass[] args) : this()
{
_AndroidJavaObject(className, (object)args);
}
public AndroidJavaObject(string className, AndroidJavaProxy[] args) : this()
{
_AndroidJavaObject(className, (object)args);
}
public AndroidJavaObject(string className, AndroidJavaRunnable[] args) : this()
{
_AndroidJavaObject(className, (object)args);
}
///<summary>Construct an AndroidJavaObject based on the name of the class.</summary>
///<remarks>This essentially means locate the class type, allocate an object and run the specified constructor.</remarks>
///<param name="className">Specifies the Java class name (e.g. "<tt>java.lang.String</tt>" or "<tt>java/lang/String</tt>").</param>
///<param name="args">An array of parameters passed to the constructor.</param>
public AndroidJavaObject(string className, params object[] args) : this()
{
_AndroidJavaObject(className, args);
}
///<summary>Create AndroidJavaObject for existing Java object.</summary>
///<remarks>Does not take ownership of passed reference, you still have to delete it.</remarks>
///<param name="jobject">A reference to existing Java object.</param>
public AndroidJavaObject(IntPtr jobject) : this()
{
if (jobject == IntPtr.Zero)
{
throw new Exception("JNI: Init'd AndroidJavaObject with null ptr!");
}
IntPtr jclass = AndroidJNISafe.GetObjectClass(jobject);
m_jobject = new GlobalJavaObjectRef(jobject);
m_jclass = new GlobalJavaObjectRef(jclass);
AndroidJNISafe.DeleteLocalRef(jclass);
}
///<summary>Create AndroidJavaObject (and it's Java counterpart) using given Java class and constructor.</summary>
///<param name="clazz">A pointer to Java class.</param>
///<param name="constructorID">A method ID for the constructor to be used.</param>
///<param name="args">An array of parameters passed to the constructor.</param>
public AndroidJavaObject(IntPtr clazz, IntPtr constructorID, params object[] args)
{
m_jclass = new GlobalJavaObjectRef(clazz);
_AndroidJavaObject(constructorID, args);
}
//===================================================================
// IDisposable callback
///<summary>IDisposable callback.</summary>
///<remarks>Used in conjunction with using() { }</remarks>
///<seealso href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx">IDisposable Interface (MSDN)</seealso>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
//===================================================================
// Calls a Java method on an object (non-static).
///<summary>Calls a Java method on an object (non-static).</summary>
///<remarks>To call a method with return type 'void', use the regular version.</remarks>
///<param name="methodName">Specifies which method to call.</param>
///<param name="args">An array of parameters passed to the method.</param>
public void Call<T>(string methodName, T[] args)
{
_Call(methodName, (object)args);
}
///<summary>Calls a Java method on an object (non-static).</summary>
///<remarks>To call a method with return type 'void', use the regular version.</remarks>
///<param name="args">An array of parameters passed to the method.</param>
///<param name="methodID">The ID of the method to call.</param>
public void Call<T>(IntPtr methodID, T[] args)
{
_Call(methodID, (object)args);
}
///<summary>Calls a Java method on an object (non-static).</summary>
///<remarks>To call a method with return type 'void', use the regular version.</remarks>
///<param name="methodName">Specifies which method to call.</param>
///<param name="args">An array of parameters passed to the method.</param>
public void Call(string methodName, params object[] args)
{
_Call(methodName, args);
}
///<summary>Calls a Java method on an object (non-static).</summary>
///<remarks>To call a method with return type 'void', use the regular version.</remarks>
///<param name="args">An array of parameters passed to the method.</param>
///<param name="methodID">The ID of the method to call.</param>
public void Call(IntPtr methodID, params object[] args)
{
_Call(methodID, args);
}
//===================================================================
// Call a static Java method on a class.
///<summary>Call a static Java method on a class.</summary>
///<remarks>To call a static method with return type 'void', use the regular version.</remarks>
///<param name="methodName">Specifies which method to call.</param>
///<param name="args">An array of parameters passed to the method.</param>
public void CallStatic<T>(string methodName, T[] args)
{
_CallStatic(methodName, (object)args);
}
///<summary>Call a static Java method on a class.</summary>
///<remarks>To call a static method with return type 'void', use the regular version.</remarks>
///<param name="args">An array of parameters passed to the method.</param>
///<param name="methodID">The ID of the method to call.</param>
public void CallStatic<T>(IntPtr methodID, T[] args)
{
_CallStatic(methodID, (object)args);
}
///<summary>Call a static Java method on a class.</summary>
///<remarks>To call a static method with return type 'void', use the regular version.</remarks>
///<param name="methodName">Specifies which method to call.</param>
///<param name="args">An array of parameters passed to the method.</param>
public void CallStatic(string methodName, params object[] args)
{
_CallStatic(methodName, args);
}
///<summary>Call a static Java method on a class.</summary>
///<remarks>To call a static method with return type 'void', use the regular version.</remarks>
///<param name="args">An array of parameters passed to the method.</param>
///<param name="methodID">The ID of the method to call.</param>
public void CallStatic(IntPtr methodID, params object[] args)
{
_CallStatic(methodID, args);
}
//===================================================================
// Get the value of a field in an object (non-static).
///<summary>Get the value of a field in an object (non-static).</summary>
///<remarks>The generic parameter determines the field type.</remarks>
///<param name="fieldName">The name of the field (e.g. int counter; would have fieldName = "counter").</param>
public FieldType Get<FieldType>(string fieldName)
{
return _Get<FieldType>(fieldName);
}
///<summary>Get the value of a field in an object (non-static).</summary>
///<remarks>The generic parameter determines the field type.</remarks>
///<param name="fieldID">The ID of the field to get.</param>
public FieldType Get<FieldType>(IntPtr fieldID)
{
return _Get<FieldType>(fieldID);
}
// Set the value of a field in an object (non-static).
///<summary>Set the value of a field in an object (non-static).</summary>
///<remarks>The generic parameter determines the field type.</remarks>
///<param name="fieldName">The name of the field (e.g. int counter; would have fieldName = "counter").</param>
///<param name="val">The value to assign to the field. It has to match the field type.</param>
///<example>
/// <code><![CDATA[
///using UnityEngine;
///
///public class Example : MonoBehaviour
///{
/// void Start()
/// {
/// AndroidJavaObject javaObject = new AndroidJavaObject("android.text.format.Time");
/// javaObject.Set<bool>("allDay", true);
/// }
///}
///]]></code>
///</example>
public void Set<FieldType>(string fieldName, FieldType val)
{
_Set<FieldType>(fieldName, val);
}
///<summary>Set the value of a field in an object (non-static).</summary>
///<remarks>The generic parameter determines the field type.</remarks>
///<param name="fieldID">The ID of the field to set.</param>
///<param name="val">The value to assign to the field. It has to match the field type.</param>
public void Set<FieldType>(IntPtr fieldID, FieldType val)
{
_Set<FieldType>(fieldID, val);
}
//===================================================================
// Get the value of a static field in an object type.
///<summary>Get the value of a static field in an object type.</summary>
///<remarks>The generic parameter determines the field type.</remarks>
///<param name="fieldName">The name of the field (e.g. <i>int counter;</i> would have fieldName = "counter").</param>
public FieldType GetStatic<FieldType>(string fieldName)
{
return _GetStatic<FieldType>(fieldName);
}
///<summary>Get the value of a static field in an object type.</summary>
///<remarks>The generic parameter determines the field type.</remarks>
///<param name="fieldID">The ID of the field to get.</param>
public FieldType GetStatic<FieldType>(IntPtr fieldID)
{
return _GetStatic<FieldType>(fieldID);
}
// Set the value of a static field in an object type.
///<summary>Set the value of a static field in an object type.</summary>
///<remarks>The generic parameter determines the field type.</remarks>
///<param name="fieldName">The name of the field (e.g. int counter; would have fieldName = "counter").</param>
///<param name="val">The value to assign to the field. It has to match the field type.</param>
///<example>
/// <code><![CDATA[
///using UnityEngine;
///
///public class Example : MonoBehaviour
///{
/// // Create an object of user provided class org.example.StaticFields,
/// // and set the value of field 'globalName'.
/// void Start()
/// {
/// AndroidJavaObject javaObject = new AndroidJavaObject("org.example.StaticFields");
/// javaObject.Set<string>("globalName", "this_is_the_name");
/// }
///}
///]]></code>
///</example>
public void SetStatic<FieldType>(string fieldName, FieldType val)
{
_SetStatic<FieldType>(fieldName, val);
}
///<summary>Set the value of a static field in an object type.</summary>
///<remarks>The generic parameter determines the field type.</remarks>
///<param name="fieldID">The ID of the field to set.</param>
///<param name="val">The value to assign to the field. It has to match the field type.</param>
public void SetStatic<FieldType>(IntPtr fieldID, FieldType val)
{
_SetStatic<FieldType>(fieldID, val);
}
//===================================================================
// Retrieve the <i>raw</i> jobject pointer to the Java object.
///<summary>Retrieves the raw <c>jobject</c> pointer to the Java object.
///
///**Note:** Using raw JNI functions requires advanced knowledge of the Android Java Native Interface (JNI).</summary>
///<example>
/// <code><![CDATA[
///using System;
///using UnityEngine;
///
///public class AndroidJavaObjectGetRawObjectExample: MonoBehaviour
///{
/// void Start()
/// {
/// using (AndroidJavaObject javaObject = new AndroidJavaObject("com.example.exampleunityplugin.ExampleJavaClass"))
/// {
/// IntPtr rawObject = javaObject.GetRawObject();
/// string message = javaObject.Call<string>("getMessage");
///
/// Debug.Log("Message: " + message + " Pointer: "+ rawObject);
/// }
/// }
///}
///]]></code>
///</example>
///<seealso cref="AndroidJavaObject.GetRawClass" />
public IntPtr GetRawObject()
{
return _GetRawObject();
}
// Retrieve the <i>raw</i> jclass pointer to the Java class;
///<summary>Retrieves the raw <c>jclass</c> pointer to the Java class.
///
///**Note:** Using raw JNI functions requires advanced knowledge of the Android Java Native Interface (JNI).</summary>
///<seealso cref="AndroidJavaObject.GetRawObject" />
public IntPtr GetRawClass()
{
return _GetRawClass();
}
//===================================================================
///<summary>Creates a clone of the C# object that references the same Java object.</summary>
///<remarks>Allows you to create multiple C# instances referencing the same Java object. The Java object will be excluded from garbage collection until all the C# references to it are disposed or garbage collected.
///If you call this method on an <see cref="AndroidJavaClass" /> instance, the returned clone's type will also be AndroidJavaClass.</remarks>
///<returns>A new C# object which references the same Java object as the original instance.</returns>
public AndroidJavaObject CloneReference()
{
if (m_jclass == null)
throw new Exception("Cannot clone a disposed reference");
// if no object, assume this is AndroidJavaClass
if (m_jobject != null)
{
AndroidJavaObject clone = new AndroidJavaObject();
clone.m_jobject = new GlobalJavaObjectRef(m_jobject);
clone.m_jclass = new GlobalJavaObjectRef(m_jclass);
return clone;
}
else
return new AndroidJavaClass(m_jclass);
}
//===================================================================
// Call a Java method on an object.
///<summary>Call a Java method on an object.</summary>
///<remarks>To call a Java method with a non-void return type, use the generic version.</remarks>
///<param name="methodName">Specifies which method to call.</param>
///<param name="args">An array of parameters passed to the method.</param>
public ReturnType Call<ReturnType, T>(string methodName, T[] args)
{
return _Call<ReturnType>(methodName, (object)args);
}
///<summary>Calls a Java method on an object (non-static).</summary>
///<remarks>To call a Java method with a non-void return type, use the generic version.</remarks>
///<param name="args">An array of parameters passed to the method.</param>
///<param name="methodID">The ID of the method to call.</param>
public ReturnType Call<ReturnType, T>(IntPtr methodID, T[] args)
{
return _Call<ReturnType>(methodID, (object)args);
}
///<summary>Call a Java method on an object.</summary>
///<remarks>To call a Java method with a non-void return type, use the generic version.</remarks>
///<param name="methodName">Specifies which method to call.</param>
///<param name="args">An array of parameters passed to the method.</param>
public ReturnType Call<ReturnType>(string methodName, params object[] args)
{
return _Call<ReturnType>(methodName, args);
}
///<summary>Calls a Java method on an object (non-static).</summary>
///<remarks>To call a Java method with a non-void return type, use the generic version.</remarks>
///<param name="args">An array of parameters passed to the method.</param>
///<param name="methodID">The ID of the method to call.</param>
public ReturnType Call<ReturnType>(IntPtr methodID, params object[] args)
{
return _Call<ReturnType>(methodID, args);
}
// Call a static Java method on a class.
///<summary>Call a static Java method on a class.</summary>
///<remarks>To call a static method with a non-void return type, use the generic version.</remarks>
///<param name="methodName">Specifies which method to call.</param>
///<param name="args">An array of parameters passed to the method.</param>
public ReturnType CallStatic<ReturnType, T>(string methodName, T[] args)
{
return _CallStatic<ReturnType>(methodName, (object)args);
}
///<summary>Call a static Java method on a class.</summary>
///<remarks>To call a static method with a non-void return type, use the generic version.</remarks>
///<param name="args">An array of parameters passed to the method.</param>
///<param name="methodID">The ID of the method to call.</param>
public ReturnType CallStatic<ReturnType, T>(IntPtr methodID, T[] args)
{
return _CallStatic<ReturnType>(methodID, (object)args);
}
///<summary>Call a static Java method on a class.</summary>
///<remarks>To call a static method with a non-void return type, use the generic version.</remarks>
///<param name="methodName">Specifies which method to call.</param>
///<param name="args">An array of parameters passed to the method.</param>
public ReturnType CallStatic<ReturnType>(string methodName, params object[] args)
{
return _CallStatic<ReturnType>(methodName, args);
}
///<summary>Call a static Java method on a class.</summary>
///<remarks>To call a static method with a non-void return type, use the generic version.</remarks>
///<param name="args">An array of parameters passed to the method.</param>
///<param name="methodID">The ID of the method to call.</param>
public ReturnType CallStatic<ReturnType>(IntPtr methodID, params object[] args)
{
return _CallStatic<ReturnType>(methodID, args);
}
//===================================================================
[NoAutoStaticsCleanup]
private static bool enableDebugPrints = false;
protected void DebugPrint(string msg)
{
if (!enableDebugPrints)
return;
Debug.Log(msg);
}
protected void DebugPrint(string call, string methodName, string signature, object[] args)
{
if (!enableDebugPrints)
return;
StringBuilder sb = new StringBuilder();
foreach (object obj in args)
{
sb.Append(", ");
sb.Append(obj == null ? "<null>" : obj.GetType().ToString());
}
Debug.Log(call + "(\"" + methodName + "\"" + sb + ") = " + signature);
}
//===================================================================
private void _AndroidJavaObject(string className, params object[] args)
{
DebugPrint("Creating AndroidJavaObject from " + className);
var clazz = AndroidJNISafe.FindClass(className.Replace('.', '/'));
m_jclass = new GlobalJavaObjectRef(clazz);
AndroidJNISafe.DeleteLocalRef(clazz);
IntPtr constructorID = AndroidJNIHelper.GetConstructorID(m_jclass, args);
_AndroidJavaObject(constructorID, args);
}
private void _AndroidJavaObject(IntPtr constructorID, params object[] args)
{
Span<jvalue> jniArgs = (args == null || args.Length == 0) ? new Span<jvalue>() : stackalloc jvalue[args.Length];
AndroidJNIHelper.CreateJNIArgArray(args, jniArgs);
try
{
IntPtr jobject = AndroidJNISafe.NewObject(m_jclass, constructorID, jniArgs);
m_jobject = new GlobalJavaObjectRef(jobject);
AndroidJNISafe.DeleteLocalRef(jobject);
}
finally
{
AndroidJNIHelper.DeleteJNIArgArray(args, jniArgs);
}
}
internal AndroidJavaObject()
{
}
#pragma warning disable UA5000 // The Avoid Finalizer Analyzer produces compile errors for any new finalizers. This pre-existing finalizer declaration has been suppressed, but should be rewritten if possible.
~AndroidJavaObject()
{
Dispose(false);
}
#pragma warning restore UA5000
protected virtual void Dispose(bool disposing)
{
if (m_jobject != null)
{
m_jobject.Dispose();
m_jobject = null;
}
if (m_jclass != null)
{
m_jclass.Dispose();
m_jclass = null;
}
}
//===================================================================
protected void _Call(string methodName, params object[] args)
{
IntPtr methodID = AndroidJNIHelper.GetMethodID(m_jclass, methodName, args, false);
_Call(methodID, args);
}
protected void _Call(IntPtr methodID, params object[] args)
{
Span<jvalue> jniArgs = (args == null || args.Length == 0) ? new Span<jvalue>() : stackalloc jvalue[args.Length];
if (jniArgs.Length > 0)
{
AndroidJNISafe.PushLocalFrame(jniArgs.Length);
AndroidJNIHelper.CreateJNIArgArray(args, jniArgs);
}
try
{
AndroidJNISafe.CallVoidMethod(m_jobject, methodID, jniArgs);
}
finally
{
if (jniArgs.Length > 0)
AndroidJNI.PopLocalFrame(IntPtr.Zero);
}
}
protected ReturnType _Call<ReturnType>(string methodName, params object[] args)
{
IntPtr methodID = AndroidJNIHelper.GetMethodID<ReturnType>(m_jclass, methodName, args, false);
return _Call<ReturnType>(methodID, args);
}
protected ReturnType _Call<ReturnType>(IntPtr methodID, params object[] args)
{
Span<jvalue> jniArgs = (args == null || args.Length == 0) ? new Span<jvalue>() : stackalloc jvalue[args.Length];
AndroidJNI.PushLocalFrame(jniArgs.Length + 1);
AndroidJNIHelper.CreateJNIArgArray(args, jniArgs);
try
{
if (AndroidReflection.IsPrimitive(typeof(ReturnType)))
{
if (typeof(ReturnType) == typeof(Int32))
return (ReturnType)(object)AndroidJNISafe.CallIntMethod(m_jobject, methodID, jniArgs);
else if (typeof(ReturnType) == typeof(Boolean))
return (ReturnType)(object)AndroidJNISafe.CallBooleanMethod(m_jobject, methodID, jniArgs);
else if (typeof(ReturnType) == typeof(Byte))
{
Debug.LogWarning("Return type <Byte> for Java method call is obsolete, use return type <SByte> instead");
return (ReturnType)(object)(Byte)AndroidJNISafe.CallSByteMethod(m_jobject, methodID, jniArgs);
}
else if (typeof(ReturnType) == typeof(SByte))
return (ReturnType)(object)AndroidJNISafe.CallSByteMethod(m_jobject, methodID, jniArgs);
else if (typeof(ReturnType) == typeof(Int16))
return (ReturnType)(object)AndroidJNISafe.CallShortMethod(m_jobject, methodID, jniArgs);
else if (typeof(ReturnType) == typeof(Int64))
return (ReturnType)(object)AndroidJNISafe.CallLongMethod(m_jobject, methodID, jniArgs);
else if (typeof(ReturnType) == typeof(Single))
return (ReturnType)(object)AndroidJNISafe.CallFloatMethod(m_jobject, methodID, jniArgs);
else if (typeof(ReturnType) == typeof(Double))
return (ReturnType)(object)AndroidJNISafe.CallDoubleMethod(m_jobject, methodID, jniArgs);
else if (typeof(ReturnType) == typeof(Char))
return (ReturnType)(object)AndroidJNISafe.CallCharMethod(m_jobject, methodID, jniArgs);
}
else if (typeof(ReturnType) == typeof(String))
return (ReturnType)(object)AndroidJNISafe.CallStringMethod(m_jobject, methodID, jniArgs);
else if (typeof(ReturnType) == typeof(AndroidJavaClass))
{
IntPtr jclass = AndroidJNISafe.CallObjectMethod(m_jobject, methodID, jniArgs);
return (jclass == IntPtr.Zero) ? default(ReturnType) : (ReturnType)(object)new AndroidJavaClass(jclass);
}
else if (typeof(ReturnType) == typeof(AndroidJavaObject))
{
IntPtr jobject = AndroidJNISafe.CallObjectMethod(m_jobject, methodID, jniArgs);
return (jobject == IntPtr.Zero) ? default(ReturnType) : (ReturnType)(object)new AndroidJavaObject(jobject);
}
else if (AndroidReflection.IsAssignableFrom(typeof(Array), typeof(ReturnType)))
{
IntPtr jobject = AndroidJNISafe.CallObjectMethod(m_jobject, methodID, jniArgs);
return FromJavaArray<ReturnType>(jobject);
}
else
{
throw new Exception("JNI: Unknown return type '" + typeof(ReturnType) + "'");
}
return default(ReturnType);
}
finally
{
AndroidJNI.PopLocalFrame(IntPtr.Zero);
}
}
//===================================================================
protected FieldType _Get<FieldType>(string fieldName)
{
IntPtr fieldID = AndroidJNIHelper.GetFieldID<FieldType>(m_jclass, fieldName, false);
return _Get<FieldType>(fieldID);
}
protected FieldType _Get<FieldType>(IntPtr fieldID)
{
if (AndroidReflection.IsPrimitive(typeof(FieldType)))
{
if (typeof(FieldType) == typeof(Int32))
return (FieldType)(object)AndroidJNISafe.GetIntField(m_jobject, fieldID);
else if (typeof(FieldType) == typeof(Boolean))
return (FieldType)(object)AndroidJNISafe.GetBooleanField(m_jobject, fieldID);
else if (typeof(FieldType) == typeof(Byte))
{
Debug.LogWarning("Field type <Byte> for Java get field call is obsolete, use field type <SByte> instead");
return (FieldType)(object)(Byte)AndroidJNISafe.GetSByteField(m_jobject, fieldID);
}
else if (typeof(FieldType) == typeof(SByte))
return (FieldType)(object)AndroidJNISafe.GetSByteField(m_jobject, fieldID);
else if (typeof(FieldType) == typeof(Int16))
return (FieldType)(object)AndroidJNISafe.GetShortField(m_jobject, fieldID);
else if (typeof(FieldType) == typeof(Int64))
return (FieldType)(object)AndroidJNISafe.GetLongField(m_jobject, fieldID);
else if (typeof(FieldType) == typeof(Single))
return (FieldType)(object)AndroidJNISafe.GetFloatField(m_jobject, fieldID);
else if (typeof(FieldType) == typeof(Double))
return (FieldType)(object)AndroidJNISafe.GetDoubleField(m_jobject, fieldID);
else if (typeof(FieldType) == typeof(Char))
return (FieldType)(object)AndroidJNISafe.GetCharField(m_jobject, fieldID);
}
else if (typeof(FieldType) == typeof(String))
return (FieldType)(object)AndroidJNISafe.GetStringField(m_jobject, fieldID);
else if (typeof(FieldType) == typeof(AndroidJavaClass))
{
IntPtr jclass = AndroidJNISafe.GetObjectField(m_jobject, fieldID);
return (jclass == IntPtr.Zero) ? default(FieldType) : (FieldType)(object)AndroidJavaClassDeleteLocalRef(jclass);
}
else if (typeof(FieldType) == typeof(AndroidJavaObject))
{
IntPtr jobject = AndroidJNISafe.GetObjectField(m_jobject, fieldID);
return (jobject == IntPtr.Zero) ? default(FieldType) : (FieldType)(object)AndroidJavaObjectDeleteLocalRef(jobject);
}
else if (AndroidReflection.IsAssignableFrom(typeof(Array), typeof(FieldType)))
{
IntPtr jobject = AndroidJNISafe.GetObjectField(m_jobject, fieldID);
return FromJavaArrayDeleteLocalRef<FieldType>(jobject);
}
else
{
throw new Exception("JNI: Unknown field type '" + typeof(FieldType) + "'");
}
return default(FieldType);
}
protected void _Set<FieldType>(string fieldName, FieldType val)