Open In App

Overview of WorkManager in Android Architecture Components

Improve
Improve
Like Article
Like
Save
Share
Report

Android WorkManager could be thought of as a  backgrounding library that is employed to execute background tasks that should run in a guaranteed way but not necessarily immediately. With WorkManager we’ll enqueue our backgrounding even when the app isn’t running and even when the device is rebooted for a couple of reasons. WorkManager also lets us define constraints necessary to run the task e.g. Wi-Fi. or battery availability before starting the background task. 

Android WorkManager is one of the parts of Android Jetpack (a suite of libraries to guide developers to write down great quality apps) and is one among the Android Architecture Components (collection of components that help developers design robust, testable, and simply maintainable apps).

When to Use WorkManager while Working with Background Processing?

As the Android OS evolved greatly over the years, there are certain restrictions placed on backgrounding the processes, it all is been done so as to optimize battery consumption and make use of device resources in an optimal and judicious way. Each new Android release, ranging from android marshmallow (API 23), has added some restrictions and they continue to come till way. You can examine the precise details on an equivalent within the Android developer guide. Thus, it’s important to settle on the simplest backgrounding approach for your app per your needs. Let’s quickly mention cases once you would prefer to use WorkManager. Android WorkManager is often an ideal backgrounding library to use when your task:

  1. Doesn’t get to run at a selected time
  2. Can be deferred to be executed
  3. Is bound to run even after the app is killed or the device is restarted or permanently shut down
  4. Has got to meet constraints like network coverage or network availability before execution

The simplest example for this can be when your app needs to upload a large chunk of user data onto the server. This requires the developers to reside and use the WorkManager as it’s the perfect thing that is required!

But Why?

  1. Results needn’t be reflected immediately in your Android app (slight delay is allowed)
  2. Data must be uploaded even when the upload begins and therefore the user kills the app to figure on another app or decides to keep the phone to rest, and
  3. The network and battery must be available so as to upload data on the server.

Step #1: Add Work Manager to Android build.gradle

Adding work manager is simple, just include the following lines in your project level and you’re good to roll!

Java




dependencies
{
    def work_version = "2.5.0"
 
        // (Java only)
        implementation "androidx.work:work-runtime:$work_version"
 
        // Kotlin + coroutines
        implementation "androidx.work:work-runtime-ktx:$work_version"
 
        // optional - RxJava2 support
        implementation "androidx.work:work-rxjava2:$work_version"
 
        // optional - GCMNetworkManager support
        implementation "androidx.work:work-gcm:$work_version"
 
        // optional - Test helpers
        androidTestImplementation "androidx.work:work-testing:$work_version"
 
        // optional - Multiprocess support
        implementation "androidx.work:work-multiprocess:$work_version"
}


Step #2: Defining The Work

We need to create some work like mentioned in the example above, and then we will need to extend the Worker class by overriding the doSomeWork() method. The below given example shows how to add a Worker to the Android App that uploads data (primarily Images) to a server.

Java




public class WorkManagerOverviewGfg extends Worker {
    public WorkManagerOverviewGfg(@NonNull Context context,
                                  @NonNull WorkerParameters params)
    {
        super(context, params);
    }
    @Override public Result doSomeWork()
    {
 
        // Do the work here--in this case, upload the data.
        uploadData();
        return Result.success();
    }
}


 
The Result method mentioned above (returned from the Code) tells the system service whether the specified job/work went alright or not. If it returns fail, then it also gives the method to retry the work or not

Step #3: Creating a WorkRequest

Once that you have defined your work, you must now schedule it using the WorkManager service, so as to make the service run. You can also schedule it to run programmatically over an interval or multiple times, or make it run only once! The below code snippet guides you on how to build a service that runs your job only once!

Java




WorkRequest uploadRequestGfg = new OneTimeWorkRequest.Builder(WorkManagerOverviewGfg.class).build();


Finally, Step #4: Submitting the WorkRequest to the system to be carried out

After you have successfully crafted a WorkRequest the final step which is needed to be done is to submit the created WorkRequest to WorkManager using the enqueue method(), and then just see your job is performed using the WorkManager. The below code snippet guides you through the required steps to get this final step done

Java




WorkManager.getInstance(getContext).enqueue(uploadRequestGfg);


 That’s it! You’ve done it!

Now sit back and hold tight, the exact time the worker will take will include all the steps and constraints you’ve put in your WorkRequest and the system state at the moment.

 



Last Updated : 30 Dec, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads