颤音:在应用程序在后台运行时,运行代码像计时器一样
我有一个简单的计时器,当应用在前景中运行时可以正常工作。我可以收听流并更新UI。但是,当应用在后台时,它将不会继续计数。当应用在后台运行时,如何继续计数?
这是我的计时器代码:
class SetTimer {
int _seconds = 0;
final _streamController = StreamController<int>.broadcast();
Timer? _timer;
// Getters
Stream<int> get stream => _streamController.stream;
// Setters
void start() {
_timer = Timer.periodic(const Duration(seconds: 1), (_) {
_seconds++;
_updateSeconds();
});
}
void _updateSeconds() {
// stop counting after one hour
if (_seconds < 3600) {
_streamController.sink.add(_seconds);
}
}
}
I have a simple timer which works fine when the app is running in foreground. I can listen to the stream and update the UI. However when the app is in the background it will not continue counting. How can I continue counting when the app is running in the background?
This is my code for the timer:
class SetTimer {
int _seconds = 0;
final _streamController = StreamController<int>.broadcast();
Timer? _timer;
// Getters
Stream<int> get stream => _streamController.stream;
// Setters
void start() {
_timer = Timer.periodic(const Duration(seconds: 1), (_) {
_seconds++;
_updateSeconds();
});
}
void _updateSeconds() {
// stop counting after one hour
if (_seconds < 3600) {
_streamController.sink.add(_seconds);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试以下代码 -
我测试了它&amp;发现它将计算背景中的数字&amp;没有问题。
我添加了一个屏幕记录视频
Try the below code -
I tested it & found it will count the number in the background & there is no problem.
I added a screen record video here, it will help you to understand.
据我所知,像您想要的那样,无法在后台运行该应用程序。我在应用程序上也有类似的问题,我开发了,没有找到完美的解决方案。
作为解决方法,我正在使用 wakelock package 防止移动设备/应用程序进入待机。也许这也可能是您的解决方案。
As far as I know, there is no way to run the app in the background, like you want to. I had a similar problem with an app, I developed and didn't found the perfect solution.
As a workaround, I'm using the wakelock package to prevent the mobile device / app from going into standby. Maybe this could also be a solution for you.