Flutter蓝牙通信插件flutter_blue_plus_ohos的使用
Flutter蓝牙通信插件flutter_blue_plus_ohos的使用教程可以参考:https://www.itying.com/goods-1176.html
简介
flutter_blue_plus_ohos 是 Flutter 的蓝牙插件,支持蓝牙设备的扫描、连接、数据读写及状态监测。它简化了蓝牙通信的开发流程,适用于智能家居、健康监测等应用场景。
构建
拉取代码后进入到
cd ./example 执行 flutter build hap 可在example下编译出对应的har包
使用说明
1. 获取蓝牙关闭状态
// 注意:插件在首次调用任何FlutterBluePlus方法时进行初始化。
if (await FlutterBluePlus.isSupported == false) {
print("Bluetooth not supported by this device");
return;
}
// 处理蓝牙开启与关闭
// 注意:对于iOS,初始状态通常是BluetoothAdapterState.unknown
// 注意:如果权限有问题,可能会卡在BluetoothAdapterState.unauthorized
var subscription = FlutterBluePlus.adapterState.listen((BluetoothAdapterState state) {
print(state);
if (state == BluetoothAdapterState.on) {
// 通常开始扫描、连接等操作
} else {
// 向用户显示错误信息等
}
});
// 如果是Android或OHOS系统,可以自行打开蓝牙
if (Platform.isAndroid || Platform.operatingSystem == 'ohos') {
await FlutterBluePlus.turnOn();
}
// 取消监听以防止重复监听
subscription.cancel();
2. 扫描设备
// 监听扫描结果
// 注意:`onScanResults` 仅返回实时扫描结果,即在扫描过程中。如果您想获得实时扫描结果或之前的扫描结果,请使用 `scanResults`
var subscription = FlutterBluePlus.onScanResults.listen((results) {
if (results.isNotEmpty) {
ScanResult r = results.last; // 最近找到的设备
print('${r.device.remoteId}: "${r.advertisementData.advName}" found!');
}
},
onError: (e) => print(e),
);
// 清理:当扫描停止时取消订阅
FlutterBluePlus.cancelWhenScanComplete(subscription);
// 等待蓝牙启用及权限授予
// 在实际应用中,您应该使用 `FlutterBluePlus.adapterState.listen` 来处理所有状态
await FlutterBluePlus.adapterState.where((val) => val == BluetoothAdapterState.on).first;
// 开始扫描并设置超时
// 可选:使用 `stopScan()` 作为替代超时方案
await FlutterBluePlus.startScan(
withServices:[Guid("180D")], // 匹配指定的服务之一
withNames:["Bluno"], // 或匹配指定的名称之一
timeout: Duration(seconds:15));
// 等待扫描停止
await FlutterBluePlus.isScanning.where((val) => val == false).first;
3. 连接到设备
// 监听断开连接
var subscription = device.connectionState.listen((BluetoothConnectionState state) async {
if (state == BluetoothConnectionState.disconnected) {
// 1. 通常启动一个定时器,尝试重新连接,或者立即再次调用连接
// 2. 您必须在每次重新连接后重新发现服务!
print("${device.disconnectReason?.code} ${device.disconnectReason?.description}");
}
});
// 清理:断开连接时取消订阅
// - [delayed] 此选项仅适用于 `connectionState` 订阅。延迟取消。这确保 `connectionState` 监听器接收到 `disconnected` 事件。
// - [next] 如果为真,则该流仅在下次断开连接时取消,而不是当前断开连接。如果您在连接之前设置订阅,这很有用。
device.cancelWhenDisconnected(subscription, delayed:true, next:true);
// 连接到设备
await device.connect();
// 断开设备连接
await device.disconnect();
// 取消监听以防止重复监听
subscription.cancel();
4. MTU
final subscription = device.mtu.listen((int mtu) {
// iOS: 初始值始终为23,但iOS会很快协商更高的值
print("mtu $mtu");
});
// 清理:断开连接时取消订阅
device.cancelWhenDisconnected(subscription);
// 您也可以手动更改MTU
if (Platform.isAndroid || Platform.operatingSystem == 'ohos') {
await device.requestMtu(512);
}
5. 发现服务
// 注意:每次重新连接后都必须调用 discoverServices!
List<BluetoothService> services = await device.discoverServices();
services.forEach((service) {
// 对服务进行一些操作
});
6. 写入特性
// 向特征写入数据
await c.write([0x12, 0x34]);
allowLongWrite:要写入大型特征(最多 512 字节),而不考虑 mtu,请使用:allowLongWrite
await c.write(data, allowLongWrite:true);
7. 订阅特征
final subscription = characteristic.onValueReceived.listen((value) {
// onValueReceived 更新:
// - 任何时间调用 read()
// - 任何时间接收到通知(如果已订阅)
});
// 清理:断开连接时取消订阅
device.cancelWhenDisconnected(subscription);
// 订阅
// 注意:如果一个特征同时支持 **通知** 和 **指示**,则默认情况下将使用 **通知**。这符合iOS上的CoreBluetooth工作方式。
await characteristic.setNotifyValue(true);
8. 读取和写入描述符
// 读取所有描述符
var descriptors = characteristic.descriptors;
for(BluetoothDescriptor d in descriptors) {
List<int> value = await d.read();
print(value);
}
// 向描述符写入数据
await d.write([0x12, 0x34])
9. 获取互联设备
List<BluetoothDevice> devs = FlutterBluePlus.connectedDevices;
for (var d in devs) {
print(d);
}更多关于Flutter蓝牙通信插件flutter_blue_plus_ohos的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter蓝牙通信插件flutter_blue_plus_ohos的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
flutter_blue_plus_ohos 是一个用于在 Flutter 应用中实现蓝牙通信的插件,特别针对 OpenHarmony (OHOS) 平台进行了优化。它基于 flutter_blue_plus 插件,并提供了对 OHOS 平台的额外支持。以下是如何使用 flutter_blue_plus_ohos 插件进行蓝牙通信的基本步骤。
1. 添加依赖
首先,在 pubspec.yaml 文件中添加 flutter_blue_plus_ohos 插件的依赖:
dependencies:
flutter:
sdk: flutter
flutter_blue_plus_ohos: ^1.0.0 # 请根据实际版本号进行替换
然后运行 flutter pub get 来获取依赖。
2. 初始化插件
在你的 Dart 代码中,首先需要初始化 flutter_blue_plus_ohos 插件。
import 'package:flutter_blue_plus_ohos/flutter_blue_plus_ohos.dart';
class BluetoothManager {
final FlutterBluePlusOhos flutterBlue = FlutterBluePlusOhos.instance;
Future<void> initBluetooth() async {
// 检查蓝牙是否可用
bool isAvailable = await flutterBlue.isAvailable;
if (!isAvailable) {
print("Bluetooth is not available on this device.");
return;
}
// 检查蓝牙是否开启
bool isOn = await flutterBlue.isOn;
if (!isOn) {
print("Bluetooth is not on.");
return;
}
print("Bluetooth is ready to use.");
}
}
3. 扫描设备
你可以使用 flutterBlue.startScan 方法来扫描附近的蓝牙设备。
Future<void> scanDevices() async {
// 开始扫描
flutterBlue.startScan(timeout: Duration(seconds: 4));
// 监听扫描结果
flutterBlue.scanResults.listen((results) {
for (ScanResult result in results) {
print("Found device: ${result.device.name} (${result.device.id})");
}
});
// 停止扫描
await Future.delayed(Duration(seconds: 4));
flutterBlue.stopScan();
}
4. 连接设备
扫描到设备后,你可以使用 device.connect 方法来连接设备。
Future<void> connectToDevice(BluetoothDevice device) async {
// 连接设备
await device.connect();
// 监听连接状态
device.state.listen((state) {
if (state == BluetoothDeviceState.connected) {
print("Device connected");
} else if (state == BluetoothDeviceState.disconnected) {
print("Device disconnected");
}
});
}
5. 发现服务与特征
连接成功后,你可以发现设备提供的服务和特征。
Future<void> discoverServices(BluetoothDevice device) async {
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}");
}
}
}
6. 读取和写入特征
你可以使用 characteristic.read 和 characteristic.write 方法来读取和写入特征值。
Future<void> readCharacteristic(BluetoothCharacteristic characteristic) async {
List<int> value = await characteristic.read();
print("Characteristic value: $value");
}
Future<void> writeCharacteristic(BluetoothCharacteristic characteristic, List<int> value) async {
await characteristic.write(value);
print("Characteristic value written");
}
7. 断开连接
使用 device.disconnect 方法来断开设备连接。
Future<void> disconnectDevice(BluetoothDevice device) async {
await device.disconnect();
print("Device disconnected");
}
8. 处理权限
在 OHOS 平台上,使用蓝牙可能需要特定的权限。确保在 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"/>
9. 处理错误
在实际使用中,可能会遇到各种错误,如连接失败、权限问题等。确保在代码中添加适当的错误处理逻辑。
try {
await connectToDevice(device);
} catch (e) {
print("Failed to connect to device: $e");
}
10. 完整示例
以下是一个完整的示例,展示了如何使用 flutter_blue_plus_ohos 插件进行蓝牙通信:
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus_ohos/flutter_blue_plus_ohos.dart';
class BluetoothApp extends StatefulWidget {
[@override](/user/override)
_BluetoothAppState createState() => _BluetoothAppState();
}
class _BluetoothAppState extends State<BluetoothApp> {
final FlutterBluePlusOhos flutterBlue = FlutterBluePlusOhos.instance;
List<BluetoothDevice> devices = [];
[@override](/user/override)
void initState() {
super.initState();
initBluetooth();
}
Future<void> initBluetooth() async {
bool isAvailable = await flutterBlue.isAvailable;
if (!isAvailable) {
print("Bluetooth is not available on this device.");
return;
}
bool isOn = await flutterBlue.isOn;
if (!isOn) {
print("Bluetooth is not on.");
return;
}
print("Bluetooth is ready to use.");
}
Future<void> scanDevices() async {
flutterBlue.startScan(timeout: Duration(seconds: 4));
flutterBlue.scanResults.listen((results) {
setState(() {
devices = results.map((result) => result.device).toList();
});
});
await Future.delayed(Duration(seconds: 4));
flutterBlue.stopScan();
}
Future<void> connectToDevice(BluetoothDevice device) async {
await device.connect();
print("Device connected");
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}");
}
}
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Bluetooth App"),
),
body: ListView.builder(
itemCount: devices.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(devices[index].name ?? "Unknown Device"),
subtitle: Text(devices[index].id.toString()),
onTap: () => connectToDevice(devices[index]),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: scanDevices,
child: Icon(Icons.search),
),
);
}
}
void main() => runApp(MaterialApp(
home: BluetoothApp(),
));

