Flutter 中利用 BLE 蓝牙(基于 flutter_blue_plus)

打印 上一主题 下一主题

主题 1692|帖子 1692|积分 5076

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本指南将详细介绍如安在 Flutter 应用中利用 flutter_blue_plus 插件实现 BLE 蓝牙功能,包括扫描、毗连、读写特性值等操作。
1. 添加依赖
pubspec.yaml 中添加 flutter_blue_plus 依赖:
  1. dependencies:
  2.   flutter:
  3.     sdk: flutter
  4.   flutter_blue_plus: ^1.10.0 # 使用最新版本
复制代码
运行以下下令安装依赖
  1. flutter pub get
复制代码
2. 配置权限
BLE 蓝牙需要蓝牙和位置权限。
Android
AndroidManifest.xml 中添加以下权限:
  1. <uses-permission android:name="android.permission.BLUETOOTH"/>
  2. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
  3. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  4. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
  5. <uses-permission android:name="android.permission.BLUETOOTH_SCAN"/>
  6. <uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
复制代码
对于 Android 12 及以上版本,还需要添加以下配置:
  1. <uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
  2. <uses-feature android:name="android.hardware.location" android:required="true"/>
复制代码
iOS
Info.plist 中添加以下权限:
  1. <key>NSBluetoothAlwaysUsageDescription</key>
  2. <string>我们需要访问蓝牙来连接设备</string>
  3. <key>NSBluetoothPeripheralUsageDescription</key>
  4. <string>我们需要访问蓝牙来连接设备</string>
  5. <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
  6. <string>我们需要访问位置来扫描蓝牙设备</string>
  7. <key>NSLocationWhenInUseUsageDescription</key>
  8. <string>我们需要访问位置来扫描蓝牙设备</string>
复制代码
3. 封装 BLE 工具类
创建一个 BluetoothManager 类,封装 BLE 蓝牙的常用操作。
  1. import 'package:flutter_blue_plus/flutter_blue_plus.dart';
  2. class BluetoothManager {
  3.   static final BluetoothManager _instance = BluetoothManager._internal();
  4.   FlutterBluePlus flutterBlue = FlutterBluePlus.instance;
  5.   // 当前连接的设备
  6.   BluetoothDevice? _connectedDevice;
  7.   // 当前连接的服务和特征
  8.   BluetoothService? _connectedService;
  9.   BluetoothCharacteristic? _connectedCharacteristic;
  10.   // 扫描到的设备列表
  11.   List<BluetoothDevice> devices = [];
  12.   // 私有构造函数
  13.   BluetoothManager._internal();
  14.   // 单例模式
  15.   factory BluetoothManager() {
  16.     return _instance;
  17.   }
  18.   // 开始扫描设备
  19.   Future<void> startScan({Duration? timeout}) async {
  20.     devices.clear();
  21.     flutterBlue.startScan(timeout: timeout);
  22.     flutterBlue.scanResults.listen((results) {
  23.       for (ScanResult result in results) {
  24.         if (!devices.contains(result.device)) {
  25.           devices.add(result.device);
  26.         }
  27.       }
  28.     });
  29.   }
  30.   // 停止扫描
  31.   Future<void> stopScan() async {
  32.     flutterBlue.stopScan();
  33.   }
  34.   // 连接设备
  35.   Future<void> connectToDevice(BluetoothDevice device) async {
  36.     await device.connect();
  37.     _connectedDevice = device;
  38.     print('Connected to ${device.name}');
  39.     // 发现服务
  40.     List<BluetoothService> services = await device.discoverServices();
  41.     for (BluetoothService service in services) {
  42.       print('Service: ${service.uuid}');
  43.       for (BluetoothCharacteristic characteristic in service.characteristics) {
  44.         print('Characteristic: ${characteristic.uuid}');
  45.       }
  46.     }
  47.   }
  48.   // 断开连接
  49.   Future<void> disconnectDevice() async {
  50.     if (_connectedDevice != null) {
  51.       await _connectedDevice!.disconnect();
  52.       _connectedDevice = null;
  53.       _connectedService = null;
  54.       _connectedCharacteristic = null;
  55.       print('Disconnected');
  56.     }
  57.   }
  58.   // 设置当前服务和特征
  59.   void setConnectedServiceAndCharacteristic(
  60.       BluetoothService service, BluetoothCharacteristic characteristic) {
  61.     _connectedService = service;
  62.     _connectedCharacteristic = characteristic;
  63.   }
  64.   // 读取特征值
  65.   Future<List<int>> readCharacteristic() async {
  66.     if (_connectedCharacteristic != null) {
  67.       return await _connectedCharacteristic!.read();
  68.     }
  69.     throw Exception('No characteristic selected');
  70.   }
  71.   // 写入特征值
  72.   Future<void> writeCharacteristic(List<int> value) async {
  73.     if (_connectedCharacteristic != null) {
  74.       await _connectedCharacteristic!.write(value);
  75.     } else {
  76.       throw Exception('No characteristic selected');
  77.     }
  78.   }
  79.   // 监听特征值通知
  80.   Future<void> setNotification(bool enable) async {
  81.     if (_connectedCharacteristic != null) {
  82.       await _connectedCharacteristic!.setNotifyValue(enable);
  83.       if (enable) {
  84.         _connectedCharacteristic!.value.listen((value) {
  85.           print('Notification value: $value');
  86.         });
  87.       }
  88.     } else {
  89.       throw Exception('No characteristic selected');
  90.     }
  91.   }
  92.   // 获取已连接的设备
  93.   BluetoothDevice? get connectedDevice => _connectedDevice;
  94.   // 获取已连接的服务
  95.   BluetoothService? get connectedService => _connectedService;
  96.   // 获取已连接的特征
  97.   BluetoothCharacteristic? get connectedCharacteristic => _connectedCharacteristic;
  98. }
