max
max

Reputation: 591

Flutter - Background Service in Dart (only when app is visible)

I need a background service in flutter, that makes very minute a http.get(...)

This service should run in the background, while the app is running. If the app is closed, the background service should stopp also. When the app gets started, the background service should also get started.

I can only find packages, that provide a background service, that also runs, when the app is closed - like this example: https://medium.com/flutter-io/executing-dart-in-the-background-with-flutter-plugins-and-geofencing-2b3e40a1a124

Maybe what I'm looking for is not called "background-service"?

Here is some code, I want to run in this background service/task...

Timer.periodic(Duration(seconds: 60), (Timer t) => checkForUpdates());    

Upvotes: 2

Views: 1720

Answers (1)

dirkbo
dirkbo

Reputation: 673

I came across the same Problem. Timer.periodic keeps running in the background for an uncontrollable time after leaving the app. My solution is something like this:

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) {
        ... 
     }
}

You can also save the AppLifecycleState, if you want to use it in other places, or change the behavior for different AppLifecycleStates. But like this, the timer is only active, when the app is in the foreground. As soon as it's in the Background, the timer is canceled.

Upvotes: 0

Related Questions