Search code examples
androidalarm

AlarmManager use setExactAndAllowWhileIdle so it repeats


I have an app that uses an AlarmManager to schedule a service to repeat at a set frequency, say every hour.

From Android 6, devices will drop into Doze mode, this mode ignores wakelock and Alarms, potentially running them in the maintenance window. I would prefer that the Alarm executes when it is scheduled even if the device is in low-power idle modes.

I understand i can use setExactAndAllowWhileIdle to execute the alarm in Doze but this will excute only once. I cannot see any method that has this functionality but will repeat at a set frequency.

for example i use the code below to fire an alarm every hour. Is there a way to use setExactAndAllowWhileIdle so it repeats?

                             // get a Calendar object with current time
                             Calendar cal2 = Calendar.getInstance();
                             // add 5 minutes to the calendar object
                             cal2.add(Calendar.MINUTE, 1);
                             Intent intentTracking = new Intent(getApplicationContext(), TrackingAlarmReceiver.class);

                             // In reality, you would want to have a static variable for the request code instead of 192837
                             PendingIntent sender3 = PendingIntent.getBroadcast(getApplicationContext(), 192839, intentTracking, PendingIntent.FLAG_UPDATE_CURRENT);

                             // Get the AlarmManager service
                             AlarmManager am3 = (AlarmManager) getSystemService(ALARM_SERVICE);
                             //am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);


                             am3.setRepeating(AlarmManager.RTC_WAKEUP, cal2.getTimeInMillis(), ((Integer.parseInt(carerTrackingInteval)) * 60000 ), sender3);

Solution

  • ADM is spot-on.

    As part of the work in TrackingAlarmReceiver, you call setExactAndAllowWhileIdle() to schedule the next bit of work.

    Bear in mind that the minimum granularity of such events is ~10 minutes IIRC, and that you may not have network access even though you get control.