How to set more than one alarm simultaneously in Android?

I am creating a small application where I need to set an alarm from an array, but only one alarm is set and works at the time that is in the last position of the array, why it behaves as follows: this is my code

AlarmManager[] alarmManager=new AlarmManager[24]; for(f=0;f<arr2.length;f++) { Intent intent = new Intent(AlarmR.this, Riciving.class); pi=PendingIntent.getBroadcast(AlarmR.this, 0,intent, 0); alarmManager[f] = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager[f].set(AlarmManager.RTC_WAKEUP,arr2[f] ,pi); } 

Thanks at Advance

+9
android alarmmanager
Aug 31 2018-11-11T00:
source share
2 answers

On your pendingIntent you need to set the second requestCode to a unique number. I usually run the array through a for loop and dynamically set the request code for each element of the array. Without requestCode alarms overwrite each other.

 AlarmManager[] alarmManager=new AlarmManager[24]; intentArray = new ArrayList<PendingIntent>(); for(f=0;f<arr2.length;f++){ Intent intent = new Intent(AlarmR.this, Riciving.class); pi=PendingIntent.getBroadcast(AlarmR.this, f,intent, 0); alarmManager[f] = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager[f].set(AlarmManager.RTC_WAKEUP,arr2[f] ,pi); intentArray.add(pi); } 

Basically, you just want to change requestCode to a dynamic number. By setting it to f , you give it a new unique identifier for each element of the array. Keep in mind that if you want to cancel alarms, you will need to use another for the loop and cancel each separately. I personally add all my alarms to my own array so that I can handle them separately.

Then, if you need to cancel them:

  private void cancelAlarms(){ if(intentArray.size()>0){ for(int i=0; i<intentArray.size(); i++){ alarmmanager.cancel(intentArray.get(i)); } intentArray.clear(); } } 
+22
Aug 31 '11 at 6:30 a.m.
source share

If you want to set several alarms (repeating or single), you just need to create their PendingIntents using another requestCode. If requestCode is the same, then the new alarm will overwrite the old one.

Here is the code for creating several single alarms and saving them in an ArrayList. I store the PendingIntent in an array because this is what you need to cancel the alarm. // context variable contains your Context

 AlarmManager mgrAlarm = (AlarmManager) context.getSystemService(ALARM_SERVICE); ArrayList<PendingIntent> intentArray = new ArrayList<PendingIntent>(); for(i = 0; i < 10; ++i) { Intent intent = new Intent(context, OnAlarmReceiver.class); // Loop counter `i` is used as a `requestCode` PendingIntent pendingIntent = PendingIntent.getBroadcast(context, i, intent, 0); // Single alarms in 1, 2, ..., 10 minutes (in `i` minutes) mgrAlarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 60000 * i, pendingIntent); intentArray.add(pendingIntent); } 
+3
Jun 27 '13 at 7:45
source share



All Articles