I need to upload file from device to my app. I use WorkManager to do it in background.
After updating library from android.arch.work:work-runtime:1.0.0-alpha04
to androidx.work:work-runtime:2.0.0
something goes wrong.
Method doWork()
not calling in my UploadFileTask(workerParams: WorkerParameters) : Worker(Application.getContext(), workerParams)
Here is how I run my uploading:
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
}
But my uploadObserver
receives State.FAILED
exactly after State.ENQUEUED
What I'm doing wrong?
Solved
The trick was in that we have to create out task by this way:
UploadFileTask(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams)
The constructor of our task have to receive exactly two parameters: context: Context
and workerParams: WorkerParameters
Explanation:
val downloadWork = OneTimeWorkRequest.Builder(downloadingTask)
.addTag(ID_TAG)
.keepResultsForAtLeast(0, TimeUnit.SECONDS)
.build()
workManager.enqueue(downloadWork)
WorkManager
expects to receive downloadWork
which was biult with downloadingTask
, that has exactly two params in its constructor