DEV Community

Cover image for WorkManager
Li_jin_Admin
Li_jin_Admin

Posted on

WorkManager

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 'androidx.work:work-runtime-ktx:2.5.0-alpha01'
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")
        Thread.sleep(3000)
        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?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        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
                    .build()
            // 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
                    .build()
            workerManager.enqueue(workRequest)   // Add a task queue
            workerManager.getWorkInfoByIdLiveData(workRequest.id).observe(this, Observer {
                if(it.state == WorkInfo.State.SUCCEEDED){
                    Log.d("TAG", " ${it.outputData.getString(KEY)}")
                }
            })
        }

    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)