jeudi 17 mai 2018

Turning Bluetooth Tethering On in Xamarin.Android

I'm currently trying to add some Bluetooth functionality to my app. I want to be able to change the Bluetooth Tethering on or off, as well as check its status.

I found the Java code on StackOverflow: How to check Bluetooth tethering status programmatically in Android

I have translated it into C#, but I don't seem to be able to get any result.

Regardless of the tethering setting, it always shows the toast with "Tethering:false", and the setBluetoothTethering doesn't change anything.

Any idea what I'm missing?

Here's my code:

[...]
        try
        {
            Class classBluetoothPan = Class.ForName("android.bluetooth.BluetoothPan");

            Method mBTPanConnect = classBluetoothPan.GetDeclaredMethod("connect", Class.FromType(typeof(BluetoothDevice)));

            Constructor BTPanCtor = classBluetoothPan.GetDeclaredConstructor(Class.FromType(typeof(Context)), Class.FromType(typeof(IBluetoothProfileServiceListener)));

            BTPanCtor.Accessible = true;

            Java.Lang.Object BTSrvInstance = BTPanCtor.NewInstance(Activity, new BTPanServiceListener(Activity));

            Method isTetheringOnMethod = classBluetoothPan.GetDeclaredMethod("isTetheringOn", null);

            var isTetheringOn = isTetheringOnMethod.Invoke(BTSrvInstance);

            Toast.MakeText(Activity, "Tethering:" + isTetheringOn, ToastLength.Short).Show();

            Method setBluetoothTetheringMethod = classBluetoothPan.GetDeclaredMethod("setBluetoothTethering", new Class[1] { Class.FromType(typeof(bool)) });

            setBluetoothTetheringMethod.Invoke(BTSrvInstance, true);

            // tether = !tether;

        }
        catch (ClassNotFoundException e)
        {
            e.PrintStackTrace();
        }
        catch (Java.Lang.Exception e)
        {
            e.PrintStackTrace();
        }
[...]


public class BTPanServiceListener : Java.Lang.Object, IBluetoothProfileServiceListener
{

    private Activity _activity;

    public BTPanServiceListener(Activity activity)
    {
        _activity = activity;
    }

    public void OnServiceConnected([GeneratedEnum] ProfileType profile, IBluetoothProfile proxy)
    {
        // throw new NotImplementedException();
    }

    public void OnServiceDisconnected([GeneratedEnum] ProfileType profile)
    {
        // throw new NotImplementedException();
    }
}





Aucun commentaire:

Enregistrer un commentaire