当触发通知的取消操作时,是否可以取消在 doWork()
中完成的工作?
class TestWorker(context: Context, parameters: WorkerParameters) :
CoroutineWorker(context, parameters) {
override suspend fun doWork(): Result {
setForeground(createForegroundInfo())
doStuff()
return Result.success()
}
private fun doStuff() {
for (i in 0..10) {
Log.d(LOG, "Can this be interrupted?")
Thread.sleep(1000)
}
}
private fun createForegroundInfo(): ForegroundInfo {
val cancelIntent = WorkManager.getInstance(applicationContext)
.createCancelPendingIntent(id)
val notification = NotificationCompat.Builder(applicationContext, CHANNEL_ID)
...
.addAction(android.R.drawable.ic_delete, "cancel", cancelIntent)
.build()
createChannelIfNeeded()
return ForegroundInfo(1, notification)
}
最佳答案
Thread.sleep(1000)
不可被协程中断。如果您使用delay(1000)
,那么它将按照 this blog post 被中断。 .
private suspend fun doStuff() {
for (i in 0..10) {
Log.d(LOG, "Can this be interrupted?")
delay(1000)
}
}
关于android - 协程 worker : interrupt doWork() on cancelPendingIntent action,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62050518/