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   

13 comments

  • Avatar
    nathaniel@insight.ly

    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

    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

    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.

  • Adriano José Santana
    Adriano José Santana

    Hi,

    I create a class ServiceWorker,he execute when application start, but dont execute in time i determinate ( 1 minute ).

    What a doing wrong ?

    Thanks.

Leave a comment