Getting started with Android workmanager

Work manager provides task scheduling function, and we can mark or name work. Let's use an example to demonstrate how to use workmanager. This article uses kotlin.

Add the following dependencies to the build.gradle file of the application module

dependencies {
    def work_version = "2.5.0"

    // (Java only)
    implementation "androidx.work:work-runtime:$work_version"

    // Kotlin + coroutines
    implementation "androidx.work:work-runtime-ktx:$work_version"

    // optional - RxJava2 support
    implementation "androidx.work:work-rxjava2:$work_version"

    // optional - GCMNetworkManager support
    implementation "androidx.work:work-gcm:$work_version"

    // optional - Test helpers
    androidTestImplementation "androidx.work:work-testing:$work_version"

    // optional - Multiprocess support
    implementation "androidx.work:work-multiprocess:$work_version"
}

After adding dependencies and synchronizing gradle, the next step is to define some work.

The work here is simplified for the convenience of testing. In the actual project, please change it to a specific business code. Create a new uploadworker class and inherit the worker class. Two parameters are required: context, params: workerparameters. In the dowork () method, our specific task runs asynchronously on the background thread provided by workmanager.

class UploadWorker(context: Context,params: WorkerParameters) : Worker(context,params) {
    override fun doWork(): Result {
        for (i in 1..3) {
            Log.d(TAG,"模拟执行任务 ${tags.first()} ${Thread.currentThread()}")
            Thread.sleep(100) // 模拟耗时
        }
        return Result.success()
    }
}

In the dowork () method, we print the current thread information. Let's look at the thread operation later.

After the task is executed, dowork() needs to return a result:

We defined the work class uploadworker earlier. Workmanager can schedule work and make it run. Work can be run periodically or only once in a certain period of time. To run work, the workrequest class and its subclasses are involved.

Here we demonstrate a job that runs only once, using onetimeworkrequest. Create worka as a variable in the activity

private val mWorkA = OneTimeWorkRequest.Builder(UploadWorker::class.java)
        .addTag("workA").build()

Create workb

val workB = OneTimeWorkRequest.Builder(UploadWorker::class.java)
        .addTag("workB").build()

Submit the workrequest to the workmanager using the enqueue method.

Obtain the instance of workmanager and use the workmanager. GetInstance (ApplicationContext) method.

Mworka is a variable

WorkManager.getInstance(applicationContext).enqueue(mWorkA)
// ...

Workb is to create a new object each time, and then hand it over to the workmanager for execution.

val workB = OneTimeWorkRequest.Builder(UploadWorker::class.java)
        .addTag("workB").build()
WorkManager.getInstance(applicationContext).enqueue(workB)

The exact time to execute the worker depends on the constraints used in the workrequest and how the system is optimized. Google has officially designed workmanager to provide the best behavior when constraints are met.

Button a triggers mworka and button B triggers workb. Click buttons a / B respectively

模拟执行任务 workA Thread[pool-2-thread-3,5,main]
模拟执行任务 workA Thread[pool-2-thread-3,main]
点击按钮B Thread[main,main]
模拟执行任务 workB Thread[pool-2-thread-1,main]

Observing the log, it is found that the dowork () method of the work runs asynchronously on the background thread provided by the workmanager. The main thread is [main, main], and the working thread is [pool-2-thread-3, main].

In practice, it is found that when you click button a many times, mworka will only execute for the first time. Click button a later, and mworka will not be executed.

This example introduces how to introduce workmanager, define work (task) and queue up to execute tasks. In terms of usage, it is reminiscent of asynctask.

Other references

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>