WorkManager

Posted by OOFTF Blog on April 23, 2021

WorkManager

调度在退出应用或重启设备后仍应运行的可延期异步任务

使用底层作业来调度服务

workmanager

示例

  1. 创建一个Worker ```kotlin class UploadWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) { override fun doWork(): Result { inputData.getString(“data”) if(){ Result.success() }else if(){ Result.retry() }else{ Result.failure() }

    1
    
    } } ```kotlin
    
  2. 执行Worker

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
     val data = Data.Builder()
                .putString("data", jsonParser.object2Json(request))
                .build()
     val uploadWorkRequest: WorkRequest =
         OneTimeWorkRequestBuilder<UploadWorker>()
             .setInputData(data)
             .build()
     WorkManager
         .getInstance(AppHolder.app)
         .enqueue(uploadWorkRequest)