'Timer is not worked in background flutter
This code is not printed, when app go to background in iOS.
Timer.periodic(Duration(seconds: 1), (timer) { print('timer'); }
I need to save state to database and play sound after finishing timer. But timer counter minimum is 1 minute. So it means at minimum after 1 minute timer will be finished. This value will be set by user. During this interval device maybe locked. Even if device is locked, app must save state after finishing timer.
Solution 1:[1]
Running dart code in background is not a trivial task. You can read this: https://docs.flutter.dev/development/packages-and-plugins/background-processes
Or can check this plugin: https://pub.dev/packages/flutter_background_service
Solution 2:[2]
In iOS app, after using flutter_background_service, timer is worked only when app went to background with playing audio. So in this situation timer must work with playing audio in parallel. Without playing audio, timer is not worked in background. Because of this I have try to hack this. I play silence audio in loop mode, when timer is started. I debug this with more than an hour timer tick. This is worked perfectly.
For this I don't use any package. I just enable background mode and playing audio in background mode from Xcode:
I get silence sounds from here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | yelliver |
Solution 2 | Shohin |