Skip to content

Instantly share code, notes, and snippets.

@raystatic
Created March 2, 2022 20:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raystatic/cf4e6538ccc20056955a86d955ca8cdd to your computer and use it in GitHub Desktop.
Save raystatic/cf4e6538ccc20056955a86d955ca8cdd to your computer and use it in GitHub Desktop.
private fun startDownloadingFile(
file: File,
success:(String) -> Unit,
failed:(String) -> Unit,
running:() -> Unit
) {
val data = Data.Builder()
data.apply {
putString(FileDownloadWorker.FileParams.KEY_FILE_NAME, file.name)
putString(FileDownloadWorker.FileParams.KEY_FILE_URL, file.url)
putString(FileDownloadWorker.FileParams.KEY_FILE_TYPE, file.type)
}
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresStorageNotLow(true)
.setRequiresBatteryNotLow(true)
.build()
val fileDownloadWorker = OneTimeWorkRequestBuilder<FileDownloadWorker>()
.setConstraints(constraints)
.setInputData(data.build())
.build()
workManager.enqueueUniqueWork(
"oneFileDownloadWork_${System.currentTimeMillis()}",
ExistingWorkPolicy.KEEP,
fileDownloadWorker
)
workManager.getWorkInfoByIdLiveData(fileDownloadWorker.id)
.observe(this){ info->
info?.let {
when (it.state) {
WorkInfo.State.SUCCEEDED -> {
success(it.outputData.getString(FileDownloadWorker.FileParams.KEY_FILE_URI) ?: "")
}
WorkInfo.State.FAILED -> {
failed("Downloading failed!")
}
WorkInfo.State.RUNNING -> {
running()
}
else -> {
failed("Something went wrong")
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment