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.gradleimplementation'androidx.work:work-runtime-ktx:2.5.0-alpha01'
// 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 ResultclassMyWorker(context:Context,workerParams:WorkerParameters):Worker(context,workerParams){overridefundoWork():Result{// val name = inputData.getString(KEY) // Retrieve the data passed in the taskLog.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))returnResult.success()}}
Used in MainActivity
classMainActivity:AppCompatActivity(){// Add a single example of WorkerManager to pass the contextprivatevalworkerManager=WorkManager.getInstance(this)overridefunonCreate(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)valconstraints=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 > createdvalworkRequest=OneTimeWorkRequestBuilder<MyWorker>().setConstraints(constraints)// Add execution criteria (constraints of the previous section of code).setInputData(workDataOf(KETtovalue))// Pass data to the Created Work class.build()workerManager.enqueue(workRequest)// Add a task queueworkerManager.getWorkInfoByIdLiveData(workRequest.id).observe(this,Observer{if(it.state==WorkInfo.State.SUCCEEDED){Log.d("TAG"," ${it.outputData.getString(KEY)}")}})}}}
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)