Search code examples
androidbroadcastreceiveralarmmanagerandroid-pendingintent

Multiple AlarmManager firing isn't firing at a time


When I set multiple AlarmManager at the same time, it only fires the first one.

There is a MessageReceiver class that extends BroadcastReceiver. When AlarmManager will fire MessageReceiver (onReceive() method) will be executed. From MainActivity, I create PendingIntent and set the AlarmManager.

MessageReceiver.java

public class MessageReceiver extends BroadcastReceiver {
@Override
    public void onReceive(Context context, Intent intent) {
        Log.d("Msg","triggered");
        //Do some work
    }
 }

MainActivity.java

AlarmManager msgAlarmManager = (AlarmManager)  getSystemService(Context.ALARM_SERVICE);
Intent msgIntent = new Intent(MainActivity.this,MessageReceiver.class);


PendingIntent msgPending = PendingIntent.getBroadcast(context,
    ++requestCode,
    msgIntent,
    PendingIntent.FLAG_ONE_SHOT);//requestCode is a global variable


msgAlarmManager.setExact(
        AlarmManager.RTC_WAKEUP,
        calender.getTimeInMillis(),
        msgPending); //calender is a Calender Object

This piece of code from MainActivity.java will be executed multiple times in a single runtime of my application.

I want every single Alarm to be fired even if they supposed to be fired at the same time. But in my case, the only first one is firing and another AlarmManager isn't. How can I make sure that all AlarmManager is firing?


Solution

  • Simply just using a unique value as request code helped to solve the problem. So, the change will be only into the PendingIntent and updated PendingIntent will be like this:

    Random random = new Random();
    PendingIntent msgPending = PendingIntent.getBroadcast(context,
    random.nextInt(10000),
    msgIntent,
    PendingIntent.FLAG_ONE_SHOT);
    

    Now multiple alarm will be fired.