android-ktx icon indicating copy to clipboard operation
android-ktx copied to clipboard

Adding extension function for scheduling jobs

Open RamV13 opened this issue 7 years ago • 6 comments

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 Context parameter
  • compile-time enforcement of the Service type upper bound for the class given to the JobInfo.Builder via the ComponentName (also cleaner by avoiding ::class.java)
  • automatic construction of the ComponentName instance
  • lambda with receiver for building the JobInfo
  • automatic system service retrieval as well as build and schedule calls

* code snippet adapted from Google Samples

RamV13 avatar May 23 '18 22:05 RamV13

Shouldn't this be an extension function of Context then?

romtsn avatar May 24 '18 19:05 romtsn

Good point ... fixed

RamV13 avatar May 24 '18 19:05 RamV13

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.

AllanWang avatar May 27 '18 21:05 AllanWang

Fixed

RamV13 avatar May 28 '18 02:05 RamV13

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.

AllanWang avatar May 28 '18 02:05 AllanWang

Just keeping it on separate lines for formatting

RamV13 avatar May 28 '18 03:05 RamV13