简体   繁体   中英

Java.Lang GetClass within C#

I am trying to pass a pin to a Bluetooth device within my own receiver on the Android part of my Xamarin Forms application. I am getting the correct action stage, but am having issues getting the setPin and convertPinToBytes method. I followed the suggestion found here: https://stackoverflow.com/a/19776382/13902576 , but I am having trouble converting this into C#.

My implementation is as below:

var convert = device.BluetoothClass.Class.GetMethod("convertPinToBytes", Java.Lang.Class.FromType(typeof(Java.Lang.String)));
byte[] pin = (byte[])convert.Invoke(device.BluetoothClass.Class, "1234");
var setPin = device.BluetoothClass.Class.GetMethod("setPin", Java.Lang.Class.FromType(typeof(Java.Lang.Byte)));
var connectResult = (bool)setPin.Invoke(device, pin);
Console.WriteLine(connectResult);

I am getting the following exception:

java.lang.NoSuchMethodException: convertPinToBytes [class java.lang.String]
at java.lang.Class.getMethod(Class.java:2068)
at java.lang.Class.getMethod(Class.java:1690)
at crc6444c83b34196acfb6.BluetoothInstance_BluetoothReceiver.n_onReceive(Native Method)
at crc6444c83b34196acfb6.BluetoothInstance_BluetoothReceiver.onReceive(BluetoothInstance_BluetoothReceiver.java:29)
at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$-android_app_LoadedApk$ReceiverDispatcher$Args_52226(LoadedApk.java:1319)
at android.app.-$Lambda$FilBqgnXJrN9Mgyks1XHeAxzSTk.$m$0(Unknown Source:4)
at android.app.-$Lambda$FilBqgnXJrN9Mgyks1XHeAxzSTk.run(Unknown Source:0)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

Any suggestions would be appreciated, thanks!

There appeared to be a native solution within C#. As there is a instance of the BluetoothDevice class within C#, some of these methods are available.

The solution could be greatly simplified using by doing:

byte[] pin = Encoding.UTF8.GetBytes("1234");
var setPin = device.SetPin(pin);

I ended up fixing the first method error using instead:

var deviceClass = Java.Lang.Class.ForName(device.Class.CanonicalName);
var convert = deviceClass.GetMethod("convertPinToBytes", Java.Lang.Class.FromType(typeof(Java.Lang.String)));

I could not fix the setPin method error. However, my final solution is from example one above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM