每天同一时间在Flutter中发送随机通知的最佳方式是什么?

x4shl7ld  于 2023-05-19  发布在  Flutter
关注(0)|答案(1)|浏览(88)

我正在尝试构建一个应用程序,每天从上午9点到下午5点每小时发送通知。通知正文是从数组中随机选择的。我试着使用flutter_local_notifications,特别是zonedSchedule函数,像这样:

await flutterLocalNotificationsPlugin.zonedSchedule(
      i,
      "Promise",
      uiLocalNotificationDateInterpretation:
          UILocalNotificationDateInterpretation.absoluteTime,
      NotificationRepo.getNotification(notification.category),
      t,
      notificationDetails,
      androidAllowWhileIdle: true,
      matchDateTimeComponents: DateTimeComponents.time);

NotificationRepo.getNotification(notification.category)是选择通知正文的函数。问题是,它应该每天重复,这样通知就会重复,而不是随机选择。此外,根据文档,flutter_local_notifications的计划通知限制为64个,所以我不能提前几周安排它们。我不想使用Firebase消息传递,因为我想脱机发送通知。我该如何处理这个问题?

nue99wik

nue99wik1#

尝试创建一个函数来生成通知消息,例如:

String notificationMessages() {
List<Strind> messages = ['msg1', 'msg2', 'msg3'];

RandomMessage randomMsg = RandomMessage();

int index = randomMsg.nextInt(messages.length);
return messages[index];
}

之后,创建一个函数,根据您想要的时间安排通知:

void ScheduleNotification() {
const int start = 9;
const int end = 17;

Timer.periodic(Duration(hour: 2), (timer) async {
DateTime present = DateTime();

int hour = present.hour;

if (hour >= startHour && hour <= endHour) {
  String Noti_message = notificationMessages();

  await flutterLocalNotificationsPlugin.show(
      0, 'yes', Noti_message, platformChannelSpecifies);
  }
});
}

您还应该设置通知设置,例如频道:

const NotificationProperties platformChannelSpecifies= NotificationProperties (android : androidplatformChannelSpecifies);

希望这能帮上忙。

相关问题