I am writing an app that needs to schedule a one-time notification for a specific time in the future. I'm generating the notification via WorkManager
.
In particular, I'm using setInitialDelay
for the request.
This is working in most cases - it works when the app is in Stop
state, for instance (not visible). But if I reboot the phone, the notification never occurs (with API 34). I'd like it to occur when the phone boots up, if the time has passed.
Is this the wrong approach to solving my problem? Does setInitialDelay
not do what I expect? The documentation suggests that WorkManager
is the right approach to this problem and that it should handle reboots (if I'm understanding it properly).
WorkManager
works by scheduling work relative to the time you enqueue it—it’s not based on an absolute time. This means that if the device reboots after the scheduled time has passed, the delay (which is now negative) won’t “catch up” and the work might not run. In other words, WorkManager is designed for deferrable, non‐exact background tasks rather than exact alarms.
If you want a specific task to take place at an exact time or in that time window (when battery optimizations like Doze mode is active), you would want to use AlarmManager.
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmBroadcastReceiver.class);
intent.putExtra("data", data);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context,
requestCode,
intent,
PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
);
AlarmManagerCompat.setExactAndAllowWhileIdle(
alarmManager,
AlarmManager.RTC_WAKEUP, // Alarm Type
Long.parseLong(data.getEpoch()), // epoch time millis
pendingIntent
);
public class AlarmBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Do your task
}
}
<receiver android:name="service.AlarmBroadcastReceiver"/>
And finally, don't forget to hold a record of your alarms. Since whenever the device reboots, the alarms would be forgotten. You would have to re-schedule the alarms in an Boot-Completed broadcast receiver.