Chapter 28 Background Services
When onStopJob(...) is called, your service is about to be shut down. No waiting is allowed: You must
stop your work immediately. Returning true here means that your job should be rescheduled to run
again in the future. Returning false means, “Okay, I was done anyway. Do not reschedule me.”
When you register your service in the manifest, you must export it and add a permission:
<service
android:name=".PollService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="true"/>
Exporting it exposes it to the world at large, but adding the permission restricts it back down so that
only JobScheduler can run it.
Once you have created a JobService, kicking it off is a snap. You can use JobScheduler to check on
whether your job has been scheduled.
final int JOB_ID = 1;
JobScheduler scheduler = (JobScheduler)
context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
boolean hasBeenScheduled = false;
for (JobInfo jobInfo : scheduler.getAllPendingJobs()) {
if (jobInfo.getId() == JOB_ID) {
hasBeenScheduled = true;
}
}
If your job has not been scheduled, you can create a new JobInfo that says when you want your job to
run. Hmm, when should PollService run? How about something like this:
final int JOB_ID = 1;
JobScheduler scheduler = (JobScheduler)
context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
JobInfo jobInfo = new JobInfo.Builder(
JOB_ID, new ComponentName(context, PollService.class))
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
.setPeriodic(1000 60 15)
.setPersisted(true)
.build();
scheduler.schedule(jobInfo);
This schedules your job to run every 15 minutes, but only on WiFi or another unmetered network.
Calling setPersisted(true) also makes your job persisted so that it will survive a reboot. Check out
the reference documentation to see all the other ways you can configure a JobInfo.