Search code examples
javaandroidalarmmanageralarm

Android : How to use same AlarmManager in loop?


I write bellow method for alarm.

 public void alarm(int time){
    Intent intent = new Intent(MainActivity.this, Alarm.class);

    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0 , intent, 0);
    am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+time*1000, pi);
}

This method working perfectly. But the problem when I call the method more than one time. Like,

alarm(10);
alarm(50);

This time it only invoke alarm(10); But don't invoke alarm(50);

Anyone please help why it show this problem!


Solution

  • Your PendingIntent has the same properties both times you call your method. When you call PendingIntent.getBroadcast() the second time it will return the PendingIntent that was already created the first time.

    If you want the alarm to trigger twice you need to do something like this:

    public void alarm(int time, int requestCode){
        Intent intent = new Intent(MainActivity.this, Alarm.class);
    
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), requestCode , intent, 0);
        am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+time*1000, pi);
    }
    

    And then call it like this:

    alarm(10, 0);
    alarm(50, 1);