1

有一个

@ExperimentalUnsignedTypes
class SomeNotification : JobService() {
    
    @SuppressLint("CommitPrefEdits")
    override fun onStartJob(params: JobParameters?): Boolean {        
        //..
    }

    override fun onStopJob(params: JobParameters?): Boolean {
        //..
    }
}

我可以在这里使用协程而不是 Jobservice 吗?

我也不明白 JobService 评论:

这意味着您必须将执行逻辑卸载到您选择的 * 另一个线程/处理程序/{@link android.os.AsyncTask}。

4

1 回答 1

-1

你可以这样做WorkManager

def work_version = "2.3.4"

// Kotlin + coroutines
implementation "androidx.work:work-runtime-ktx:$work_version"

CoroutineWorker

class CoroutineDownloadWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {

override suspend fun doWork(): Result = coroutineScope {
    val jobs = (0 until 100).map {
        async {
            downloadSynchronously("https://www.google.com")
        }
    }

    // awaitAll will throw an exception if a download fails, which CoroutineWorker will treat as a failure
    jobs.awaitAll()
    Result.success()
}


private suspend fun showNotification(progress: Int) {
    setForeground(
        ForegroundInfo(
            notificationId,
            NotificationCompat.Builder(appContext, channelId)
                .setContentTitle(appContext.getString(R.string.app_name))
                .setProgress(100, progress, false)
                .setContentText(appContext.getString(R.string.content_text))
                .setAutoCancel(false)
                .setSmallIcon(R.drawable.ic_notification)
                .setColor(ContextCompat.getColor(appContext, R.color.colorPrimary))
                .build()
        )
    )
}
}
于 2020-07-20T11:37:10.827 回答