延迟为链的多个 OneTimeWorkRequests

Multiple OneTimeWorkRequests with delay as chain

我正在制作一个应用程序 Medicine Reminder,它应该根据数据库中保存的日期和时间来提醒药物消耗。 提醒应以通知的形式进行。 假设我有一种药物应该服用两次(例如在 9:50 pm 和 9:55 pm 进行快速测试)。单击按钮会触发通知。

我的问题 - 只显示第一个通知,其他的不显示。

这是我的代码:

public void makeNotifications(Date now, String[] medicineNames, Date[] 
takingTime) {

    WorkContinuation continuation = null;

    for (int i = 1; i < medicineNames.length + 1; i++) {

        Data.Builder dataBuilder = new Data.Builder()
                .putString(MEDICINE_NAME_KEY, medicineNames[i - 1])
                .putLong(MEDICINE_TAKING_TIME_KEY, takingTime[i - 1].getTime());
        OneTimeWorkRequest.Builder requestBuilder =
                new OneTimeWorkRequest.Builder(NotificationWorker.class)
                        .setInputData(dataBuilder.build());

        if (i == 1) {
            long diff = Math.abs(takingTime[i - 1].getTime() - now.getTime());
            requestBuilder.setInitialDelay(diff, TimeUnit.MILLISECONDS);
            continuation = mWorkManager.beginUniqueWork(
                    MEDICINE_NOTIFICATION_KEY,
                    ExistingWorkPolicy.KEEP,
                    requestBuilder.build());
        } else {
            long diff = Math.abs(takingTime[i - 1].getTime() - now.getTime());
            requestBuilder.setInitialDelay(diff, TimeUnit.MILLISECONDS);
            continuation.then(requestBuilder.build());
        }
    }
    continuation.enqueue();
} 

你有suggestion/explanation/solution吗?

WorkManager 不是您用例的最佳解决方案,因为您需要在 特定时间 完成一些琐碎的工作。 WorkManager 将遵守休眠模式条件,如果设备处于休眠模式,您的通知将不会发布。

我建议您改用 AlarmManager。使用 AlarmManager

setAndAllowWhileIdle()setExactAndAllowWhileIdle()

基于documentation

Standard AlarmManager alarms (including setExact() and setWindow()) are deferred to the next maintenance window.

  • If you need to set alarms that fire while in Doze, use setAndAllowWhileIdle() or setExactAndAllowWhileIdle().
  • Alarms set with setAlarmClock() continue to fire normally — the system exits Doze shortly before those alarms fire.