簡體   English   中英

如何在應用程序被殺死時讓 WorkManager 活着?

[英]How to make WorkManager alive when app is killed?

我正在使用“Coroutine Worker”工作管理器下載文件,當應用程序在后台時下載工作正常但當應用程序被終止時,工作管理器停止工作。

我試圖在無限循環中使用 boolean 變量使其保持活動狀態以使其工作,但效果不佳。


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

    }

嘗試使用 PeriodicWorkRequest,而不是使用 OneTimeWorkRequest,希望它有效。

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 提出了自己的服務,因此在 Work 正在進行時應用程序不太可能被殺死
  • 如果應用程序被終止並且相應的工作停止 - 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()
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM