颤音:在应用程序在后台运行时,运行代码像计时器一样

发布于 2025-01-30 04:55:30 字数 623 浏览 2 评论 0原文

我有一个简单的计时器,当应用在前景中运行时可以正常工作。我可以收听流并更新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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

愁以何悠 2025-02-06 04:55:30

尝试以下代码 -

我测试了它&amp;发现它将计算背景中的数字&amp;没有问题。

我添加了一个屏幕记录视频

import 'dart:async';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Flutter Demo',
      home: MyTest(),
    );
  }
}

class MyTest extends StatefulWidget {
  const MyTest({Key? key}) : super(key: key);

  @override
  State<MyTest> createState() => _MyTestState();
}

class _MyTestState extends State<MyTest> {
  final SetTimer _setTimer = SetTimer();

  @override
  void initState() {
    _setTimer.start();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: StreamBuilder<int>(
        stream: _setTimer.stream,
        builder: (
            BuildContext context,
            AsyncSnapshot<int> snapshot,
            ) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return CircularProgressIndicator();
          } else if (snapshot.connectionState == ConnectionState.active
              || snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasError) {
              return const Text('Error');
            } else if (snapshot.hasData) {
              return Center(
                child: Text(
                    snapshot.data.toString(),
                    style: const TextStyle(color: Colors.red, fontSize: 40)
                ),
              );
            } else {
              return const Text('Empty data');
            }
          } else {
            return Text('State: ${snapshot.connectionState}');
          }
        },
      ),
    );
  }
}

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);
    }
  }
}

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.

import 'dart:async';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Flutter Demo',
      home: MyTest(),
    );
  }
}

class MyTest extends StatefulWidget {
  const MyTest({Key? key}) : super(key: key);

  @override
  State<MyTest> createState() => _MyTestState();
}

class _MyTestState extends State<MyTest> {
  final SetTimer _setTimer = SetTimer();

  @override
  void initState() {
    _setTimer.start();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: StreamBuilder<int>(
        stream: _setTimer.stream,
        builder: (
            BuildContext context,
            AsyncSnapshot<int> snapshot,
            ) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return CircularProgressIndicator();
          } else if (snapshot.connectionState == ConnectionState.active
              || snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasError) {
              return const Text('Error');
            } else if (snapshot.hasData) {
              return Center(
                child: Text(
                    snapshot.data.toString(),
                    style: const TextStyle(color: Colors.red, fontSize: 40)
                ),
              );
            } else {
              return const Text('Empty data');
            }
          } else {
            return Text('State: ${snapshot.connectionState}');
          }
        },
      ),
    );
  }
}

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);
    }
  }
}
烟酉 2025-02-06 04:55:30

据我所知,像您想要的那样,无法在后台运行该应用程序。我在应用程序上也有类似的问题,我开发了,没有找到完美的解决方案。
作为解决方法,我正在使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文