Skip to content Skip to sidebar Skip to footer

Call A Method Every X Minutes

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 min

Solution 1:

You might want to consider something like this:

Intentintent=newIntent(this, MyService.class);
PendingIntentpintent= PendingIntent.getService(this, 0, intent, 0);

AlarmManageralarm= (AlarmManager)getSystemService(Context.ALARM_SERVICE);
// Start every 30 seconds
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent); 

If you are unclear, go through this tutorial

Solution 2:

Write a IntentService. Inside it, just start a new Thread. In the Thread.run(), put an infinite while loop to call your notification code and Thread.sleep(15 * 60 * 1000)....

Solution 3:

If you want to schedule your tasks with the specified interval don't use flags AlarmManager.RTC and AlarmManager.RTC_WAKEUP with method alarm.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 flags AlarmManager.ELAPSED_REALTIME or AlarmManager.ELAPSED_REALTIME_WAKEUP. In this case SystemClock.elapsedRealtime() will serve as a basis for scheduling an alarm.

The code will look like:

alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + checkIntervalMillis, checkIntervalMillis, pendingIntent);

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

Post a Comment for "Call A Method Every X Minutes"