Arturouu
Arturouu

Reputation: 23

How to set android alarm to trigger until an specific date

I'm new to android and using alarmManager and I was wondering if there is a way to set an alarm in android that triggers for example every monday until a certain specific date. Like this : Start date 10/09/15 Remind me something every monday at 2:30 pm Until End date 11/09/15

Upvotes: 2

Views: 1337

Answers (2)

Vaishak Nair
Vaishak Nair

Reputation: 918

 AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 14);
        calendar.set(Calendar.MINUTE, 30);
        int weekInMillis = 7 * 24 * 60 * 60 * 1000;

        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                weekInMillis, PendingIntent.getBroadcast(context, 0, new Intent(context, ReminderAlarmWakefulBroadcastReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT));

Above code snippet sets an alarm for 2:30 PM that repeats itself every week. Tweak calendar for varying the time at which the alarm goes off. For example, the coming Monday.

When the alarm goes off, it sends a broadcast which will be received by ReminderWakefulBroadcastReceiver, a custom receiver containing the code that you want to run every Monday at 2:30 PM. This code should also check whether it is time to cancel the alarm and if it is, the following code cancels it:

 AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
 alarmManager.cancel(PendingIntent.getBroadcast(context, 0, new Intent(context, ReminderAlarmWakefulBroadcastReceiver.class));

References: AlarmManager, Scheduling Repeating Alarms, PendingIntent

Upvotes: 2

JBA
JBA

Reputation: 2899

If you know how to setup an Alarm, the solution is quite simple:

1) At the time you setup the Alarm, calculate the maximum timestamp you want it to run, and save it as a local preference.

2) Then in the Alarm code itself, each time it is triggered you can make a first test to see if the current timestamp is before or after your limit preference saved at first time.

3) If reached, then cancel the Alarm as @karthik said. If not, keep your code going...

Upvotes: 0

Related Questions