Android : Avoid setting of same Alarm again and again

on Friday, August 22, 2014


In my android app, I have two services which are supposed to run timely. One will run on a fixed date and the other will run on 11:00 PM everyday.


To achieve this, I have created services and used Alarm manager to start them at fixed time.



private void scheduleAlarmForCleanup(){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 00);


Intent pendingIntent = new Intent(this, CleanupService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, pendingIntent, 0);


AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000 , pintent);
}


Now I have called this function in my Activity's onCreate. But onCreate can be called multiple times during a day and my concern is this will lead to multiple calls to this function.


What effect can this have ? Would the Alarm be set multiple times. Is there a way by which I can check whether my alarm is already set and in that case I won't try to set alarm again.


0 comments:

Post a Comment