Time/Date change listener

人盡茶涼 提交于 2019-12-03 22:51:57

问题


I want to make a time or date listener which for example invoke an activity every day at 9 AM. I am not sure what is the best way to do that? I know I can use Alarm Manager, but I don't know how to make it repetitive?

Does anyone know? Thank you very much in advance.

Cheer :)


回答1:


I know I can use Alarm Manager, but I don't know how to make it repetitive?

Use setRepeating() and specify a repeat interval of INTERVAL_DAY:

    static void scheduleAlarms(Context ctxt) {
      AlarmManager mgr=(AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
      Intent i=new Intent(ctxt, ScheduledService.class);
      PendingIntent pi=PendingIntent.getService(ctxt, 0, i, 0);

      mgr.setRepeating(AlarmManager.ELAPSED_REALTIME,
                       SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY,
                       AlarmManager.INTERVAL_DAY, pi);
  }

The above code will set up an alarm that will go off 24 hours from right now and every 24 hours thereafter. To have it start at 9am, replace ELAPSED_REALTIME with RTC and replace SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY with 9am (today or tomorrow), such as via a Calendar object.



来源:https://stackoverflow.com/questions/11085628/time-date-change-listener

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