我使用“协程工作程序”下载文件。当应用在后台时,下载工作正常进行;但当应用被关闭时,工作管理器停止工作。
我尝试使用布尔变量在一个无限循环中使其保持运行以使其工作,但这也没有起作用。
我尝试使用布尔变量在一个无限循环中使其保持运行以使其工作,但这也没有起作用。
class UploadWorker(
private val appContext: Context,
workerParams: WorkerParameters
) : CoroutineWorker(appContext, workerParams) {
private var isDownloadCompleted = false
override suspend fun doWork(): Result {
val filName = inputData.getString("filName") ?: ""
val url = inputData.getString("URL") ?: ""
/*when file is downloaded, I change the status of the boolean to true, so it break the
loop*/
//Loop break when download file is completed, occur error, or pause.
while (!isDownloadCompleted) {
Log.e("tag**", "downloaded file $isDownloadCompleted")
}
// Indicate whether the work finished successfully with the Result
return Result.success()
}
}
val imageData = workDataOf("URL" to url, "filName" to filName)
val constraints = Constraints.Builder()
.setRequiresBatteryNotLow(false)
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresStorageNotLow(false)
.build()
Log.e("tag**", "createReq")
val uploadWorkRequest: WorkRequest =
OneTimeWorkRequestBuilder<UploadWorker>()
.setInputData(imageData)
.setConstraints(constraints)
.setInitialDelay(0, TimeUnit.SECONDS)
.setBackoffCriteria(
BackoffPolicy.LINEAR,
OneTimeWorkRequest.MIN_BACKOFF_MILLIS,
TimeUnit.MILLISECONDS
)
.build()
我希望即使应用程序被杀死或在后台运行,它也能正常工作。