android - Flutter 如何在后台发现蓝牙设备(flutter_bluetooth_serial)
问题描述
我想在后台开始连续搜索蓝牙设备,并在检测到设备“X”时发送通知。
此时我每 5 秒运行一次定期计时器,在其中我执行新的扫描
即使我关闭了应用程序,我该如何进行此扫描?
Timer.periodic(Duration(milliseconds: 5000), (timer) => discovery());
void discovery() {
var tmp = new Map<String, BluetoothDevice>();
FlutterBluetoothSerial.instance.startDiscovery().listen((r) {
tmp.putIfAbsent(r.device.address, () => r.device);
app.onDiscovery(r);
}).onDone(() {
_isDiscovering = false;
});
}
我想要一个兼容 IOS 和 Android 的解决方案。
谢谢你,美好的一天。
解决方案
要在后台运行任务,您可能需要考虑使用Isolate。
Isolate? isolate;
@override
void initState() {
/// Start background task
_asyncInit();
super.initState();
}
_asyncInit() async {
final ReceivePort receivePort = ReceivePort();
isolate = await Isolate.spawn(_isolateEntry, receivePort.sendPort);
receivePort.listen((dynamic data) {
if (data is SendPort) {
if (mounted) {
data.send({
/// Map data using key-value pair
/// i.e. 'key' : String
});
}
} else {
if (mounted) {
setState(() {
/// Update data here as needed
});
}
}
});
}
static _isolateEntry(dynamic d) async {
final ReceivePort receivePort = ReceivePort();
d.send(receivePort.sendPort);
/// config contains the key-value pair from _asyncInit()
final config = await receivePort.first;
/// send bluetooth data you received
d.send(...);
}
@override
void dispose() {
/// Determine when to terminate the Isolate
if (isolate != null) {
isolate.kill();
}
super.dispose();
}
至于 Flutter 上的 BLE 支持,您还可以考虑使用flutter_blue