currently I have a application which can send notifications, I would like this application to be able to send these notifications automatically every x minutes (for example, 15 minutes is the default). The app may or may not be currently running when this notification should be sent.
After some reading, I've determined that an AlarmManager would be used here, but I cannot figure out how to call a method from it. I already have the notification code, I just need a way to call it every x minutes.
I'm very new to this, this is my first practice app (having experience in C#, but little in Java).
Thanks, David.
If you want to schedule your tasks with the specified interval don't use flags
AlarmManager.RTC
andAlarmManager.RTC_WAKEUP
with methodalarm.setRepeating(...)
. Because in this case alarm will be bounded to the device's real time clock. So changing the system time may cause alarm to misbehave. You must use flagsAlarmManager.ELAPSED_REALTIME
orAlarmManager.ELAPSED_REALTIME_WAKEUP
. In this caseSystemClock.elapsedRealtime()
will serve as a basis for scheduling an alarm.The code will look like:
If you want your long running task to be executed when device in the sleep mode I recommend to use WakefulIntentService library by CommonsWare: https://github.com/commonsguy/cwac-wakeful
Write a
IntentService
. Inside it, just start a newThread
. In theThread.run()
, put an infinite while loop to call your notification code andThread.sleep(15 * 60 * 1000)
....You might want to consider something like this:
If you are unclear, go through this tutorial