0

I am starting my alarm at 8am using below code, repeating at every 1min. I want to stop this alarm repeating at 12pm. I am starting alarm like this:

AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
PendingIntent loggerIntent1 = PendingIntent.getBroadcast(this, 0,new Intent(this,AlarmReceiver.class), 0);
Calendar timeOff9 = Calendar.getInstance();
timeOff9.set(Calendar.HOUR_OF_DAY, 08);
timeOff9.set(Calendar.MINUTE, 00);
timeOff9.set(Calendar.SECOND, 00);


long duration = interval * 60 * 1000;
manager.setRepeating(AlarmManager.RTC_WAKEUP,timeOff9.getTimeInMillis(), duration, loggerIntent1);

and stopping with this code:

Calendar timeOff = Calendar.getInstance();
timeOff.set(Calendar.HOUR_OF_DAY,12);
timeOff.set(Calendar.MINUTE,00);
timeOff.set(Calendar.SECOND, 00);

manager.set(AlarmManager.RTC_WAKEUP,timeOff.getTimeInMillis(), loggerIntent1);
manager.cancel(loggerIntent1);
loggerIntent1.cancel(); 

but the code for stopping causes the app to work the wrong way. I am writing the code to stop alarm right after first alarm. is it the problem? Do I need to write another alarm. Please guide.

user2310041
  • 101
  • 1
  • 2
  • 10
  • Well you may need another Alarm for ending it Reference http://stackoverflow.com/questions/23829176/cancel-repeating-alarm-at-specific-time – Umair Khalid Jan 03 '17 at 07:25

1 Answers1

0

Maybe there is another logic you could give a try?

Imagine this, carry on with your first portion of code where you trigger an intent for every duration.

But inside your AlarmReceiver.class, that will be the one checking current time, and do the AlarmManager.cancel() when the time is over 12pm.

Chor Wai Chun
  • 3,226
  • 25
  • 41