Open In App

Android Jetpack – WorkManager with Example

Last Updated : 14 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

WorkManager is an Android Jetpack library that provides a flexible and efficient way to schedule and manage background tasks in your app. It is a powerful and recommended tool for managing background processing in Android applications. With WorkManager, you can schedule asynchronous, deferred, and periodic tasks that need to run even when the app is not in the foreground. WorkManager uses the most appropriate and efficient implementation for each device, depending on the API level, so you don’t have to worry about managing compatibility.

Some of the key features of WorkManager are:

  • WorkManager provides flexible scheduling: WorkManager allows you to schedule work requests that can be run immediately, at a later time, or repeatedly at specific intervals. It also provides you with the flexibility to chain multiple work requests together to create complex workflows. WorkManager uses a combination of foreground and background threads to ensure that work requests are executed efficiently and reliably.
  • WorkManager is backward compatible: WorkManager is backward compatible all the way back to API level 14, which makes it a great option for developers who need to support older versions of Android. It automatically chooses the best implementation for the current API level, such as AlarmManager for API levels before 23, JobScheduler for API levels 23 and 24, and a combination of JobScheduler and Firebase JobDispatcher for API levels 25 and higher.
  • WorkManager supports constraints: WorkManager allows you to specify constraints that must be met before a work request can be executed. Some examples of constraints include network connectivity, battery charging status, and device idle state. Constraints ensure that your work requests run at the appropriate time, and they help to conserve battery life and minimize network usage.
  • WorkManager provides a WorkInfo API: WorkManager provides a WorkInfo API that allows you to query the status of your work requests. You can use this API to check whether a work request is running, succeeded, failed, or canceled. You can also retrieve output data from a completed work request using the WorkInfo API.
  • WorkManager supports different types of work requests: WorkManager supports three different types of work requests:
    • OneTimeWorkRequest: A one-time work request that runs once and then stops.
    • PeriodicWorkRequest: A work request that runs at specific intervals, such as once a day or once an hour. 
    • CoroutineWorker: A type of worker that uses coroutines to perform asynchronous work.

Overall, WorkManager is a powerful tool for managing background processing in your Android app. It provides flexible scheduling, backward compatibility, support for constraints, a WorkInfo API, and different types of work requests to suit your needs.

Example Project

Now let’s take a look at the code. Here is an example of how to use WorkManager in an Android app to schedule a background task that displays a notification.

Add the WorkManager dependency to your app’s build.gradle file:

dependencies {
    def work_version = "2.7.0"
    implementation "androidx.work:work-runtime-ktx:$work_version"
}

Create a class that extends the Worker class and implements the doWork() method. This method will be called by the WorkManager to perform the background task:

Kotlin




package com.example.gfg
  
import android.content.Context
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.work.Worker
import androidx.work.WorkerParameters
  
class NotificationWorker(context: Context, params: WorkerParameters) : Worker(context, params) {
  
    override fun doWork(): Result {
        val notification = NotificationCompat.Builder(applicationContext, "default")
            .setSmallIcon(
                androidx.loader.R.drawable.notification_bg)
            .setContentTitle("Task completed")
            .setContentText("The background task has completed successfully.")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .build()
              
        // Perform the background task here, 
        // such as displaying a notification
        NotificationManagerCompat.from(applicationContext).notify(1, notification)
        return Result.success()
    }
}


Schedule the background task using WorkManager. In this example, we schedule a one-time notification to be displayed 30 minutes from now:

Kotlin




import android.app.NotificationChannel
import android.app.NotificationManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
import androidx.work.WorkRequest
import java.util.concurrent.TimeUnit
  
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        val channel =
            NotificationChannel("default", "Default", NotificationManager.IMPORTANCE_DEFAULT)
        val notificationManager = getSystemService(NotificationManager::class.java)
        notificationManager.createNotificationChannel(channel)
  
        val notificationWorkRequest:WorkRequest = OneTimeWorkRequest.Builder(NotificationWorker::class.java)
            .setInitialDelay(30, TimeUnit.MINUTES)
            .build()
        Log.i("WorkManager",notificationWorkRequest.toString())
  
        // Schedule the WorkRequest with WorkManager
        WorkManager.getInstance(this).enqueue(notificationWorkRequest)
  
    }
}


That’s it! Now, when the delay time has elapsed, the NotificationWorker will be executed by the WorkManager to perform the background task. In this example, the task is to display a notification, but you can replace it with any other background task that your app needs to perform.

Output:

WorkManager output can be even seen in the logcat as below. Here, we can see after 30mins workmanager has been called.

Logcat

Also, in the app inspection, we can see when was work manager called.

App Inspection

We can see that notification has arrived after 30 minutes:

 

Here, you can change the time according to your need. 

Conclusion

To summarize, in this conversation, we discussed WorkManager in Android, which is a powerful tool for managing background processing in your Android app. We talked about its features, including flexible scheduling, backward compatibility, support for constraints, a WorkInfo API, and different types of work requests.

We then discussed a simple task that you can perform using WorkManager, which was to display a notification after a specified delay time. I provided an example code for creating a class that extends the Worker class and implements the doWork() method, creating an instance of the OneTimeWorkRequest class and enqueuing the work request using the WorkManager.getInstance() method. Finally, we discussed modifying the delay time to change when the notification will be displayed.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads