Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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