Adding extension function for scheduling jobs
Resolves #554
Signature
inline fun <reified T : Service> Context.scheduleJob(
jobId: Int,
buildSequence: JobInfo.Builder.() -> Unit
): Int
Before
val serviceComponent = ComponentName(this, MyService::class.java)
val builder = JobInfo.Builder(jobId++, serviceComponent)
if (wiFiConnectivityRadioButton.isChecked) {
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
} else if (anyConnectivityRadioButton.isChecked) {
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
}
systemService<JobScheduler>().schedule(builder.build())
After
scheduleJob<MyService>(jobId++) {
if (wiFiConnectivityRadioButton.isChecked) {
setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
} else if (anyConnectivityRadioButton.isChecked) {
setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
}
}
Benefits
- no need for a
Contextparameter - compile-time enforcement of the
Servicetype upper bound for the class given to theJobInfo.Buildervia theComponentName(also cleaner by avoiding::class.java) - automatic construction of the
ComponentNameinstance - lambda with receiver for building the
JobInfo - automatic system service retrieval as well as
buildandschedulecalls
* code snippet adapted from Google Samples
Shouldn't this be an extension function of Context then?
Good point ... fixed
Shouldn't this return the int that is returned from schedule? And in light of that, I'm not sure if this constitutes a feature addition or not, but you could also use safe casting and return JobScheduler.RESULT_FAILURE if the service isn't found, which seems to happen a lot.
Fixed
You can have the get system service and schedule calls in one line. Also note that I'm just a visitor and not a contributor. Those who manage the project may have a different opinion on the safe casting.
Just keeping it on separate lines for formatting