Getting Started With WorkManager

Avatar

Jon

If you need to schedule a background task on Android, you’re probably familiar with all of the various ways to accomplish this such as:

  • Google Cloud Messaging
  • Firebase Cloud Messaging
  • DownloadManager
  • Foreground Service
  • Alarm Manager
  • etc

WorkManager

Give a warm welcome to WorkManager. WorkManager is a library that makes it easy to schedule deferrable, asynchronous tasks even if the app exits or the device restarts. It was designed to be backwards compatible to API 14 and does so by wrapping JobScheduler, AlarmManager, and BroadcastReceivers all in one.

Using JobScheduler your app will be running on a device that is API 23+. Anything below, you’ll be using a combination of AlarmManager + BroadcastReceivers.

How is work executed?

Work is fed to an executor to guarantee the work is done.

The executor will complete the work so long as it meets the constraints that you set up when you enqueue the work.

Async by Default

Every operation is asynchronous. Thus you won’t have to worry about threading at all. The operations are saved in a WorkManager database that is the source of truth for any enqueued, successful, or cancelled operations.

When does work end?

  • Upon the work finishing.
  • In the event that the constraints are no longer met (Network could be lost, Phone is no longer plugged in, etc).
  • The OS decided to kill your enqueued work.
  • You cancelled your work.

Lifetime of work

One Time Work

This type of work’s final state is Succeeded when completed. Otherwise it will go into a Failed or Cancelled state.

Periodic Work

This type of work does not have a final state because it has either a finite or infinite amount of iterations. Thus it will continuously enqueue and run.

Getting Started

Installing the NuGet

Using NuGet, install the Xamarin.Android.Arch.Work.Runtime  package into your Android application. Make sure your application is targeting Android Pie (API 28) or greater.

https://www.nuget.org/packages/Xamarin.Android.Arch.Work.Runtime/

Creating a background task

A task is defined using the Worker class. The DoWork() method is ran on a background thread provided by WorkManager.

To create a background task, extend the Worker class and override the DoWork() method. For example, to create a Worker that calculates two numbers, you can do the following:

The Result returned from the DoWork() method informs you whether the task:

  • Finished successfully via Result.Success()
  • Failed gracefully via Result.Failure()
  • Needs another attempt via Result.Retry()

Note: Your worker only knows about the state passed into it by WorkerParameters.

When and how a task should run?

While a Worker defines the work to be done, a WorkRequest defines when and how the work should run. These tasks may be one time or periodic. You can use OneTimeWorkRequest for one time requests, and you can use PeriodicTimeWorkRequest for period time requests.

Here’s how you would build the WorkRequest for our Worker:

Running the task

Once you’ve built the Worker and the WorkRequest, you are ready to enqueue it using WorkManager and the Enqueue() method.

Seeing the task

We can then use adb logcat  to view our task.

Summary

Use WorkManager for your background task needs in Android. The API is straight-forward and friendly to developers. Don’t worry about managing the lifecycle of the device and let WorkManager do the work for you.

GitHub Sample: https://github.com/JonDouglas/WorkManagerSample

Avatar
Jon Douglas

Program Manager, Xamarin.Android

Follow Jon   

9 Comments
Avatar
Ebresafe Oghenevwogaga 2019-04-12 23:04:49
What namespace(s) can we find the WorkManager API?
Avatar
Jameel Iqbal 2019-04-16 19:48:30
Can you please provide example of how to get feedback from Worker process using "Observe"?
Avatar
nathaniel@insight.ly 2019-04-17 10:33:22
If you get a chance to do a followup article, it would be great to compare and contrast WorkManager with the other approaches you mentioned at the beginning of the article. Is WorkManager compelling enough to switch to if you have existing code? Also, how does WorkManager compare to platform neutral approaches using just Mono.
Avatar
Ricardo Costa 2019-04-21 18:20:04
Hello John Douglas, does this WorkManager service have any incompatibility to catch latitude and longitude when the application is removed from the recent app list? When the app is running it works normally however when I close the app using the list of recent applications it stops picking up the positions.
Avatar
Min-Seo Park 2019-04-21 18:34:45
Much easier to work with background tasking. Nice. I ran the sample app provided, but runtime is still not guaranteed because of the Priority Buckets and $DOZE$ the merciless killer. Once the device is left untouched for like 30 minutes, device falls into DOZE mode and yes, the periodic work cycle stops. Pending periodic works are only processed when the time window is available which is "exponential manner". Meaning the period doubles every time it runs(1 hour, 2 hours, 4 hours, 8 hours, another 8 hours for some reason, and boom, complete oblivion). I guess the only option to avoid the struggle(I know the power management is good thing but, still) is yet the Foreground Service + FCM hack.
Avatar
keshavraja27@gmail.com 2019-04-23 21:32:41
Any example of how do I use this in Xamarin Forms?
Avatar
Nguyễn Liêm 2019-04-26 22:44:10
Can use this for Geofence? Anyone have sample implement this for Geofence please give me suggestions! Thank you!
Avatar
Vincent Nwonah 2019-06-04 05:04:39
I am targetting Android Pie and have the nuget installed yet I am getting namespace AndroidX not found. Any Ideas?