从通知操作安排 WorkManager worker

Schedule WorkManager worker from a notification action

android 文档展示了如何以编程方式安排 WorkManager Worker

val uploadWorkRequest = OneTimeWorkRequestBuilder<UploadWorker>()
        .build()

WorkManager.getInstance().enqueue(uploadWorkRequest)

但是一旦用户单击通知操作,您应该如何安排它?

例如,这是在用户单击通知操作时启动 IntentService 的代码:

class ApiCallService : IntentService("ApiCallService") {
   // ...
}

val notificationBuilder = NotificationCompat.Builder(context,
            NOTIFICATION_CHANNEL_ID)

val saveIntent = Intent(context, ApiCallService::class.java)
val savePendingIntent = PendingIntent.getBroadcast(context,
                0, saveIntent, 0)

notificationBuilder.addAction(R.drawable.ic_done_white_24dp,
                context.getString(R.string.save),
                savePendingIntent)

但是当用户点击相同的通知操作时,您应该如何将 WorkManager Worker 加入队列而不是 IntentService

如果有人想知道我是如何解决这个问题的,我创建了一个额外的 IntentService 来安排不同的工作人员。

class WorkManagerService : IntentService("WorkManagerService") {
    override fun onHandleIntent(intent: Intent?) {
        when (intent?.action) {
            ACTION_SCHEDULE_WORKER1 -> {
                scheduleWorker1(intent)
            },
            ACTION_SCHEDULE_WORKER2 -> {
                scheduleWorker2(intent)
            }
        }
    }

    private fun scheduleWorker1(intent: Intent) {
        // ...

        val worker1 = OneTimeWorkRequestBuilder<Worker1>()
                .setConstraints(networkConstraint)
                .setInputData(workData)
                .build()

        WorkManager.getInstance().enqueue(worker1)
    }

    private fun scheduleWorker2(intent: Intent) {
        // ...
    }
}

从 API 级别 30 开始弃用 IntentService:

"IntentService is subject to all the background execution limits imposed with Android 8.0 (API level 26). Consider using WorkManager or JobIntentService, which uses jobs instead of services when running on Android 8.0 or higher." https://developer.android.com/reference/android/app/IntentService

解决方案:只需创建一个标准服务,将其与您的 PendingIntent 相关联,然后在该服务的 onStartCommand-Method 中启动 WorkManager。