CoroutineWorker:在cancelPendingIntent操作上中断doWork()

问题描述 投票:0回答:1

当触发通知中的取消动作时,是否可以取消在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)
    }

android android-workmanager
1个回答
0
投票

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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.