Search code examples
androidandroid-workmanager

Schedule WorkManager worker from a notification action


The android documentation shows how to schedule a WorkManager Worker programmatically like so:

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

WorkManager.getInstance().enqueue(uploadWorkRequest)

But how are you supposed to schedule it once a user clicks a notification action?

For example, this is the code to start an IntentService when a user clicks on a notification action:

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)

But instead of an IntentService how are you supposed to enqueue a WorkManager Worker when user clicks on the same notification action?


Solution

  • IntentService is deprecated starting with API level 30:

    "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

    SOLUTION: Simply create a standard service, associate it with your PendingIntent and start the WorkManager within the service's onStartCommand-Method.