Search code examples
androidalarmmanagerandroid-pendingintentintentserviceandroid-alarms

PendingIntent with IntentService not working


Following code works perfectly for Activity:

Intent intent = new Intent(context, MyActivity.class);
PendingIntent operation = PendingIntent.getActivity(context, 
                              0, 
                              intent, 
                              PendingIntent.FLAG_UPDATE_CURRENT);
alarmmanager.setExact(AlarmManager.RTC_WAKEUP, 
                              startTime.getTimeInMillis(),
                              operation);

However, when I do the same thing for IntentService, It works only if startTime and time I set alarm are on the same day. e.g. If I set the alarm today for 5 PM, it will be executed but when I set the alarm today for 5 PM tomorrow, it will not be executed. If this was Activity then it works for both cases.

Intent intent = new Intent(context, MyService.class);
PendingIntent operation = PendingIntent.getService(context, 
                              0, 
                              intent, 
                              PendingIntent.FLAG_UPDATE_CURRENT);
alarmmanager.setExact(AlarmManager.RTC_WAKEUP, 
                              startTime.getTimeInMillis(),
                              operation);

How to solve this?

The goal here I am trying to achieve is to execute IntentService every day at the exact time.


Solution

  • The goal here I am trying to achieve is to execute IntentService every day at the exact time.

    Google has made this progressively harder from release to release. See Android AlarmManager setExact() is not exact. There could be two ways to solve this for your case:

    1. you start an activity, which starts the service (as starting an Activity seems to work for you)
    2. you use either setExactAnd... or setAlarmClock. setAlarmClock also triggers in the new "doze" mode, see https://stackoverflow.com/a/47049705/1587329.

    Another way would be to re-think why and if you really need this... or if a JobScheduler could not fit your purpose more easily.