DEV Community

Cover image for WorkManager

Posted on


WorkManager can invoke deferred asynchronous tasks that should still run when the device restarts or when the app exits. Methods can also be called when the program is exited or the device is shut down and restarted.
// Import WorkManager dependencies in build.gradle
implementation ''
Enter fullscreen mode Exit fullscreen mode
// The new class class inherits the Worker class with the parameters context, workerParams
// Override the doWork method and add the logic to be executed to Result
class MyWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
    override fun doWork(): Result {
        // val name = inputData.getString(KEY)    // Retrieve the data passed in the task
        Log.d("TAG", "doWork: $name start")
        Log.d("TAG", "doWork: $name finish")
        // The outputData return value can be added in the success, and the return value type is Pair (KEY, value)
        // return Result.success(workDataOf(Pair(key,value)))
        // Success can also be in to form
        // return Result.success(workDataOf(KEY to value))
        return Result.success()
Enter fullscreen mode Exit fullscreen mode
Used in MainActivity
class MainActivity : AppCompatActivity() {
    // Add a single example of WorkerManager to pass the context
    private val workerManager = WorkManager.getInstance(this)
    override fun onCreate(savedInstanceState: Bundle?) {
        button.setOnClickListener {
            // Add a task condition (this condition is a hook when the network is connected)
            val constraints = Constraints.Builder()
                    .setRequiredNetworkType(NetworkType.CONNECTED)  // When the network type is connected
            // Add cascading tasks (multitasking) demos:
            // workerManager.beginWith(workA).then(workB).then(workC).enqueue
            // Add a single job request OneTimeWorkRequestBuilder < type: The Work class > created
            val workRequest = OneTimeWorkRequestBuilder<MyWorker>()
                    .setConstraints(constraints) // Add execution criteria (constraints of the previous section of code)
                    .setInputData(workDataOf(KET to value))  // Pass data to the Created Work class
            workerManager.enqueue(workRequest)   // Add a task queue
            workerManager.getWorkInfoByIdLiveData(, Observer {
                if(it.state == WorkInfo.State.SUCCEEDED){
                    Log.d("TAG", " ${it.outputData.getString(KEY)}")

Enter fullscreen mode Exit fullscreen mode

Top comments (0)