金歌 发表于 前天 14:08

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

本指南将详细介绍如安在 Flutter 应用中利用 flutter_blue_plus 插件实现 BLE 蓝牙功能,包括扫描、毗连、读写特性值等操作。
1. 添加依赖
在 pubspec.yaml 中添加 flutter_blue_plus 依赖:
dependencies:
flutter:
    sdk: flutter
flutter_blue_plus: ^1.10.0 # 使用最新版本
运行以下下令安装依赖:
flutter pub get
2. 配置权限
BLE 蓝牙需要蓝牙和位置权限。
Android
在 AndroidManifest.xml 中添加以下权限:
<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"/>
<uses-permission android:name="android.permission.BLUETOOTH_SCAN"/>
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
对于 Android 12 及以上版本,还需要添加以下配置:
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
<uses-feature android:name="android.hardware.location" android:required="true"/>
iOS
在 Info.plist 中添加以下权限:
<key>NSBluetoothAlwaysUsageDescription</key>
<string>我们需要访问蓝牙来连接设备</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>我们需要访问蓝牙来连接设备</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>我们需要访问位置来扫描蓝牙设备</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>我们需要访问位置来扫描蓝牙设备</string>
3. 封装 BLE 工具类
创建一个 BluetoothManager 类,封装 BLE 蓝牙的常用操作。
import 'package:flutter_blue_plus/flutter_blue_plus.dart';

class BluetoothManager {
static final BluetoothManager _instance = BluetoothManager._internal();
FlutterBluePlus flutterBlue = FlutterBluePlus.instance;

// 当前连接的设备
BluetoothDevice? _connectedDevice;

// 当前连接的服务和特征
BluetoothService? _connectedService;
BluetoothCharacteristic? _connectedCharacteristic;

// 扫描到的设备列表
List<BluetoothDevice> devices = [];

// 私有构造函数
BluetoothManager._internal();

// 单例模式
factory BluetoothManager() {
    return _instance;
}

// 开始扫描设备
Future<void> startScan({Duration? timeout}) async {
    devices.clear();
    flutterBlue.startScan(timeout: timeout);

    flutterBlue.scanResults.listen((results) {
      for (ScanResult result in results) {
      if (!devices.contains(result.device)) {
          devices.add(result.device);
      }
      }
    });
}

// 停止扫描
Future<void> stopScan() async {
    flutterBlue.stopScan();
}

// 连接设备
Future<void> connectToDevice(BluetoothDevice device) async {
    await device.connect();
    _connectedDevice = device;
    print('Connected to ${device.name}');

    // 发现服务
    List<BluetoothService> services = await device.discoverServices();
    for (BluetoothService service in services) {
      print('Service: ${service.uuid}');
      for (BluetoothCharacteristic characteristic in service.characteristics) {
      print('Characteristic: ${characteristic.uuid}');
      }
    }
}

// 断开连接
Future<void> disconnectDevice() async {
    if (_connectedDevice != null) {
      await _connectedDevice!.disconnect();
      _connectedDevice = null;
      _connectedService = null;
      _connectedCharacteristic = null;
      print('Disconnected');
    }
}

// 设置当前服务和特征
void setConnectedServiceAndCharacteristic(
      BluetoothService service, BluetoothCharacteristic characteristic) {
    _connectedService = service;
    _connectedCharacteristic = characteristic;
}

// 读取特征值
Future<List<int>> readCharacteristic() async {
    if (_connectedCharacteristic != null) {
      return await _connectedCharacteristic!.read();
    }
    throw Exception('No characteristic selected');
}

// 写入特征值
Future<void> writeCharacteristic(List<int> value) async {
    if (_connectedCharacteristic != null) {
      await _connectedCharacteristic!.write(value);
    } else {
      throw Exception('No characteristic selected');
    }
}

// 监听特征值通知
Future<void> setNotification(bool enable) async {
    if (_connectedCharacteristic != null) {
      await _connectedCharacteristic!.setNotifyValue(enable);
      if (enable) {
      _connectedCharacteristic!.value.listen((value) {
          print('Notification value: $value');
      });
      }
    } else {
      throw Exception('No characteristic selected');
    }
}

// 获取已连接的设备
BluetoothDevice? get connectedDevice => _connectedDevice;

// 获取已连接的服务
BluetoothService? get connectedService => _connectedService;

// 获取已连接的特征
BluetoothCharacteristic? get connectedCharacteristic => _connectedCharacteristic;
}
4. 在 Flutter 应用中利用
以下是一个简单的 Flutter 应用示例,展示怎样利用 BluetoothManager 类。
import 'package:flutter/material.dart';
import 'bluetooth_manager.dart'; // 导入蓝牙工具类

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
    return MaterialApp(
      home: BluetoothApp(),
    );
}
}

class BluetoothApp extends StatefulWidget {
@override
_BluetoothAppState createState() => _BluetoothAppState();
}

class _BluetoothAppState extends State<BluetoothApp> {
final BluetoothManager bluetoothManager = BluetoothManager();

@override
void initState() {
    super.initState();
    bluetoothManager.startScan(timeout: Duration(seconds: 4));
}

@override
Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
      title: Text('Flutter BLE Example'),
      ),
      body: Column(
      children: [
          Expanded(
            child: ListView.builder(
            itemCount: bluetoothManager.devices.length,
            itemBuilder: (context, index) {
                return ListTile(
                  title: Text(bluetoothManager.devices.name ?? 'Unknown device'),
                  subtitle: Text(bluetoothManager.devices.id.toString()),
                  onTap: () async {
                  await bluetoothManager.connectToDevice(bluetoothManager.devices);
                  setState(() {});
                  },
                );
            },
            ),
          ),
          if (bluetoothManager.connectedDevice != null)
            Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
                children: [
                  Text('Connected to: ${bluetoothManager.connectedDevice!.name}'),
                  ElevatedButton(
                  onPressed: () async {
                      await bluetoothManager.disconnectDevice();
                      setState(() {});
                  },
                  child: Text('Disconnect'),
                  ),
                ],
            ),
            ),
      ],
      ),
    );
}
}
5. 功能阐明
扫描设备:通过 startScan 方法扫描附近的 BLE 设备。
毗连设备:通过 connectToDevice 方法毗连设备,并自动发现服务和特性。
读写特性值:通过 readCharacteristic 和 writeCharacteristic 方法读写特性值。
监听通知:通过 setNotification 方法监听特性值的通知。
6. 注意事项
权限:确保在 Android 和 iOS 上精确配置蓝牙和位置权限。
动态权限请求:在高版本系统中,需要在运行时动态请求权限。
设备兼容性:不同设备的 BLE 实现大概有所不同,确保测试你的应用在各种设备上的兼容性。
通过以上步骤,你可以在 Flutter 应用中轻松实现 BLE 蓝牙功能。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: Flutter 中利用 BLE 蓝牙(基于 flutter_blue_plus)