For the More Curious: JobScheduler and JobServices
public class PollService extends JobService {
@Override
public boolean onStartJob(JobParameters params) {
return false;
}
@Override
public boolean onStopJob(JobParameters params) {
return false;
}
}
When Android is ready to run your job, your service will be started and you will receive a call to
onStartJob(...) on your main thread. Returning false from this method means, “I went ahead and did
everything this job needs, so it is complete.” Returning true means, “Got it. I am working on this job
now, but I am not done yet.”
IntentService created a background thread for you, so you did not have to worry about threading. In
JobService, though, you must implement your own threading. You might do that with an AsyncTask:
private PollTask mCurrentTask;
@Override
public boolean onStartJob(JobParameters params) {
mCurrentTask = new PollTask();
mCurrentTask.execute(params);
return true;
}
private class PollTask extends AsyncTask<JobParameters,Void,Void> {
@Override
protected Void doInBackground(JobParameters... params) {
JobParameters jobParams = params[0];
// Poll Flickr for new images
jobFinished(jobParams, false);
return null;
}
}
When you are done with your job, you call jobFinished(JobParameters, boolean) to say that you
are done. Passing in true for the second parameter means that you were not able to get the job done
this time and it should be rescheduled for the future.
While your job is running, you may receive a call to the onStopJob(JobParameters) callback. This
means that your job needs to be interrupted. This can happen when, for example, you only want your
job to run when a WiFi connection is available. If the phone moves out of WiFi range while your job is
still running, you will get a call to onStopJob(...), which is your cue to drop everything immediately.
@Override
public boolean onStopJob(JobParameters params) {
if (mCurrentTask != null) {
mCurrentTask.cancel(true);
}
return true;
}