复制代码
4. 在 Flutter 应用中利用
以下是一个简单的 Flutter 应用示例,展示怎样利用 BluetoothManager 类。
  1. import 'package:flutter/material.dart';
  2. import 'bluetooth_manager.dart'; // 导入蓝牙工具类
  3. void main() => runApp(MyApp());
  4. class MyApp extends StatelessWidget {
  5.   @override
  6.   Widget build(BuildContext context) {
  7.     return MaterialApp(
  8.       home: BluetoothApp(),
  9.     );
  10.   }
  11. }
  12. class BluetoothApp extends StatefulWidget {
  13.   @override
  14.   _BluetoothAppState createState() => _BluetoothAppState();
  15. }
  16. class _BluetoothAppState extends State<BluetoothApp> {
  17.   final BluetoothManager bluetoothManager = BluetoothManager();
  18.   @override
  19.   void initState() {
  20.     super.initState();
  21.     bluetoothManager.startScan(timeout: Duration(seconds: 4));
  22.   }
  23.   @override
  24.   Widget build(BuildContext context) {
  25.     return Scaffold(
  26.       appBar: AppBar(
  27.         title: Text('Flutter BLE Example'),
  28.       ),
  29.       body: Column(
  30.         children: [
  31.           Expanded(
  32.             child: ListView.builder(
  33.               itemCount: bluetoothManager.devices.length,
  34.               itemBuilder: (context, index) {
  35.                 return ListTile(
  36.                   title: Text(bluetoothManager.devices[index].name ?? 'Unknown device'),
  37.                   subtitle: Text(bluetoothManager.devices[index].id.toString()),
  38.                   onTap: () async {
  39.                     await bluetoothManager.connectToDevice(bluetoothManager.devices[index]);
  40.                     setState(() {});
  41.                   },
  42.                 );
  43.               },
  44.             ),
  45.           ),
  46.           if (bluetoothManager.connectedDevice != null)
  47.             Padding(
  48.               padding: const EdgeInsets.all(16.0),
  49.               child: Column(
  50.                 children: [
  51.                   Text('Connected to: ${bluetoothManager.connectedDevice!.name}'),
  52.                   ElevatedButton(
  53.                     onPressed: () async {
  54.                       await bluetoothManager.disconnectDevice();
  55.                       setState(() {});
  56.                     },
  57.                     child: Text('Disconnect'),
  58.                   ),
  59.                 ],
  60.               ),
  61.             ),
  62.         ],
  63.       ),
  64.     );
  65.   }
  66. }
复制代码
5. 功能阐明
扫描设备:通过 startScan 方法扫描附近的 BLE 设备。
毗连设备:通过 connectToDevice 方法毗连设备,并自动发现服务和特性。
读写特性值:通过 readCharacteristic 和 writeCharacteristic 方法读写特性值。
监听通知:通过 setNotification 方法监听特性值的通知。
6. 注意事项
权限:确保在 Android 和 iOS 上精确配置蓝牙和位置权限。
动态权限请求:在高版本系统中,需要在运行时动态请求权限。
设备兼容性:不同设备的 BLE 实现大概有所不同,确保测试你的应用在各种设备上的兼容性。
通过以上步骤,你可以在 Flutter 应用中轻松实现 BLE 蓝牙功能。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

金歌

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表