Stop a service at specific time

2019-08-06 09:17发布

I am starting my service using below code repeatedly. My service starts at 8am everyday. And AlarmManager repeates at every 1 min. I want to stop this sevice at 6pm. how can I do this ?

    AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    PendingIntent loggerIntent = 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 = userinterval * 60 * 1000;
    manager.setRepeating(AlarmManager.RTC_WAKEUP,timeOff9.getTimeInMillis(), duration, loggerIntent);

1条回答
beautiful°
2楼-- · 2019-08-06 09:17

In order to cancel at 6pm exactly, I would consider 2 options:

  1. Each time the alarm triggers (i.e. every 1 minute), check the time, and cancel if time is after 6PM.
  2. Set a once-off alarm in AlarmManager to go off at 6PM exactly. In that alarm, cancel.

I prefer option 2 for simplicity, and modularity of each code block. So for me, I would use (2) in my proof-of-concept code, while working on the solution.

But option 1 is better from a resources point of view, as the Android system only needs to remember a single alarm. I would use (1) in my final production code.

This way of working is just my personal preference, and most ppl probably will say to use (1) right away from the start.

The details about cancelling are below...


As for how to cancel an alarm, you don't often beat an answer by @commonsware....

Below answer copied from How to cancel this repeating alarm?


Call cancel() on AlarmManager with an equivalent PendingIntent to the one you used with setRepeating():

Intent intent = new Intent(this, AlarmReceive.class);
PendingIntent sender = PendingIntent.getBroadcast(this,
               0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

alarmManager.cancel(sender);

查看更多
登录 后发表回答