首页 > 解决方案 > 在 Xamarin.iOS 中检查蓝牙状态(开/关)

问题描述

我正在寻找一种获取设备蓝牙状态的功能,这样我就可以告诉应用程序用户它是打开还是关闭。

当前代码一直说蓝牙已关闭,即使它已打开。任何帮助和指导表示赞赏!

public bool CheckBluetoothStatus()
        {
            bool status;

            if (state == CBCentralManagerState.PoweredOn)
            {
                status = true;
                bluetoothEnabledLbl.Text = "Bluetooth enabled";
                bluetoothEnabledAdviceLbl.Text = "Consider turning Bluetooth off if not in use or check to see if all connected devices are recognisable";

                return status;
            }
            else
            {
                status = false;
                bluetoothEnabledLbl.Text = "Bluetooth not enabled";

                return status;
            }
        }

标签: c#iphonebluetoothxamarin.ios

解决方案


开发Xamarin iOS 蓝牙应用程序有两点需要注意。

  • 首先,需要在物理设备上运行,不能在模拟器设备上测试蓝牙功能。如果是这样,您将始终使用共享代码获得关注控制台日志:

2020-02-28 13:32:38.310442+0800 AppIOSBluetooth[36757:5394891] 蓝牙未启用

  • 其次,您需要在info.plist文件中添加蓝牙应用程序的权限。第一次运行应用程序时,它会显示权限弹出窗口。

在此处输入图像描述

但是,在中info.plist,您可以像下面这样轻松添加蓝牙权限,而忘记另一个最重要的权限:

<key>NSBluetoothPeripheralUsageDescription</key>
<string>Add BlueTooth Peripheral Permission</string>

这对蓝牙来说还不够。您还需要添加另一个权限:

<key>NSBluetoothAlwaysUsageDescription</key>
<string>use Bluetooth</string>

此外,还有一个关于在 Xamarin iOS 中使用蓝牙的官方 API 文档,你可以看看。

public override void ViewDidLoad ()
{
    base.ViewDidLoad ();
    // Perform any additional setup after loading the view, typically from a nib.
    myDel = new MySimpleCBCentralManagerDelegate();
    var myMgr = new CBCentralManager(myDel, DispatchQueue.CurrentQueue);
}

public class MySimpleCBCentralManagerDelegate : CBCentralManagerDelegate
{
    override public void UpdatedState(CBCentralManager mgr)
    {
        if (mgr.State == CBCentralManagerState.PoweredOn)
        {
            Console.WriteLine("Bluetooth is available");
            //Passing in null scans for all peripherals. Peripherals can be targeted by using CBUIIDs
            CBUUID[] cbuuids = null;
            mgr.ScanForPeripherals(cbuuids); //Initiates async calls of DiscoveredPeripheral
                                                //Timeout after 30 seconds
            var timer = new Timer(30 * 1000);
            timer.Elapsed += (sender, e) => mgr.StopScan();
        }
        else
        {
            //Invalid state -- Bluetooth powered down, unavailable, etc.
            System.Console.WriteLine("Bluetooth is not available");
        }
    }
    public override void DiscoveredPeripheral(CBCentralManager central, CBPeripheral peripheral, NSDictionary advertisementData, NSNumber RSSI)
    {
        Console.WriteLine("Discovered {0}, data {1}, RSSI {2}", peripheral.Name, advertisementData, RSSI);
    }

}

推荐阅读