Flutter低功耗蓝牙通信插件bluetooth_low_energy_android的使用
Flutter低功耗蓝牙通信插件bluetooth_low_energy_android的使用
bluetooth_low_energy_android
是 bluetooth_low_energy
包在 Android 平台上的实现。此包是被官方支持的(即“endorsed”),因此你可以直接使用 bluetooth_low_energy
。
使用
当你使用 bluetooth_low_energy
包时,它会自动包含在这个应用中,因此你不需要将其添加到你的 pubspec.yaml
文件中。但是,如果你需要导入这个包以直接使用其 API,你应该像平常一样将其添加到你的 pubspec.yaml
文件中。
dependencies:
bluetooth_low_energy: ^x.y.z
示例代码
以下是一个简单的示例代码,展示了如何使用 bluetooth_low_energy
插件进行低功耗蓝牙通信。
import 'dart:async';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
import 'router_config.dart';
void main() {
// 在应用启动前运行一个保护函数
runZonedGuarded(onStartUp, onCrashed);
}
// 应用启动时调用的函数
void onStartUp() async {
// 配置日志记录器
Logger.root.onRecord.listen(onLogRecord);
hierarchicalLoggingEnabled = true;
// 运行应用
runApp(const MyApp());
}
// 应用崩溃时调用的函数
void onCrashed(Object error, StackTrace stackTrace) {
Logger.root.shout('App crashed.', error, stackTrace);
}
// 日志记录处理器
void onLogRecord(LogRecord record) {
log(
record.message,
time: record.time,
sequenceNumber: record.sequenceNumber,
level: record.level.value,
name: record.loggerName,
zone: record.zone,
error: record.error,
stackTrace: record.stackTrace,
);
}
// 主应用类
class MyApp extends StatelessWidget {
const MyApp({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
// 配置路由
return MaterialApp.router(
routerConfig: routerConfig,
theme: ThemeData.light().copyWith(
materialTapTargetSize: MaterialTapTargetSize.padded,
),
darkTheme: ThemeData.dark().copyWith(
materialTapTargetSize: MaterialTapTargetSize.padded,
),
);
}
}
更多关于Flutter低功耗蓝牙通信插件bluetooth_low_energy_android的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter低功耗蓝牙通信插件bluetooth_low_energy_android的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个使用 bluetooth_low_energy_android
插件在 Flutter 中进行低功耗蓝牙通信的示例代码。这个示例将展示如何扫描设备、连接到设备、发现服务和特征值,以及读写特征值。
首先,确保你已经在 pubspec.yaml
文件中添加了 bluetooth_low_energy_android
依赖:
dependencies:
flutter:
sdk: flutter
bluetooth_low_energy_android: ^x.y.z # 请替换为最新版本号
然后,运行 flutter pub get
来获取依赖。
接下来是示例代码:
import 'package:flutter/material.dart';
import 'package:bluetooth_low_energy_android/bluetooth_low_energy_android.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
BluetoothLowEnergyManager? _bluetoothManager;
List<BluetoothDevice> _devices = [];
BluetoothDevice? _connectedDevice;
BluetoothService? _service;
BluetoothCharacteristic? _characteristic;
@override
void initState() {
super.initState();
initBluetooth();
}
Future<void> initBluetooth() async {
_bluetoothManager = BluetoothLowEnergyManager.instance;
// 请求权限
if (!await _bluetoothManager!.isLocationPermissionGranted()) {
await _bluetoothManager!.requestLocationPermission();
}
// 检查蓝牙是否开启
if (!await _bluetoothManager!.isBluetoothEnabled()) {
await _bluetoothManager!.enableBluetooth();
}
// 开始扫描设备
_bluetoothManager!.scanForDevices().listen((List<BluetoothDevice> devices) {
setState(() {
_devices = devices;
});
});
}
Future<void> connectToDevice(BluetoothDevice device) async {
_connectedDevice = device;
await _bluetoothManager!.connectToDevice(device.address);
discoverServices();
}
Future<void> discoverServices() async {
if (_connectedDevice == null) return;
List<BluetoothService> services = await _bluetoothManager!.discoverServices(_connectedDevice!.address);
setState(() {
_service = services.firstWhere((service) => service.uuid == "your-service-uuid", orElse: () => null);
});
if (_service != null) {
discoverCharacteristics();
}
}
Future<void> discoverCharacteristics() async {
if (_service == null) return;
List<BluetoothCharacteristic> characteristics = await _bluetoothManager!.discoverCharacteristics(_service!.uuid);
setState(() {
_characteristic = characteristics.firstWhere((characteristic) => characteristic.uuid == "your-characteristic-uuid", orElse: () => null);
});
}
Future<void> readCharacteristic() async {
if (_characteristic == null) return;
List<int> value = await _bluetoothManager!.readCharacteristic(_characteristic!.uuid);
print("Characteristic value: ${String.fromCharCodes(value)}");
}
Future<void> writeCharacteristic(String data) async {
if (_characteristic == null) return;
List<int> value = data.codeUnits;
await _bluetoothManager!.writeCharacteristic(_characteristic!.uuid, value);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Bluetooth Low Energy Example'),
),
body: Column(
children: [
Expanded(
child: ListView.builder(
itemCount: _devices.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_devices[index].name ?? "Unknown Device"),
onTap: () => connectToDevice(_devices[index]),
);
},
),
),
ElevatedButton(
onPressed: _connectedDevice != null ? readCharacteristic : null,
child: Text('Read Characteristic'),
),
ElevatedButton(
onPressed: () {
writeCharacteristic("Hello BLE");
},
child: Text('Write Characteristic'),
),
],
),
),
);
}
}
注意事项:
- UUID:在
discoverServices
和discoverCharacteristics
方法中,你需要替换"your-service-uuid"
和"your-characteristic-uuid"
为实际的服务和特征值的 UUID。 - 权限:确保在
AndroidManifest.xml
中添加了必要的蓝牙权限。 - 错误处理:示例代码省略了错误处理逻辑,实际使用中应添加适当的错误处理。
- 依赖版本:确保使用最新版本的
bluetooth_low_energy_android
插件,并根据其文档进行调整。
这个示例展示了基本的蓝牙低功耗通信流程,包括扫描设备、连接设备、发现服务和特征值,以及读写特征值。根据实际需求,你可以进一步扩展和修改这个示例。