如何安排特定时间的通知?

时间:2020-01-27 15:01:52

标签: android notifications scheduling builder worker

我可以使用AlarmManager设置特定时间的通知,但是如果重新启动手机,通知将被取消。另外,我在描述here的AlarmManager上遇到了问题。

由于上述问题,我决定通过OneTimeWorkRequest设置通知。 OneTimeWorkRequest.Builder(class).setInitialDelay(long)会将通知延迟几毫秒,而不是基于设备日历时间的通知。我尝试将延迟时间设置为5分钟,并将设备时间设置为提前4分钟,但我仍然需要等待5分钟才能收到通知,而不是1分钟。

如果我安排f.e.战利品开放。 就我而言,我想安排付款通知,这样我就不会显示通知。在午夜而不是8:00 AM,因为用户在旅行期间切换了时区。

是否有一种方法可以始终根据设备时间设置OneTimeWorkRequest延迟?

NotificationScheduler.class

public void scheduleNotificationWorker(Bill bill){
    if (calculateNotificationDelay(bill, 14, 1) > 0) {
        Data inputData = new Data.Builder().putInt(UploadWorker.NOTIFICATION_ID, 1).build();
        OneTimeWorkRequest notificationWork = new OneTimeWorkRequest.Builder(UploadWorker.class)
                .setInitialDelay(calculateNotificationDelay(bill, 14, 2), TimeUnit.MILLISECONDS)
                .setInputData(inputData)
                .addTag("notification")
                .build();
        WorkManager.getInstance(context).enqueue(notificationWork);
    }
    else
        Log.e("notification_error ", "Could't create notification because delay is negative. Probably bill is overdued.");
}

UploadWorker.class

@NonNull
@Override
public Result doWork() {
    triggerNotification();
    return Result.success();
}

private void triggerNotification(){
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext());

    NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), "channel_id")
            .setSmallIcon(R.drawable.ic_launcher_background)
            .setContentTitle("My notificatiop")
            .setContentText("Hello")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT);
    Notification notification = builder.build();
    final int id = getInputData().getInt(NOTIFICATION_ID, 0);
    notificationManager.notify(id, notification);
}

0 个答案:

没有答案