Loading... BLE:低功耗蓝牙(BlueTooth Low Battery) ## 一.开发工具 Microsoft Visual Studio Community 2022 (64 位) - Preview 版本 17.2.0 Preview 2.0 ## 二.创建项目编写代码 创建MAUI项目。 通过nuget安装Plugin.BluetoothLE包。 在`AndroidManifest.xml`中添加 ```xml <uses-feature android:name="android.hardware.bluetooth" /> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> ``` 在`MainPage.xaml.cs`中添加命名空间`Plugin.BluetoothLE`引用。 在`public MainPage()`函数中添加如下代码: ```c# Debug.WriteLine("Owner Device Name:"+ CrossBleAdapter.Current.DeviceName); //检查蓝牙是否开启 if (CrossBleAdapter.Current.Status != AdapterStatus.PoweredOn) { Debug.WriteLine("Bluetooth is not turned on."); return; } //检查蓝牙是否在搜索设备 if (CrossBleAdapter.Current.IsScanning) CrossBleAdapter.Current.StopScan(); //启动设备发现,并订阅发现结果 var scanner = CrossBleAdapter.Current.Scan().Subscribe(async scanResult => { if (scanResult.Device.Name != null) { Debug.WriteLine($"DeviceName:{scanResult.Device.Name}"); scanResult.Device.WhenConnected().Subscribe(result => { Debug.WriteLine($"connected:{result}."); }); //连接设备 scanResult.Device.Connect(); } }); ``` 至此,初步尝试完成。 ## 三.后续 Plugin.BluetoothLE的教程网上搜了下,发现非常少。 只在下面链接找到了[API介绍](https://servocode.com/blog/servocode.com/blog/bluetooth-le-for-xamarin.forms-how-to-control-things-from-the-level-of-mobile-app),下一篇文章将继续对设备连接、关闭连接,设备配对(若需要),数据传输进行研究,谢谢~ 最后修改:2022 年 03 月 19 日 11 : 00 PM © 允许规范转载