Service 颤振-Dart中的后台服务(仅当应用程序可见时)

Service 颤振-Dart中的后台服务(仅当应用程序可见时),service,dart,flutter,background-service,Service,Dart,Flutter,Background Service,我需要一个flatter中的后台服务,这使得非常小的一个http.get(…) 应用程序运行时,此服务应在后台运行。如果应用程序关闭,后台服务也应停止。当应用程序启动时,后台服务也应该启动 我只能找到提供后台服务的软件包,当应用程序关闭时,这些软件包也会运行,如以下示例所示: 也许我要找的不是“后台服务” 下面是一些代码,我想在这个后台服务/任务中运行 Timer.periodic(持续时间(秒:60),(Timer t)=>checkForUpdates()); 我遇到了同样的问题。Timer

我需要一个flatter中的后台服务,这使得非常小的一个http.get(…)

应用程序运行时,此服务应在后台运行。如果应用程序关闭,后台服务也应停止。当应用程序启动时,后台服务也应该启动

我只能找到提供后台服务的软件包,当应用程序关闭时,这些软件包也会运行,如以下示例所示:

也许我要找的不是“后台服务”

下面是一些代码,我想在这个后台服务/任务中运行

Timer.periodic(持续时间(秒:60),(Timer t)=>checkForUpdates());

我遇到了同样的问题。Timer.periodic在离开应用程序后在后台持续运行一段无法控制的时间。我的解决方案是这样的:

class CollectStampsState extends State<CollectStamps> with WidgetsBindingObserver { 
    Timer timer;

    ...

    @override
    void didChangeAppLifecycleState(AppLifecycleState state) {
        if (state != AppLifecycleState.resumed) {
            timer.cancel();
        } else {
        if (!timer.isActive) {
            timer = Timer.periodic(Duration(seconds: 30), (Timer t) => yourFunction());
        }
    }

    @override
    void initState() {
        super.initState();
        timer = Timer.periodic(Duration(seconds: 30), (Timer t) => yourFunction());
        WidgetsBinding.instance.addObserver(this);
    }

    @override
    void dispose() {
        timer?.cancel();
        WidgetsBinding.instance.removeObserver(this);
        super.dispose();
    }

     @override
     Widget build(BuildContext context) {
        ... 
     }
}
类CollectStampState使用WidgetsBindingObserver{
定时器;
...
@凌驾
void didchangeAppifecyclestate(AppLifecycleState状态){
if(state!=AppLifecycleState.recovered){
timer.cancel();
}否则{
如果(!timer.isActive){
timer=timer.periodic(持续时间(秒:30),(timer t)=>yourFunction());
}
}
@凌驾
void initState(){
super.initState();
timer=timer.periodic(持续时间(秒:30),(timer t)=>yourFunction());
WidgetsBinding.instance.addObserver(这个);
}
@凌驾
无效处置(){
计时器?.cancel();
WidgetsBinding.instance.removeObserver(此);
super.dispose();
}
@凌驾
小部件构建(构建上下文){
... 
}
}

如果你想在其他地方使用AppLifecycleState,你也可以保存它,或者更改不同ApplifeCleStates的行为。但是这样,计时器只有在应用程序位于前台时才处于活动状态。一旦应用程序位于后台,计时器就会被取消。

因此,如果它必须仅在ap运行时才运行,你根本不需要任何服务p是active,那么您将如何做呢?只需在每个init()中编写一个调用的异步函数关于一个小部件?你尝试了Timer.periodic,它不工作吗?我没有尝试过,我认为这是错误的方法。我会尝试一下,让你知道我刚刚测试过它,它工作了。奇怪的是,服务会持续运行几分钟,即使应用程序没有显示。我现在每次都会在init()中启动服务然后在每个小部件的dispose()中关闭它