How to schedule notifications using WorkManager?

前端 未结 4 1114
一个人的身影
一个人的身影 2020-11-29 08:24

I want to schedule a notification everytime the user add a note in the database for a specific time. While there are multiple ways to do it using AlarmManager, BroadcastRece

4条回答
  •  一整个雨季
    2020-11-29 09:14

    As ianhanniballake stated

    WorkManager isn't appropriate for work that needs to happen at a particular time.

    But this can be set in near future of the exact time, depending on the state of the battery optimization.

    An workaround will be like:

    // Time to show notification at
    LocalDateTime timeAt = LocalDate.now().atTime(20, 0);
    LocalDateTime timeNow = LocalDateTime.now();
    
    OneTimeWorkRequest.Builder workBuilder = new OneTimeWorkRequest.Builder(NotificationWorker.class);
    // I just need to set an delay here
    workBuilder.setInitialDelay(Duration.between(timeNow, timeAt));
    
    // This is just to complete the example
    WorkManager.getInstance().enqueueUniqueWork(UNIQUE_WORK_SHOW_NOTIFICATION,
                                        ExistingWorkPolicy.REPLACE,
                                        workBuilder.build());
    

提交回复
热议问题