2

I'm trying to schedule a background task in Flutter, firing a notification and updating a database row.
I'm using:

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

1 Answers1

0

In an app I created in Android Studio, when the activity is 'destroyed' I launch a service to re-start the app.

Since then some more parameters have been added, perhaps this 're-start' service can be executed in the Finish()

More info here, maybe this is in the right direction. https://developer.android.com/reference/android/app/Activity#onDestroy()

  • I found out that this problem does not show up on certain phones, this problems appeared only on some cheap chineese phones. Some of theese phones kill the workManager process. – Soheib Bettahar Nov 24 '20 at 11:41