Thursday, November 24, 2011

Android how to schedule multiple alarms

The Android alarm service is very useful if for scheduling tasks to be done at future dates.  A common use is passing a PendingIntent to the AlarmManager.  When the alarm wakes up the phone, a broadcastReceiver is used to perform the desired actions:

Intent intent = new Intent(a, AlarmReceiver.class);
intent.putExtra("row_id", rowId);
final int alarmId = (int) System.currentTimeMillis();
PendingIntent sender = PendingIntent.getBroadcast(a, alarmId, intent,
    PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) a.getSystemService(a.ALARM_SERVICE);
    am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), sender);

Notice the "alarmId" above.  By setting different private request codes as an argument for the getBroadcast function, you can schedule multiple alarms.  If you use the same id, the previous alarms scheduled will be cancelled.

12 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Thanks so much!! thats what I was looking for for. keep it up :)

    ReplyDelete
  3. Hi my code for multiple alarm is not working
    can u plzz help me out?
    Thanx in advance



    Intent intentAlarm = new Intent(MainActivity.this,AlarmReceiver.class);
    final int _id = (int) System.currentTimeMillis();
    Log.d("id",_id+"");
    PendingIntent intent = PendingIntent.getBroadcast(this, _id, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT);
    long r4=r3+new GregorianCalendar().getTimeInMillis();
    AlarmManager alarmManager=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP,r4, intent);

    ReplyDelete
    Replies
    1. :( code not working for me.

      Intent intent = new Intent(MainTabBottomActivity.this, MyAlarmService.class);
      // intent.putExtra("row_id", 1);
      final int alarmId = (int) System.currentTimeMillis();
      PendingIntent sender = PendingIntent.getBroadcast(MainTabBottomActivity.this, alarmId, intent,PendingIntent.FLAG_UPDATE_CURRENT);
      Calendar calendar = Calendar.getInstance();
      calendar.setTimeInMillis(System.currentTimeMillis());
      calendar.add(Calendar.SECOND, 10);
      AlarmManager am = (AlarmManager) MainTabBottomActivity.this.getSystemService(MainTabBottomActivity.this.ALARM_SERVICE);
      am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);

      Delete
  4. its helpful, i can solve my issue, thanks :)

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. Hello, I have created 5 users at 7:00AM then 4 users is firing on 7:00AM but one user is not hitting or created 7 user at 7:00am then 6 users is firing on 7:00AM but every time missing one user. Can you solve my issue? My email address sameer.digisoft@gmail.com

    ReplyDelete
  7. I like how in 2018, this comment saved my sleepless nights. Thanks sir

    ReplyDelete