Menu

AlarmManager – run any code in the background at certain intervals

Android By Feb 02, 2015 No Comments
If you want to run a piece of code in the background at certain intervals, then AlarmManager is the class helps us to do this. It will wake up the device on the given intervals and invokes the Receiver class where we should write our code to run in the background. Below code snippet explains how to implement AlarmManager.
Intent notificationIntent = new Intent(context, LoadData.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent   pendingIntentSyncDB;=
PendingIntent.getBroadcast(context, 0,
                                notificationIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager)  getSystemService(Context.ALARM_SERVICE);
int intervalTime = 1000 * 60 * 5 ;// 5min
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
intervalTime, pendingIntentSyncDB);

In the above snippet, LoadData is a broadcast receiver class which executes the background code. AlarmManager invokes the LoadData for every 5mins.

No Comments

Leave a comment

Hi, Welcome here.
JOIN OUR NEWSLETTER
And get notified everytime we publish a new blog post.