Creating a Worker

The Worker class is where you will put the logic you want to perform in the background. Once your worker is in place, you will create a WorkRequest that tells the system when you would like your work to execute.

Before you can add your worker, you first need to add the appropriate dependency in your app/build.gradle file.

Listing 27.1  Adding the WorkManager dependency (app/build.gradle)

dependencies {
    ...
    implementation 'androidx.recyclerview:recyclerview:1.0.0'
    implementation "android.arch.work:work-runtime:1.0.1"
    ...
}

Sync the project to download the dependency.

With your new library in place, move on to creating your Worker. Create a new class called PollWorker that extends the Worker base class. Your PollWorker will need two parameters, a Context and a WorkerParameters object. Both of these will be passed to the superclass constructor. For now, override the doWork() function and log a message to the console.

Listing 27.2  Creating the worker (PollWorker.kt)

private const val TAG = "PollWorker"

class PollWorker(val context: Context, workerParams: WorkerParameters)
    : Worker(context, workerParams) {

    override fun doWork(): Result {
        Log.i(TAG, "Work request triggered")
        return Result.success()
    }
}

The doWork() function is called from a background thread, so you can do any long-running tasks you need to there. The return values for the function indicate the status of your operation. In this case, you return success, since the function just prints a log to the console.

doWork() can return a failure result if the work cannot be completed. In that case, the work request would not run again. It can also return a retry result if a temporary error was encountered and you want the work to run again in the future.

The PollWorker only knows how to execute the background work. You need another component to schedule the work.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.23.101.41