我正在尝试在Flutter中安排后台任务,触发通知并更新数据库行。
我在用着:
- workmanager包在后台安排任务。
- flutter_local_notifications触发通知。
- hive持久化数据。
问题:
当应用程序处于前台或后台时,计划任务会被执行,但当应用程序关闭时,什么也不会发生。
代码示例:
该函数用于调度任务:
Future scheduleDailyUpdateTask(DomainHabit habit) async {
String uniqueName = "$DAILY_UPDATE_TASK: ${habit.id}";
String tag = habit.id.toString();
await Workmanager.initialize(callbackDispatcher);
await Workmanager.registerPeriodicTask(uniqueName, DAILY_UPDATE_TASK,
tag: tag,
inputData: {
ID: habit.id,
},
frequency: Duration(days: 1),
initialDelay: Duration(days: 1),
backoffPolicy: BackoffPolicy.exponential,
backoffPolicyDelay: Duration(seconds: 10));
}
该函数用于执行任务:
void callbackDispatcher() {
Workmanager.executeTask((taskName, inputData) async {
//show the notification
print("WorkManager task executed taskName: $taskName");
print("inputData: $inputData");
if (taskName == REMINDER_NOTIFICATION_TASK ||
taskName == DAILY_UPDATE_TASK) {
int id = inputData[ID] as int;
await HabitDatabase.initDatabase();
await HabitDatabase.openHabitsBox();
Habit habit = HabitDatabase.getHabit(id);
await NotificationHelper.initNotifications();
if (taskName == REMINDER_NOTIFICATION_TASK) {
await NotificationHelper.showNotification(id, habit.name,
"Take it one day at a time, Good luck!.", habit.name);
}
if (taskName == DAILY_UPDATE_TASK) {
await HabitDatabase.updateHabit(
id, habit.copyWith(days: habit.days + 1));
await NotificationHelper.showNotification(
id,
habit.name,
"Congratulations fo getting by another day, Validate your progress.",
habit.name);
}
}
return Future.value(true);
});
}