FirmwareEngineer
FirmwareEngineer

Reputation: 11

Setting multiple alarms to call a service

So I've been trying to set multiple alarms from my activity which will make a call to my service which handles writing to a text file. But for whatever reason I simply cannot get it to work right. In its most simple form I have this:

AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
        AlarmManager pm = (AlarmManager)getSystemService(ALARM_SERVICE);
        PendingIntent myIntent = PendingIntent.getService(MyLifeActivity.this, 0, new Intent(MyDogsLifeActivity.this, TimerService.class), 0);

        PendingIntent myIntent2 = PendingIntent.getService(MyLifeActivity.this, 0, new Intent(MyDogsLifeActivity.this, TimerService.class), 0);




Calendar tomorrow = new GregorianCalendar();

          tomorrow.setTimeInMillis(System.currentTimeMillis()); 
          tomorrow.clear(); 
          tomorrow.set(2012,2,9,17,21); // set for today 3/9/2012 at 5:21 PM.

        am.setRepeating(AlarmManager.RTC_WAKEUP, tomorrow.getTimeInMillis(), fONCE_PER_DAY, myIntent);
        Toast.makeText(MyLifeActivity.this, "AM Set for "+ tomorrow.getTime() ,Toast.LENGTH_LONG).show();


        Calendar tomorrow1 = new GregorianCalendar();
        tomorrow1.setTimeInMillis(System.currentTimeMillis()); 
          tomorrow1.clear(); 
          tomorrow1.set(2012,2,9,17,22); // set for today 3/9/2012 at 5:22 PM.


        pm.setRepeating(AlarmManager.RTC_WAKEUP, tomorrow1.getTimeInMillis(), fONCE_PER_DAY, myIntent2);

        Toast.makeText(MyLifeActivity.this, "PM Set for "+ tomorrow1.getTime() ,Toast.LENGTH_LONG).show();

In this latest iteration, only the latest one will actually call my service at the correct time. My earlier one simply gets ignored.

Ideally I want to be able to call the same service from different different timers at different times. I know the above code doesn't exactly do this but this is really just a test to understand how this really works. But as you can see it really doesn't. Any help would be really appreciated as I've been struggling with this for a long, long time.

Upvotes: 1

Views: 351

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006584

In this latest itteration, only the latest one will actually call my service at the correct time. My earlier one simply gets ignored.

You only set one alarm.

Alarms are uniquely identified by their PendingIntent. myIntent and myIntent2 are the same object, because you used getActivity() with the same Intent.

Hence, you only set one alarm. If you want two alarms, you need two different PendingIntent objects.

Reputedly, providing different values for the second parameter to getActivity() (where you have 0 for both) will be sufficient, though I have not tried this.

Another approach would be to add something (other than an extra) to one of the Intent objects, like an action string, to make it be different from an equivalence standpoint.

Upvotes: 1

Related Questions