Background Task with JobScheduler in Android

In this tutorial, you will learn how to use background task with JobScheduler API in Android.

The JobScheduler API performs a queue based operation for your application when a set of predefined conditions are met. Unlike the AlarmManager class, the timing isn’t exact. In addition, the JobScheduler API is able to batch various jobs to run together. This allows your app to perform the given task while being considerate of the device’s battery at the cost of timing control.


Scheduling a Job

In order to schedule a job you must define 2 components:

  • JobInfo that holds the constraints of when the job should run (e.g. only on WiFi, only when plugged in, periodically, etc.)
  • JobService that is a service that handles the scheduled requests.

Ccreating the JobInfo

In order to create our JobInfo object we use the JobInfo.Builder

The JobInfo needs an unique integer id and a service component that will be our implementation of JobService.

Now Schedule the JobInfo with JobSchduler.

Creating the JobService

The JobService is the child class of service and entry point of executing your scheduled job. You create your service by extending JobService and overriding the onStartJob(JobParameters jobParameters) and onStopJob(JobParameters params) callbacks.

You must take your job implementation from the onStartJob callback on another thread as this method is called on the application’s main thread.

defining our JobService in the AndroidManifest.xml file


Cancelling a Job 

To a cancel a single job from the task, you need to call cancel() with the current job id as the parameter that is pending in the JobScheduler.

To cancel all jobs, you need to call cancelAll().

jobscheduler jobscheduler_newjob jobscheduler_finishjob

Compatible API Level

JobScheduler is currently available for api level 21 (Android 5.0) and above.


Complete Source code available here.

About Durga Chiranjeevi

I’m a normal guy, engineer by education who is passionate about Programming and Internet. An android enthusiast, now moving for cross platforms and game development.