我需要在后台运行一些代码。具体来说,我必须从连接的设备上监听蓝牙数据,并侦听位置变化,并能够处理这些数据。
我对你如何处理这个问题感兴趣?
经过一些调查,我了解了在后台运行代码的下列方法:
1.前台服务
问题:
2.颤振background_fetch
问题:
3.工作经理
https://pub.dev/packages/workmanager
问题:
更新:经过研究和测试,我们找到了满足所有需求的下一个解决方案:
这两个平台都没有确切的解决方案。对于android,我一直使用运行前台服务。对于iOS来说,当应用程序使用蓝牙时,显然不需要额外的代码,它不会被系统杀死,或者至少有更少的机会这样做。此外,我的应用程序使用蓝牙从Dart代码与flutter_blue包。也许值得一提的是,我们与蓝牙设备有着持续的连接。对于永无止境的Android服务,您可以基于本文:https://fabcirablog.weebly.com/blog/creating-a-never-ending-background-service-in-android提供服务。
发布于 2021-09-14 17:03:36
要在后台运行任务,您可能需要查看使用隔离。下面是如何实现隔离的示例。
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();
}至于颤振上的蓝牙支持,您也可以考虑使用蓝色。
https://stackoverflow.com/questions/59253028
复制相似问题