Schedule a Service Using AlarmManager and JobScheduler

Service is commonly used for background tasks such as sending a request to an API and downloading file. Service runs only once. To make it run periodically, AlarmManager and JobScheduler are used. Both can be used to initiate a long-running operation outside the lifetime of your app. 

Schedule a Service with AlarmManager

Let’s say we want to execute RSSService every 60 minutes. Following are the code to schedule and cancel an alarm to carry out the task.

Schedule an alarm

[java]
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

Intent intent = new Intent(context, RSSService.class);
intent.setAction(“com.example.action.RSS”);
PendingIntent pendingIntent = PendingIntent.getService(context, RSS_SERVICE_ID, intent,
PendingIntent.FLAG_CANCEL_CURRENT);

Calendar now = Calendar.getInstance();
now.add(Calendar.MINUTE, 60);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
now.getTimeInMillis(), 60 * 60 * 1000, pendingIntent);
[/java]

Cancel an alarm

[java]
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

Intent intent = new Intent(context, RSSService.class);
PendingIntent pendingIntent = PendingIntent.getService(context, RSS_SERVICE_ID, intent, 0);
alarmManager.cancel(pendingIntent);
[/java]

Schedule a Service with JobScheduler

JobScheduler was introduced starting from Android API 21. So it is a better solution to schedule task for devices targeting API 21+.

Create a JobService

The first thing to do is to create a RSSJobService class which extends from JobService to carry out background task. The JobService runs on  main thread so you need to move the task off thread (AsyncTask).

[java]
public class RSSJobService extends JobService {

@Override
public boolean onStartJob(JobParameters params) {
//do something here
//return true to promt that the task will be processed on a separate thread. Otherwise, use false.
return true;
}

@Override
public boolean onStopJob(JobParameters params) {
//do something here
return true;
}
}
[/java]

Similar to Service, it is required to add a JobService class to Manifest file within application tag.

[xml]
<service
android:name=”.RSSJobService”
android:permission=”android.permission.BIND_JOB_SERVICE”
android:exported=”true”/>
[/xml]

Create JobInfo and schedule it

[java]
ComponentName rssJobService = new ComponentName(context, RSSJobService.class);
JobInfo jobInfo = new JobInfo.Builder(JOB_ID, rssJobService).setPeriodic(60*60*1000).build();

//schedule
JobScheduler jobsSheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
int result = jobsSheduler.schedule(jobInfo);

//cancel
jobsSheduler.cancel(JOB_ID); //cancel by JOB_ID
jobsSheduler.cancelAll(); //cancel all

[/java]

Leave a Comment

Your email address will not be published. Required fields are marked *


Scroll to Top