The JobScheduler API Android

Rohan Shrestha

       

The JobScheduler API Android

If you want to have a repetitive task in your Android app, then there are various ways to achieve it in android operating system. Developers can add a repetitive task in their app via following methods:

1.   Using Handler/TimerTasks

2.   Using AlarmManager 

3.   Using JobScheduler Api


JobScheduler Api


JobScheduler api was first introduced in Android 5.0 Lollipop (API 21). This api performs work based on conditions not on time. Job scheduler operates on system level thus can intelligently batch jobs from different apps to run on specific time. This means we can minimize things like radio use, which is a clear battery win.

How to use a JobScheduler?


Firstly, define the work you want to schedule in a JobService. JobService is an android service that extends JobService class. JobService implements three methods.

1. onStartJob() is called by the system when it is time for your job to execute. If your task is small and short, feel free to implement the logic directly inside onStartJob() and return false. However, if you want to perform more complicated task like network connection then you will need to kick a background thread and return true.

@Override   
public boolean onStartJob(final JobParameters params){       
    mDownloadArtworkTask = new DownloadArtworkTask(this){   
        @Override

       protected void onPostExecute(Boolean success)   

            jobFinished(params, !success)

       }

   };

    mDownloadArtworkTask.execute();

    return true;

}

2.  jobFinished() is not the method that you can override and the system won’t call it. That’s because you will need to call it once your background thread has finished the job. This is how to system knows that it can safely release your wakelock. If you forget to call jobFinished(), your app is going to look pretty guilty in the battery stats lineup.

3.  onStopJob() is called by the system if the job is cancelled before being finished. This generally happens when your job conditions are no longer being met, such as when the device has been unplugged or if WiFi is no longer available. So use this method for any safety checks and clean up you may need to do in response to a half-finished job. Then, return true if you’d like the system to reschedule the job, or false if it doesn’t matter and the system will drop this job.

@Override
public boolean onStopJob(final JobParameters params) {
    if (mDownloadArtworkTask != null) {
        mDownloadArtworkTask.cancel(true)
    }
    return true;
}

As with any service, you’ll need to add this one to your AndroidManifest.xml like so.

<service 
android:name=".sync.DownloadArtworkJobService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="true"/>

Secondly, consider the condition that must be met to run you job.  You can define these conditions through the JobInfo object. To build that JobInfo object, you need two things every time: a job number — to help you distinguish which job this is — and your JobService.

JobInfo.Builder jobBuilder = new JobInfo.Builder(LOAD_ARTWORK_JOB_ID, new ComponentName(this, DownloadArtworkJobService.class))
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.build()

Here, JobInfo.NETWORK_TYPE_ANY is the condition that needs to be true in order for the job to run. Other such conditions includes:

1.  Network type

2.  Charging and idle

3.  Content Provider update

4.  Backoff criteria

5.  Periodic

6.  Persistent

Finally, consider scheduling the job using JobScheduler and then call schedule() method using the jobInfo object created above.

JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(jobBuilder);