【问题标题】:Flutter Background Processes Using Android Alarm Manager and Isolates使用 Android 警报管理器和隔离器 Flutter 后台进程
【发布时间】:2020-11-15 18:26:16
【问题描述】:

我正在尝试让计时器(精确到百分之一秒)在 Flutter 中工作,即使应用程序关闭也是如此。我最初尝试使用隔离,因为我认为它们在使用运行 Android 11 的 Pixel 4 进行测试后仍然可以工作,我发现当应用程序关闭时它仍然无法正确触发。经过一番谷歌搜索后,我遇到了 Android 警报管理器,我重新设置了所有内容,但似乎没有正确触发周期性功能。 下面是触发计数器的 BLoC 地图:

Stream<TimerState> _mapTimerStartedToState(TimerStarted start) async* {
     AndroidAlarmManager.initialize();
     port.listen((_) async => await _incrementCounter());
     startCounter();
     print(_counter);
     yield TimerRunInProgress(start.duration);
  }

这里是 startCounter() 函数:

void startCounter() async {
     prefs = await SharedPreferences.getInstance();
     if (!prefs.containsKey(countKey)) {
       await prefs.setInt(countKey, 0);
     }
     IsolateNameServer.registerPortWithName(
      port.sendPort,
      isolateName,
     );
     await AndroidAlarmManager.periodic(
       Duration(milliseconds: 100),
       // Ensure we have a unique alarm ID.
       Random().nextInt(pow(2, 31)),
       callback,
       exact: true,
       wakeup: true,
     );


 }

然后这是我的回调:

static Future<void> callback() async {
     print('Alarm fired!');
     // Get the previous cached count and increment it.
     final prefs = await 
     SharedPreferences.getInstance();
     int currentCount = prefs.getInt(countKey);
     await prefs.setInt(countKey, currentCount + 1);
     // This will be null if we're running in the background.
     print(currentCount);
     uiSendPort ??= IsolateNameServer.lookupPortByName(isolateName);
uiSendPort?.send(null);
  }

我在正确的道路上吗? AndroidAlarmManager 可以做我想做的事情吗?我不确定为什么隔离方法也不能单独工作,我得到的唯一解释是我需要使用 AndroidAlarmManager。现在,事件并没有像我告诉他们的那样以 100 毫秒的速率触发,而是间隔 1 到几分钟触发。

【问题讨论】:

  • 当您的应用处于后台时,您无需计算任何计时器 - 您可以在应用切换到前台时获取当前时间并更新您的计时器
  • 你有什么可以参考的吗?我是新人

标签: flutter android-alarms dart-isolates


【解决方案1】:

Android 会限制闹钟的频率。您不能使用 AlarmManager 将警报频率设置为 100 毫秒。

请参阅https://developer.android.com/reference/android/app/AlarmManagerhttps://developer.android.com/reference/android/app/AlarmManager上的红色背景注释

注意:从 API 19 (Build.VERSION_CODES.KITKAT) 警报开始 交付不准确:操作系统将切换警报以最小化 唤醒和电池使用。有新的 API 来支持应用程序 需要严格的交货保证;见 setWindow(int, long, long, android.app.PendingIntent) 和 setExact(int, long, android.app.PendingIntent)。 targetSdkVersion 为的应用程序 早于 API 19 将继续看到以前的行为 所有警报都会在请求时准确发送。

【讨论】:

  • 啊,我可以用另一种方法来创建这个计时器还是这个任务目前不可行?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-12
  • 2016-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多