Site icon Android Tutorial Online

Performing Background Jobs with WorkManager and Coroutines

WorkManager

Usage

Scheduling Background Tasks

  1. AlarmManager : Schedule work to repeat at specified intervaks.
  2. Async Task : The API for Async Task comes with a sleep learning curve.
  3. Job Scheduler : Fixes some of the issues of the AlarmManager in AsyncTask , and adds new feature.

Using WorkManager

  1. Describe the Work (background Task) to be done
  2. Create a Work request to define the conditions of the work.
  3. You ‘ll need an instance of a WorkManager to schedule the work request

Example

Worker.kt

class MyWorker: Worker {
override fun doWork(): Result {
// do the work!
/**
 val data = inputData.getString("KEY")
**/
return Result.success()
 }
}  

MainActivity.kt

class MainActivity : AppCompatActivity() {
  // The Instance of the WorkManager is a singleTon pattern that exists for the Life Cycle of the App.
  val workManager = WorkManager
    .getInstance(this)
    
  fun startWork() {
  /**
     val data = Data.Builder(...)
     .build()
  **/   
     val workRequest = OneTimeWorkRequest
       .Builder(...)
       .setInputData(data)
       .build()
    workManager.enqueue(workRequest)
    }
}

More Details

GitHub

View Github

Exit mobile version