Skip to content
DeveloperMemos

How to Use Android's JobScheduler

Android, JobScheduler1 min read

The JobScheduler API was introduced in Android 5.0 (Lollipop) as a way to manage scheduled jobs in the background. With JobScheduler, you can schedule jobs to run when certain conditions are met, such as when the device is charging or connected to Wi-Fi.

In this tutorial, we'll go over the basics of how to use JobScheduler in your Android app using Kotlin.

Creating a JobService

Before we can use JobScheduler, we need to create a class that extends JobService. This is where we define the job that we want to run.

1class MyJobService : JobService() {
2 override fun onStartJob(params: JobParameters?): Boolean {
3 // Do work here
4 return true // Return true if there is still work to do
5 }
6
7 override fun onStopJob(params: JobParameters?): Boolean {
8 // Called when the job is cancelled before completed
9 return true // Return true to reschedule the job
10 }
11}

In this example, we've created a simple JobService that does some work in onStartJob(). The method returns true because there is still work to do. If the job completes successfully, we'd return false instead.

onStopJob() is called if the job is cancelled before it completes. We're returning true here so that the job can be rescheduled to run again. Also make sure that you define this service properly in your AndroidManifest.xml file.

Scheduling a Job

Once we've created our JobService, we can use the JobScheduler to schedule it to run at a specific time or under certain conditions using a JobInfo object.

1val jobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
2
3val jobInfo = JobInfo.Builder(1, ComponentName(this, MyJobService::class.java))
4 .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
5 .setRequiresCharging(true)
6 .build()
7
8jobScheduler.schedule(jobInfo)

In this example, we're creating a new JobInfo object that specifies that the job should only run when the device is charging and connected to an unmetered network. We're also assigning it a unique ID of 1.

Finally, we call jobScheduler.schedule() passing in the JobInfo object to schedule the job.

Cancelling a Job

If you need to cancel a scheduled job, you can use the JobScheduler to cancel it by its ID.

1val jobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
2jobScheduler.cancel(1)

In this example, we're cancelling the job with the ID of 1 that we scheduled earlier.

In Conclusion

JobScheduler provides a powerful way to manage background tasks in your Android app. By scheduling jobs to run when certain conditions are met, you can avoid unnecessary battery drain and ensure that your app is running efficiently.

In this tutorial, we've gone over the basics of how to use JobScheduler in your Android app using Kotlin. With this knowledge, you should be able to start implementing background tasks in your app with ease.