方法doWork()不使用WorkManager调用

时间:2019-03-30 16:47:10

标签: android androidx android-workmanager

我需要将文件从设备上传到我的应用程序。我使用WorkManager在后台进行。

将库从android.arch.work:work-runtime:1.0.0-alpha04更新为androidx.work:work-runtime:2.0.0后,出现了问题。

方法doWork()未调用我的UploadFileTask(workerParams: WorkerParameters) : Worker(Application.getContext(), workerParams)

这是我进行上传的方式:

fun upload(id: String, file: File, params: FileStorage.DocParams?, additionalTag: String): File {
    cancelUploadIfWas(file)
    fileStorage.save(file, params)
    val inputData = Data.Builder().putString(FileTask.PATH_KEY, file.path).build()
    val uploadWork = OneTimeWorkRequest.Builder(UploadFileTask::class.java)
        .addTag(ID_PREFIX + id)
        .addTag(PATH_PREFIX + file.path)
        .addTag(UPLOAD_TAG)
        .addTag(additionalTag)
        .keepResultsForAtLeast(0, TimeUnit.SECONDS)
        .setInputData(inputData)
        .build()

    workManager.enqueue(uploadWork)
    file.uploadStatus.onLoading()
    file.uploadWork=uploadWork
    uploadingFiles.put(ID_PREFIX + id, file)
    workManager.getWorkInfoByIdLiveData(uploadWork.id).observe(this, uploadObserver)
    return file
}

但是我的uploadObserver恰好在State.FAILED之后收到State.ENQUEUED

我做错了什么?

1 个答案:

答案 0 :(得分:0)

已解决

诀窍在于我们必须通过这种方式创建任务:

UploadFileTask(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams)

我们的任务的构造函数必须正确接收两个参数:context: ContextworkerParams: WorkerParameters