About using WorkManager

About using WorkManager

Kotlin is the main language

introduce

WorkManager is a background execution task management, which can continue to execute the created task even after the application exits. You can also add trigger conditions for WorkManager. Of course, there are special cases. When the application is completely killed, the task will not be triggered. It will wait until the next application is opened, and then trigger the task

  1. Add dependency

    • Open the ProjecySturcture of the current project

    • In dependencies Click + in the app to add dependencies, and then search for Android X work

    • Select the end of ktx, click ok, and wait for the download to complete

  2. Next, create a class MyWorker to inherit Worker

    class MyWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
        override fun doWork(): Result {
            Log.e("work", "doWork:  Task start" )
            Thread.sleep(3000)
            Log.e("work", "doWork:  End of task" )
            return Result.success()
        }
    }
    

    Inheriting workers requires parameters to be passed in, so you need to create a construction method. Here, in order to facilitate observation, the log is printed

  3. Then create the variable workMananger in the Activity, and create the workRequest and pass it in

    class MainActivity : AppCompatActivity() {
        private val workManager = WorkManager.getInstance(this)
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            //Here, a Button is created in the XML and the click event is set for it
            button.setOnClickListener {
                val wrokRequest = OneTimeWorkRequestBuilder<MyWorker>()
                .build()
                workManager.enqueue(wrokRequest)
                //Pass the created workRequest to the workManager
            }
        }
    }
    

    Above, the simple use of workManager is completed

Trigger conditions of WorkManager, data transmission and serial connection

Trigger condition
  val constraints = Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .build()
 val wrokRequest = OneTimeWorkRequestBuilder<MyWorker>()
            .setConstraints(constraints)
            .build()

Create a constraint and set the trigger condition to trigger when connecting to the network, and then pass it to workRequest

Constraints is used to set trigger conditions. After setting trigger conditions, a wrokRequest can be passed. Then, as long as the specified conditions are met, the Wroker will trigger

Transfer data

The data can be transferred into the Worker, and the Worker can also transfer the data out

val wrokRequest = OneTimeWorkRequestBuilder<MyWorker>()
			//Trigger condition
            .setConstraints(constraints)
			//Transfer data into Worker
            .setInputData(workDataOf(INTPUT_WORK_KEY to data))
            .build()

Data is transferred through setInputData, which accepts a workData parameter. workData is a key value pair, and finally accepts data in the Worker

class MyWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
    override fun doWork(): Result {
        //Get the data passed in through inputData
        val data = inputData.getString("Key")
        //You can also use result Success is used to transfer data. Of course, it is also of workData type
        return Result.success(workDataOf(OUT_WORK_KEY to "The task has ended"))
    }
}

Data can be received through inputData, and can be passed out through return Success. Data can be obtained through LiveData observation in Activity/Fragment

workManage.getWorkInfoByIdLiveData(workRequestA.id).observe(this, Observer {
                Toast.makeText(this, "When the task is completed, the returned data is ${it.outputData}", Toast.LENGTH_SHORT).show()
            })
Serial connection

First, we extract the contents of creating trigger condition and creating workRequest (shortcut key: ctrl+alt+m)

private fun createWork(data: String): OneTimeWorkRequest {
        val constraints = Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .build()
        return OneTimeWorkRequestBuilder<MyWorker>()
            .setConstraints(constraints)
            .setInputData(workDataOf(INTPUT_WORK_KEY to data))
            .build()
    }

And pass in a parameter to this method to transfer data with the Worker, and then use

  private val WORK_A_DATA = "A ni shi han han"
  private val WORK_B_DATA = "B ni shi han han"

  val workRequestA = createWork(WORK_A_DATA)
  val workRequestB = createWork(WORK_B_DATA)
      workManager.beginWith(workRequestA)
          .then(workRequestB)
          .enqueue()

Then you can use workmanager beginWith() connects two worker s in series. beginWith() is the first workRequest passed in, and the rest is passed through then. Finally, don't forget to call enqueue()

Keywords: Android kotlin

Added by Dane on Sat, 05 Mar 2022 02:21:41 +0200