0

I have three alarm managers to create three alarms at different of the day. These alarms are in the oncreate method of the mainactivity. I want these alarms to be set only when the application starts the first time. But because they are in the oncreate method of the main activity. They are recreated everytime my main activity is recreated. How can I fix this problem? Also I want the alarms to be set off even if my main activity is not active or in focus.

Moreover, I want each of these alarms to repeat daily at different times within a certain time window. The setRepeatingAlarm method does not give me that flexibility. Any ideas on how I can accomplish this?

Intent intent1 = new Intent(this, ReminderAlarmReceiver.class);
intent1.putExtra("alarm_message", "Alarm!");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent1,  PendingIntent.FLAG_NO_CREATE);

Intent intent2 = new Intent(this, ReminderAlarmReceiver.class);
intent2.putExtra("alarm_message", "Alarm!");
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(this, 2, intent2, PendingIntent.FLAG_NO_CREATE);

Intent intent3 = new Intent(this, EODAlarmReceiver.class);
intent3.putExtra("alarm_message", "Alarm!");    
PendingIntent pendingIntent3 = PendingIntent.getBroadcast(this, 3, intent3, 0);

// Get the AlarmManager service
AlarmManager alarmMgr1 = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmMgr1.set(AlarmManager.RTC_WAKEUP, cal0.getTimeInMillis(), pendingIntent);

AlarmManager alarmMgr2 = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmMgr2.set(AlarmManager.RTC_WAKEUP, cal2.getTimeInMillis(), pendingIntent2);        

AlarmManager alarmMgr3 = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmMgr3.set(AlarmManager.RTC_WAKEUP, cal4.getTimeInMillis(), pendingIntent3);
tshepang
  • 12,111
  • 21
  • 91
  • 136

1 Answers1

0

Instead of setting up the alarms in your onCreate method in the activity, you should create a separate class like shown here. This would also solve the issue you're having when your activity is out of focus.

Also, for setting a repeating alarm, you should be able to do it with setRepeating() method of AlarmManager. Reference

Community
  • 1
  • 1
Rahin
  • 943
  • 6
  • 21
  • thanks that was very helpful. Although, I could not do exactly what I wanted to do with setRepeating() method of alarm manager. – user2242590 Dec 30 '13 at 21:32
  • @Rahin the answer linked here runs the code every time the activity is created. If the activity is finished, it will run the code again. I don't think this is what the OP wants. – fsljfke Aug 16 '20 at 19:54