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[index].name ?? 'Unknown device'),
                  subtitle: Text(bluetoothManager.devices[index].id.toString()),
                  onTap: () async {
                    await bluetoothManager.connectToDevice(bluetoothManager.devices[index]);
                    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 蓝牙功能。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值