Stop a service at specific time

為{幸葍}努か 提交于 2019-12-11 08:57:33

问题


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:


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);



来源:https://stackoverflow.com/questions/16479426/stop-a-service-at-specific-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!