Job Scheduler - Tuong-Nguyen/PreparationEduLog GitHub Wiki

Intro

  • JobScheduler was introduced in Lollipop (API level 21)
  • Apps can schedule jobs while letting the system optimize based on memory, power and connectivity conditions
  • Allow batching jobs

Schedule conditions

  • The task can be schedule to run under specific conditions:
    • Device is charging
    • Device is idle
    • Device is connected to a network or an unmetered network
    • Start before a certain deadline
    • Start within a predefined time window, ex: within the next hour
    • Start after a minimal delay, ex: wait a minimum of 10 minutes
  • Constraints can be combined

How to use

  • There are three main parts:
  • JobInfo: Define triggers - Schedule conditions.
  • JobService: Define what service does.
  • JobScheduler: Apply the JobInfos into JobService.

JobService

  • Must be a subclass of JobService
public class HttpJobService extends JobService {
    //...
}
  • Override onStartJob and onStopJob
  • Create an AsyncTask to handle a long-running task
    private class UpdateAppsAsyncTask extends AsyncTask<JobParameters, Void, JobParameters[]> {
        @Override
        protected JobParameters[] doInBackground(JobParameters... params) {
            // Do updating and stopping logical here.
            return params;
        }

        @Override
        protected void onPostExecute(JobParameters[] result) {
            // ....
        }
    }
  • Execute AsyncTask in onStartJob event
    private UpdateAppsAsyncTask updateTask = new UpdateAppsAsyncTask();
    @Override
    public boolean onStartJob(JobParameters params) {
        // Note: this is preformed on the main thread.
        // ...
        updateTask.execute(params);
        return true;
    }
  • jobFinished() is called based on the success value passed into onPostExecute() callback of the async task
        @Override
        protected void onPostExecute(JobParameters[] result) {
            // Logic for stopping a job
            jobFinished(params, false);
        }
  • Register the JobService
<application>
    <!-- ... -->
    <service
        android:name=".service.HttpJobService"
        android:permission="android.permission.BIND_JOB_SERVICE"/>
</application>

JobInfo

  • Create a scheduled job with the Builder
        ComponentName serviceComponent = new ComponentName(context, HttpJobService.class);
        JobInfo.Builder builder = new JobInfo.Builder(0, serviceComponent);
        builder.setMinimumLatency(1000);

Note:

  • setPeriodic(<interval in milliseconds>): interval is at least 15 mins (minimum value get from getMinPeriodMillis())
  • setPeriodic(long) combines with setMinimumLatency(long) or setOverrideDeadline(long) will result in an error.
  • Get JobInfo from builder
   JobInfo jobInfo = builder.build();

JobScheduler

  • Create JobScheduler object
    JobScheduler scheduler = context.getSystemService(JobScheduler.class);
  • Schedule the job
    scheduler.schedule(jobInfo);

Trigger job scheduler after a reboot of system

  • Create a BroadcastReceiver
public class MyStartServiceReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // Create scheduler and schedule the job
    }
}
  • Register the receiver in the Android manifest
<receiver android:name="MyStartServiceReceiver" >
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

References

⚠️ **GitHub.com Fallback** ⚠️