首页 > 解决方案 > 无法取消在前台运行的定期工作请求

问题描述

我有一个定期的工作请求在前台运行。使用以下版本WorkManager

androidx.work:work-runtime-ktx:2.5.0-alpha03 

这是工作要求。

val workRequest = PeriodicWorkRequestBuilder<MyWorker>(15, TimeUnit.MINUTES)
                   setConstraints(constraints).build()

在工人阶级上,我将其设置为前景。

class MyWorker(context, params) : CoroutineWorker(context, params) {
    override suspend fun doWork(): Result {
         setForeground(createForegroundInfo())

         //rest of the logic
    }

    private void createForegroundInfo() {
       val cancelIntent = WorkManager.getInstance(context).createCancelPendingIntent(id) //work request id
       val notification = NotificationCompat.Builder(context, channelId)
                      .setContentTitle("Test Title")
                     .addAction(actionIconRes, "Cancel", cancelIntent).build()
       return ForegroundInfo(notificationId, notification)
    
    }
}

当我运行它时,我可以看到带有取消操作的通知。单击后,通知会暂时消失并再次出现。进一步点击取消操作没有任何反应。也没有任何取消信号。什么可能是一个障碍?有什么线索吗?

标签: androidandroid-notificationsandroid-pendingintentandroid-workmanager

解决方案


我想我找到了问题所在。我嵌套了导致Worker完全取消的挂起函数。现在我已经更改了这些功能,现在一切正常。


推荐阅读