使用Android报警管理器和Isolates的Flutter后台处理



我正试图让一个计时器(精确到百分之一秒(在Flutter中工作,即使应用程序关闭。我最初尝试使用隔离,因为我认为它们会起作用,但在使用运行Android 11的Pixel 4进行测试后,我发现当应用程序关闭时,它仍然没有正确启动。经过一些谷歌搜索,我发现了Android Alarm Manager,我重新设置了所有功能,但似乎周期性功能没有正确启动。以下是触发计数器的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到几分钟发射。

Android限制报警频率。使用AlarmManager不能将报警安排为100毫秒的频率。

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

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

最新更新