2

我正在尝试在Flutter中安排后台任务,触发通知并更新数据库行。
我在用着:

问题:

当应用程序处于前台或后台时,计划任务会被执行,但当应用程序关闭时,什么也不会发生。

代码示例:

该函数用于调度任务:

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

1 回答 1

0

在我在 Android Studio 中创建的应用程序中,当活动被“销毁”时,我会启动一项服务来重新启动应用程序。

从那以后添加了更多参数,也许这个“重新启动”服务可以在 Finish() 中执行

更多信息在这里,也许这是正确的方向。https://developer.android.com/reference/android/app/Activity#onDestroy()

于 2020-11-13T23:42:40.967 回答