在Xamarin.Android中打开蓝牙连接

时间:2018-05-17 09:27:51

标签: xamarin bluetooth xamarin.android tethering

我目前正在尝试为我的应用添加一些蓝牙功能。我希望能够打开或关闭蓝牙连接,并检查其状态。

我在StackOverflow上找到了Java代码:How to check Bluetooth tethering status programmatically in Android

我已将其翻译成C#,但我似乎无法获得任何结果。

无论绑定设置如何,它始终显示“Tethering:false”的toast,而setBluetoothTethering不会改变任何内容。

知道我缺少什么吗?

这是我的代码:

[...]
        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();
    }
}

1 个答案:

答案 0 :(得分:0)

我了解了如何通过setBluetoothTethering启用蓝牙网络共享。

我为此写了entire blog

您可以找到最终代码here

我认为isTetheringOn的工作方式相同