WorkManager初探

作者: 洛草为王 | 来源:发表于2019-04-03 10:21 被阅读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有以下几个选项:

    • NOT_REQUIRED 没要求
    • CONNECTED 网络连接
    • UNMETERED 连接无限流量的网络
    • METERED 连接按流量计费的网络
    • NOT_ROAMING 连接非漫游网络

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

    相关文章

      网友评论

        本文标题:WorkManager初探

        本文链接:https://www.haomeiwen.com/subject/jfhabqtx.html