Skip to content

Instantly share code, notes, and snippets.

@sys1yagi
Created June 29, 2018 01:37
Show Gist options
  • Save sys1yagi/13558a44e4f6aa07cdc2e42e7cf97ab6 to your computer and use it in GitHub Desktop.
Save sys1yagi/13558a44e4f6aa07cdc2e42e7cf97ab6 to your computer and use it in GitHub Desktop.
import android.app.IntentService
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.work.Data
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
import androidx.work.Worker
class WorkerService : IntentService("WorkerService") {
override fun onHandleIntent(intent: Intent) {
val clazz = intent.getSerializableExtra(ARGS_CLASS) as Class<out Worker>
val input = intent.getBundleExtra(ARGS_INPUT_DATA)
val job = OneTimeWorkRequest.Builder(clazz)
.setInputData(
Data.Builder().apply {
input.keySet().forEach {
putString(it, input.getString(it))
}
}.build()
)
.build()
WorkManager.getInstance().enqueue(job)
}
companion object {
const val ARGS_CLASS = "class"
const val ARGS_INPUT_DATA = "input_data"
fun createService(context: Context, clazz: Class<out Worker>, stringBundle: Bundle): Intent {
return Intent(context, WorkerService::class.java).apply {
putExtra(ARGS_CLASS, clazz)
putExtra(ARGS_INPUT_DATA, stringBundle)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment