Search code examples
javaandroidandroid-alarms

Can I set an end time for AlarmManager in Android?


I have set up an AlarmManager to go off at a specific time, and then repeat in intervals. Is it possible to tell it after how many intervals to stop? Or even at what time to stop?

This is what I have so far:

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 13);
    calendar.set(Calendar.MINUTE, 56);
    Intent intent = new Intent(this, MyService.class);
    alarmIntent = PendingIntent.getService(this, 0, intent, 0);
    alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            1000 * 60 * 60, alarmIntent);

Also do I need to do anything to ensure it will go off every day? Or is it already doing that?


Solution

  • Is it possible to tell it after how many intervals to stop? Or even at what time to stop?

    There's no way to specify an end time for an AlarmManager, but what you can do is, every time you receive your pending intent in your broadcast receiver, check to see if you need to cancel that alarm. To cancel the alarm, you need to call alarmManager.cancel(pendingIntent), where pendingIntent has the same requestCode that you used for the PendingIntent that you originally created the alarm with.

    Also do i need to do anything to ensure it will go off every day?

    You need to set the interval to: 1000 * 60 * 60 * 24 if you want it to fire once per day.

    You also need to take care of the situation of a device reboot. If the user reboots the device, the alarms will be cleared and you need to recreate them. You will need to implement another BroadcastReceiver that listens for RECEIVE_BOOT_COMPLETED, and add logic in your onReceive() to recreate your alarms.

    Also, this line is unnecessary:

    calendar.setTimeInMillis(System.currentTimeMillis());
    

    This line:

    Calendar calendar = Calendar.getInstance();
    

    already gives you a Calendar object set to the exact time you create it.

    You should also add the following lines to make sure your alarm fires at exactly 13:56 each day:

    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);