Search code examples
androidalarmmanager

Time/Date change listener


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


Solution

  • 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.