首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Flutter - Dart中的后台服务(仅当应用程序可见时)

Flutter - Dart中的后台服务(仅当应用程序可见时)
EN

Stack Overflow用户
提问于 2019-05-21 03:26:28
回答 1查看 1.3K关注 0票数 2

我需要在flutter中的后台服务,这使得非常分钟是一个http.get(...)

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

我只能找到提供后台服务的包,当应用程序关闭时,它也会运行-就像这个例子:https://medium.com/flutter-io/executing-dart-in-the-background-with-flutter-plugins-and-geofencing-2b3e40a1a124

也许我要找的东西不叫“后台服务”?

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

代码语言:javascript
复制
Timer.periodic(Duration(seconds: 60), (Timer t) => checkForUpdates());    
EN

回答 1

Stack Overflow用户

发布于 2019-07-26 17:59:51

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

代码语言:javascript
复制
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) {
        ... 
     }
}

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56227004

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档