当应用程序被杀死时,如何让WorkManager活着



我正在下载带有"Coroutine Worker";工作管理器,当应用程序处于后台时,下载工作正常,但当应用程序被终止时,工作管理器停止工作。

我试图在一个无限循环中使用一个布尔变量来保持它的活力,以使它发挥作用,但效果不佳。


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()

我想让它工作,无论应用程序是杀死还是在后台。

检查这是否对您有帮助->

Kotlin->


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()
}
}

不要使用OneTimeWorkRequest,试着使用PeriodicWorkRequest,希望它能起作用。

val imageData = workDataOf("URL" to url, "filName" to filName)
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresBatteryNotLow(false)
.setRequiresStorageNotLow(false)
.build()
Log.e("tag**", "createReq")
val uploadWorkRequest: WorkRequest =
PeriodicWorkRequestBuilder<UploadWorker>(2, TimeUnit.HOURS)
.setInputData(imageData)
.setConstraints(constraints)
.setInitialDelay(0, TimeUnit.SECONDS)
.setBackoffCriteria(
BackoffPolicy.LINEAR,
OneTimeWorkRequest.MIN_BACKOFF_MILLIS,
TimeUnit.MILLISECONDS
)
.build()

如果应用程序被终止,WorkManager不会工作。如果应用程序被杀,它就死了。就是这样。WorkManager确保的是:

  • 在工作进行时,应用程序不太可能被终止,因为WorkManager提出了自己的服务
  • 如果应用程序被终止,并且一项工作分别被停止,WM将确保该工作将在稍后阶段恢复,并且在满足限制的某个时刻肯定会完成

一切都很好,但我忘了附上工作经理的通知。

class UploadWorker(
private val appContext: Context,
workerParams: WorkerParameters
) : CoroutineWorker(appContext, workerParams) {
private var isDownloadCompleted = false

override suspend fun doWork(): Result {
notification = NotificationCompat.Builder(
applicationContext,
appContext.getString(R.string.channel_name)
)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setContentText("0MB/ $fileSize")
.setOnlyAlertOnce(true)
.setProgress(100, 0, false)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setOngoing(true)
.setAutoCancel(false)
.setDefaults(NotificationCompat.DEFAULT_ALL)


val filName = inputData.getString("filName") ?: ""
val url = inputData.getString("URL") ?: ""
//attach your notification, so workmanager will be killed
setForegroundAsync(ForegroundInfo(id, notification.build()))
/*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()
}
}

由于您使用的是oneTimeWorkRequest,请在构建工作请求时尝试使用setExpediated(true(。

注意:不能为定期工作请求设置setExpediated(true(。

最新更新