Search code examples
androidservicebroadcastreceiveralarmmanagerandroid-pendingintent

Multiple Alarms using BroadcastReceiver and AlarmManager


Ive been searching for how to using multiple alarms, and did find post in Stackoverflow, but never a straightful answer.

Im trying to set multiple alarms who will call a receiver class (AlarmBcast in my case) and, according to which alarm triggered the call, take different actions.

At this point I followed my way creating diferent receicer classes for each alarm call (and thus a different Intent, each with his own PendintIntent).

I read someone in other thread suggested making a stack (list) of alarms visible, and so using one receiver class for all alarms, but that is not an approach I would like to take.

There is a way to "see" which pendingintent was responsible for the call?. only the intent is passed, but as there is only one, cant get which call was from it.

Before taking the way of the multiple receivers, this is how my code(pseudo) looked

Setting the alarms...

public class SelectedService extends Service {
   //get dates from main 
   //do some date math
     AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
     Intent _myIntent = new Intent(this, AlarmBcast.class);
   //setting Alarm A
     PendingIntent _myPendingIntent = PendingIntent.getBroadcast(this, 123, _myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
     alarmManager.set(AlarmManager.RTC_WAKEUP, partidocalendar.getTimeInMillis(),_myPendingIntent);
   //setting Alarm B
     PendingIntent _myPendingIntent2 = PendingIntent.getBroadcast(this, 124, _myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
     alarmManager.set(AlarmManager.RTC_WAKEUP, convopartidocalendar.getTimeInMillis(),_myPendingIntent2);
   //setting Alarm C

The receiver as i wa planning it ...

public class AlarmBcast extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
    //how to identify call A from B ??
    if(AlarmA){}
    if(AlarmB){}
    }

Maybe i have some conceptual mistake? Back to programming since after 15 years (mostly assembler before)


Solution

  • You can put an "extra" in the Intent that identifies which alarm it is. For example:

    _myIntent.putExtra("alarm", "A");
    

    Do this before calling PendingIntent.getBroadcast() for each different alarm.

    Then, in your BroadcastReceiver.onReceive() you can check the "extra" in the Intent to determine which alarm got triggered.