c# - 在 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;
}
}
解决方案
开发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);
}
}
推荐阅读
- javascript - 如何增加底部和第一个 Y 轴标签与底部图表线之间的空间?
- python - 如果 __name__ == '__main__' 不适用于 unittest
- android - 无法使用 Fastlane 将 Android APK 上传到 Google Play 商店
- symfony - Symfony 4 - 设置日期时间
- perl - 在 perl 中更改 xml 文件
- ms-access - 替代环境(“用户名”)
- javascript - Javascript 正则表达式检查字符串中至少 3 个插入符号
- node.js - 如何在 Multer-s3 中使用动态存储桶名称进行文件上传
- ruby-on-rails - Rails 多个 mongo db 连接,但具有相同的模型名称。
- java - 设置 Glassfish 数据源问题