I schedule pendingIntent to be sent in 5 seconds, but it starts in 23 seconds. API=19 (AlarmManager.setExact(...)):
10-23 16:43:44.638 11903-11903/? D/MainActivity﹕ Fri Oct 23 16:43:44 GMT+05:00 2015: scheduled in 5000 ms
10-23 16:44:07.728 11903-11903/? D/MainActivity﹕ Fri Oct 23 16:44:07 GMT+05:00 2015: fired
private PendingIntent pendingIntent;
private int SCHEDULE_REQUEST_CODE = 1;
private static final String SCHEDULER_ACTION = "android.intent.action.FOTA_SCHEDULE_CHECK";
private void log(String message) {
StringBuilder sb = new StringBuilder();
sb.append(new Date().toString());
sb.append(": ");
sb.append(message);
sb.append("\n");
Log.d(getClass().getSimpleName(), sb.toString());
tv.append(sb.toString());
tv.append("\n");
}
private BroadcastReceiver schedulerReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
log("fired");
}
};
private void schedule() {
registerReceiver(schedulerReceiver, new IntentFilter(SCHEDULER_ACTION));
Intent scheduleIntent = new Intent(SCHEDULER_ACTION);
pendingIntent = PendingIntent.getBroadcast(this, SCHEDULE_REQUEST_CODE, scheduleIntent, 0);
AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
// first invocation (once, exact)
int delay = 5 * 1000; // 5s
log("scheduled in " + delay + " ms");
alarmManager.setExact(AlarmManager.RTC, System.currentTimeMillis() + delay, pendingIntent);
}
@Override
protected void onDestroy() {
super.onDestroy();
unschedule();
}
private void unschedule() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
pendingIntent = null;
unregisterReceiver(schedulerReceiver);
}
I'v got the same problem, but pendingIntent start after 5 seconds, not 2 as i try to set.
If i set 5 seconds and more,
alarmManager
starts exactly. I don't know what inexatly interval i'll get in production environment, so i choose 1 minute as short time interval.So, my app used
postDelayed()
instead ofAlarmManager
for the short time intervals, andAlarmManager
for long.Code sample:
Where
SoundService
- Service with sound playing functionality,delay
- delay before playing, in seconds,AlarmBroadcastReceiver
-}