Kaloyan Roussev
Kaloyan Roussev

Reputation: 14711

Android how to set AlarmManager alarm to go off at a random hour every day?

Up until now, every day at 11 o'clock an alarm manager triggers a procedure like so:

Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 11);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    long alarmTime = calendar.getTimeInMillis();
    alarmTime = alarmTime + (AlarmManager.INTERVAL_DAY);

    Intent intent = new Intent(context, SyncReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1300, intent, 0);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, AlarmManager.INTERVAL_DAY, pendingIntent);

Now I gotta change this procedure to go off at a random hour each day, how can I do that with the least amount of change?

Upvotes: 0

Views: 745

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006664

Replace setRepeating() with set(). In SyncReceiver, choose the next random hour and set() a fresh alarm to trigger SyncReceiver at that time.

Upvotes: 2

Related Questions