你可以这样做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()
)
)
}
}