-1

I am currently working on an android app with a reminder service. I am using AlarmManager. I have successfully been able to set the alarm to run when the user clicks a button. But I want it to run from a start day to a finish day. But right now, it appears to just run forever.

I already have this:

private void setAlarm(String startDate,String endDate, String startTime, Context ctx, long id, int frequency){

Calendar calendar = Calendar.getInstance();

calendar.set(Calendar.YEAR, Utility.getYear(startDate));
calendar.set(Calendar.MONTH, Utility.getMonth(startDate));
calendar.set(Calendar.DAY_OF_MONTH, Utility.getDay(startDate));
calendar.set(Calendar.HOUR_OF_DAY, Utility.getHour(startTime));
calendar.set(Calendar.MINUTE, Utility.getMinute(startTime));

Intent intent = new Intent(ctx,AlarmReceiver.class);
intent.putExtra("ID", (int)id);
intent.setAction(""+System.currentTimeMillis());

PendingIntent mPendingIntent = PendingIntent.getBroadcast(ctx, (int) id, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager)ctx.getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), (AlarmManager.INTERVAL_DAY / frequency), mPendingIntent);
}

The alarm works. I just need to set it to be able to stop when the endDate has been reached. Thanks.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Adora
  • 9
  • 4

2 Answers2

1

You cant specify the end time for the Alarm manager directly. What you can do is manually cancel the alarm manager in your broadcast receiver.In order to cancel the Alarm Manager you need to make sure the pending intent has the same request code as the one which you used to set the alarm. Use the cancel method of the AlarmManager class with the pending intent as the parameter.

Dishonered
  • 8,449
  • 9
  • 37
  • 50
0

You want to set repetitive alarm within a time range. you can store the timestamp of the end date in SharedPreferences. Every time the Pending Intent starts you need to check if it crosses the end date limit. If it does, cancel the alarm calling the cancel method alarmManager.cancel(pendingIntent);

Ashikee AbHi
  • 385
  • 2
  • 12