Time/Date change listener

后端 未结 1 1487
梦毁少年i
梦毁少年i 2021-01-07 14:12

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,

1条回答
  •  生来不讨喜
    2021-01-07 14:32

    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.

    0 讨论(0)
提交回复
热议问题