My application creates an alarm that repeats every day. Since it is not possible to know if an alarm is already registered, I create the alarm every time the application is launched.
Here is the function that is called at the beginning of the main activity (inside onCreate()):
public static void setAlarm(Context context) {
Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Calendar firingCal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Paris"));
Calendar currentCal = (Calendar)firingCal.clone();
Random rnd = new Random();
// Each day between 1:00 AM and 1:30 AM (some jitter added)
firingCal.set(Calendar.HOUR_OF_DAY, 1);
firingCal.set(Calendar.MINUTE, rnd.nextInt(30));
firingCal.set(Calendar.SECOND, 0);
long intendedTime = firingCal.getTimeInMillis();
long currentTime = currentCal.getTimeInMillis();
if (intendedTime >= currentTime) {
//set from today
alarmManager.setInexactRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
} else {
//set from next day
firingCal.add(Calendar.DAY_OF_MONTH, 1);
intendedTime = firingCal.getTimeInMillis();
alarmManager.setInexactRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
Is it OK to recreate the alarm each time the application is launched? Should I use some flags on the PendingIntent (like update or cancel existing PendingIntent)?
Thanks!
Update: is it a problem if I use flag 0 instead of PendingIntent.FLAG_UPDATE_CURRENT from a performance perspective?