Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 945
Suyash Avatar asked Sep 01 '25 11:09

Suyash


2 Answers

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.

like image 108
d-reic Avatar answered Sep 04 '25 00:09

d-reic


IntentService has been deprecated. Please check the other answer.

For anyone wondering how I solved this, I created an extra IntentService for scheduling different workers.

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) {
        // ...
    }
}
like image 25
Suyash Avatar answered Sep 04 '25 00:09

Suyash