I'm trying to schedule a background task in Flutter, firing a notification and updating a database row.
I'm using:
- workmanager package to schedule tasks in the background.
- flutter_local_notifications to fire notifications.
- hive to persist data.
Problem:
When the application is in the foreground, or in the bckground the scheduled task gets executed, but when the application is closed nothing happens.
Code samples:
This function is used to schedule the task:
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));
}
This function is used to execute the task:
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);
});
}