住家知识的搬运者

WorkManager初探

2019-04-03  本文已影响0人  洛草为王

1.创建Worker

class DownloadWorker constructor(appContext: Context, params: WorkerParameters) : Worker(appContext, params){

  override fun doWork(): Result {
    val fileUrl = inputData.getString(JSBundleKey.KEY_URL) ?: ""
    if (TextUtils.isEmpty(fileUrl)) return Result.failure()
    LogUtil.d("DownloadWorker", "start download:$fileUrl")

    ServiceGenerator.createService(ADApiService::class.java).downloadFileSync(fileUrl)
        .flatMap { t ->
          val cacheKey = Md5Util.getMD5(fileUrl)
          var videoFile = File(FileUtil.getAppDataDir() + File.separator + cacheKey + ".mp4")
          try {
            FileUtil.writeResponseBodyToDisk(t, videoFile)
            return@flatMap Observable.just(videoFile)
          } catch (e: Exception){
            return@flatMap Observable.error<File>(e)
          }
        }
        .compose(Rx2Schedulers.applyObservableAsync())
        .subscribe(object : SimpleObserver<File>(){

          override fun onNext(t: File) {
            super.onNext(t)
            LogUtil.d("DownloadWorker", "file:" + t.absolutePath)
          }

          override fun onError(e: Throwable) {
            super.onError(e)
          }
        })

    return Result.success()
  }

}

2.向Worker传递数据

  private fun createDate(videoUrl: String) : Data {
    return workDataOf(JSBundleKey.KEY_URL to videoUrl)
  }

3.创建约束条件并执行

val constraints = Constraints.Builder().setRequiredNetworkType(NetworkType.UNMETERED).build()
val downloadWorkRequest = OneTimeWorkRequest.Builder(DownloadWorker::class.java)
                  .setConstraints(constraints)
                  .setInputData(createDate(this)).build()
WorkManager.getInstance().enqueue(downloadWorkRequest)

我这里使用的约束条件是在“连接无限流量的网络”情况下触发。
NetworkType有以下几个选项:

到这里一个简单的worker使用demo就完成了。

上一篇下一篇

猜你喜欢

热点阅读