Tag Archives: workmanager

MAD Skills WorkManager : Wrap-Up

Posted by Caren Chang, Developer Relations Engineer

In case you missed it, we’ve just finished a MAD Skills series on WorkManager. We started by introducing WorkManager for those new to the library and then proceeded to talk more about advanced usages including how to test and debug your WorkManager code. The series ended with an episode on how to migrate your old code from GCMNetworkManager and FirebaseJobDispatcher to use WorkManager instead.

Here’s a quick summary of what we covered.

Episode 1: WorkManager: Basics

In our first episode, we explored the basics of WorkManager through the WorkManager codelab. We started by understanding how to define work we want done, and how to schedule the work. We then moved on to implementing different types of work: unique and periodic. Finally, we ended the episode by taking a look at app standby buckets to better understand how WorkManager schedules work.

If you’re new to WorkManager, we also recommend taking a look at the following articles:

Episode 2: WorkManager: Working in the background

The series continued with Ben giving a more in-depth look at how WorkManager deals with multi-threading. When working with threads, you have the option of using Executors, coroutines or RxJava, and Ben demonstrated each of these approaches with WorkManager. The episode concluded by demonstrating how to return a result when the work is completed so that the UI can be updated.

If you’re interested in using WorkManager with coroutines, we also recommend this article from Florina: WorkManager - Kotlin APIs

Episode 3: WorkManager: Advanced configuration and testing

In episode 3, we took a look at how to customize the initialization of WorkManager and support apps that span multiple processes. We’ve gotten a lot of questions from developers around testing and debugging, so Ben also dove into how to test your Workers, and useful debugging techniques.

Episode 4: Migrating from GCM NetworkManager and FirebaseJobDispatcher to WorkManager

In episode 4, we focused on how to migrate from old job scheduling libraries (GCMNetworkManager and FirebaseJobDispatcher) to WorkManager. Once your app starts targeting API level 30 and above, GCM NetworkManager and FirebaseJobDispatcher will no longer work on devices running Android Marshmallow (6.0) and above. If your app is still using either of those libraries, now is the time to update your apps to use WorkManager instead!

Episode 5: WorkManager with Hugo

Android GDE Hugo Visser talked about why he chose to use WorkManager in a health app he recently worked on and how the library has helped his development process.

Episode 6: Live Q&A

The series wrapped up with a live Q&A session where we answered your WorkManager related questions. Watch the recording to see all your questions answered, including future plans for WorkManager, handling duplicate work, retrying failed work, and more!

Unifying Background Task Scheduling on Android

Posted by Caren Chang, Developer Programs Engineer

Android users care a lot about the battery life on their phones. In particular, how your app schedules deferrable background tasks play an important role in battery life. To help you build more battery-friendly apps, we introduced WorkManager as the unified solution for all deferrable background processing needs.

Starting November 1, 2020, we are unifying deferrable background tasks on Android around WorkManager, and GCMNetworkManager will be deprecated and no longer supported.

Why WorkManager

The WorkManager API incorporates the features of Firebase Job Dispatcher (FJD) and GcmNetworkManager solutions, providing a consistent job scheduling service back to API level 14 while being conscious of battery life. For example, if your app needs to send log files up to the server, it would be more efficient to wait until the device is both charging and connected to WiFi. In this case, WorkManager will ensure that the sync will execute when the given constraints (charging and connected to WiFi) are met. Additionally, it does not require Google Play Services, unlike FJD and GcmNetworkManager.

Some of the other key features of WorkManager include:

  • Persist scheduled work across app updates and device restarts
  • Schedule one-off or periodic tasks
  • Monitor and manage tasks
  • Chain tasks together

What it means for developers

Now that the WorkManager library has reached maturity, we have decided to deprecate alternative solutions to simplify the developer story and focus on WorkManager stability and features.

  • We announced the deprecation of the FirebaseJobDispatcher library in April 2019. In April 2020 the library will be archived and we will no longer provide support for issues filed on the library.
  • In addition, we are now announcing the deprecation of GCMNetworkManager. The library is no longer receiving any new features and starting in November 2020, we will no longer provide support for issues relating to the library.
  • Furthermore, once your app updates the target API level (targetSdkVersion) to above Android 10 (API level 29), FirebaseJobDispatcher and GcmNetworkManager API calls will no longer work on devices running Android Marshmallow (6.0) and above.

Migrating to WorkManager

Now is the time to migrate your apps to WorkManager if you haven't already done so! You can start by reading the official documentation for WorkManager.

If your app is still using FirebaseJobDispatcher, you can migrate your app to WorkManager by following the migration guide. A similar migration guide from GCMNetworkManager to WorkManager is also available.

YouTube recently moved over to WorkManager for their background scheduling needs and has reported improvements in app startup time as well as an 8% drop in crash rates.

Going forward

The team is dedicated to improving and continuing feature development on WorkManager. If you encounter issues using the library, have proposals for features you would like to see, or have any feedback about the library, please file an issue.

Android Jetpack WorkManager Stable Release

Posted by Sumir Kataria, Software Engineering Lead & Jisha Abubaker, Product Manager

Simplify how you manage background work with WorkManager

Today, we're happy to announce the release of Android Jetpack WorkManager 1.0 Stable. We want to thank so many of you in our dev community who have given us feedback and logged bugs along the way - we've gotten here thanks to your help!

When we looked at the top problems faced by developers, we saw that doing background processing reliably and in a battery-friendly manner was a huge challenge. This meant that periodically fetching fresh content or uploading your logs was complex. Different versions of Android provided different tools for the job, each with their own API quirks. For example, listening for network or storage availability and automatically retrying your tasks involved a lot of work.

Our answer to these challenges was WorkManager. We introduced a preview of the Android Jetpack WorkManager library at Google I/O 2018 and have since iterated on it with additional features and bug fixes thanks to your valuable input.

The goal of WorkManager is to make background operations easy for you. WorkManager takes into account constraints like battery-optimization, storage, or network availability, and it only runs its tasks when the appropriate conditions are met. It also knows when to retry or reschedule your work--even if your device or app restarts.

We believe WorkManager is a friendly, approachable API that can take care of one of the most complex parts of Android for you so you can focus on the code that makes your app unique.

WorkManager Highlights

Here are some key features of WorkManager:

  • Lets you set constraints, such as network status or charge state, on when the task runs
  • Supports asynchronous one-off and periodic tasks
  • Supports chained tasks with input & output
  • Ensures task execution, even if the app or device restarts
  • Supports Android 4.0+ (API 14+)

Watch and read below to learn when and how to use WorkManager to simplify managing background work in your apps:

When to use WorkManager

WorkManager is best suited for tasks that can be deferred, but are still expected to run even if the application or device restarts (for example, syncing data periodically with a backend service and uploading logs or analytics data).

For tasks like sending an instant message that are required to run immediately or for tasks that are not required to run after the app exits, take a look at our background processing guide to learn which solution meets your needs.

How to use WorkManager

To get started with the WorkManager API, add the WorkManager dependency available on Google's Maven repository in Java or Kotlin to your application's build.gradle file:

dependencies {
    def work_version = 1.0.0

    // Java
    implementation "android.arch.work:work-runtime:$work_version"

    // Kotlin KTX + coroutines
    implementation "android.arch.work:work-runtime-ktx:$work_version"
  }

Now, simply subclass a Worker and implement your background work with doWork() and enqueue it with WorkManager.

class MyWorker(ctx: Context, params: WorkerParameters)
  : Worker(ctx, params) {
  override fun WorkerResult doWork() {
    //do the work you want done in the background here
    return Result.success()
  }
}

// optionally, add constraints like power, network availability
val constraints: Constraints = Constraints.Builder()
     .setRequiresCharging(true)
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .build()

val myWork = OneTimeWorkRequestBuilder<MyWorker>()
                .setConstraints(constraints).build()

// Now, enqueue your work
WorkManager.getInstance().enqueue(myWork)

WorkManager will now take care of running your task when it detects that your device is charging and the network is available.

Why use WorkManager

Backward compatibility

WorkManager will leverage the right scheduling API under the hood: it uses JobScheduler API on Android 6.0+ (API 23+) and a combination of AlarmManager and BroadcastReceiver on previous versions.

It also seeks to ensure the best possible behavior so that it complies with system optimizations introduced in newer Android API versions to maximize battery and enforce good app behavior.

For example, WorkManager will schedule background work during the maintenance window for Android 6.0+ (API 23+) devices when the system is in Doze mode.

Reliable scheduling

With WorkManager, you can easily add constraints like network availability or charging status. Your work will run when the constraints are met and automatically retried if they fail while running. For example, if your task requires network to be available, the task will be stopped when network is no longer available and retried later.

You can also monitor work status and retrieve work result using LiveData. This allows your UI to be notified when your task is completed.

In the event that your work fails, you can control how your work is retried by configuring how backoff is handled.

WorkManager is also able to reschedule your work, using a record of your work in its local database, if an application or device restart occurs.

Control over how your work is run

We understand that each app has unique needs, and so do your tasks--even within the same app. WorkManager provides a simple yet highly flexible API surface to help configure your work and how it is run.

Take advantage of one-off scheduling with OneTimeWorkRequest or recurrent scheduling with PeriodicWorkRequest.

You can also chain your one time work requests to run in order or in parallel. If any work in the chain fails, WorkManager seeks to ensure that the remaining chain of work will not run. Read more about chaining work requests here.

If you require more flexibility over how WorkManager parallelizes and manages work, check out our advanced threading guide.

What developers have to say

redBus, the largest online bus ticketing platform, shares their experience using WorkManager to simplify how they collect user feedback in their Android app:

"Feedback is critical to redBus as we expand into other countries. It often happens that a user gives critical feedback about a functionality within the redBus app but when the app tries to upload the feedback to backend servers, there might not be enough network coverage or battery.
WorkManager has simplified the way redBus app delivers information to it's backend servers. WorkManager library's capability to handle parameters like network connectivity, battery and use appropriate handlers like AlarmManager or JobScheduler has enabled us to concentrate on building business logics and offloading execution complexity to WorkManager."

- Dinesh Shanmugam

Android Lead, redBus.in

Get started with WorkManager

Check out our getting started guide and hands-on codelab to start using the WorkManager library for your background task needs.

We appreciate your feedback, including features you like and features you would like to see.

If you find a bug or issue, feel free to file an issue.

Modern background execution in Android

Posted by Luiz Gustavo Martins, Partner Developer Advocate, Partner DevRel

This is the third in a series of blog posts in which outline strategies and guidance in Android with regard to power.

Over the years, executing background tasks on Android has evolved. To write modern apps, it's important to learn how to run your background tasks in modern fashion.

When is an app in the background?

Before understanding what background execution is, we need to have a clear view of when Android understands an app to be in the foreground. An app is considered to be in the foreground if any of the following is true:

If none of those conditions is true, the app is considered to be in the background.

Background execution changes

Running tasks in the background consumes a device's limited resources, like RAM and battery. This might result in a bad user experience. For example, background tasks may degrade the battery life of the device or the user may experience poor device performance at times such as watching a video, playing a game, using the camera.

To improve battery life and give a better user experience, Android has evolved over several releases to establish limits on background execution. These limits include:

Use cases and solutions

Deciding which tools to use to implement background execution requires the developer to have a clear understanding of what they want to accomplish, and under which restrictions. This flowchart can help you make a decision:

  • WorkManager is the recommended solution for background execution, taking into account all OS background execution limits. If you need to guarantee that a task will run even if it is deferred, you should use WorkManager. This API allows you to schedule jobs (one-off or repeating) and chain and combine jobs. You can also apply execution constraints to them such as triggering when the device is idle or charging, or executing when a content provider changes.

    One example is if you need to compress logs to upload them to your server. To do this you can create two work requests:

    • First: compress the file. On this step you may add the constraint that the device should be charging.
    • Second: upload it to the server. For this request you should add a network connectivity constraint so that the work only gets triggered when you have a valid connection.

    After enqueuing both tasks, WorkManager will take care of executing them when your app has access to the resources you need.

    Another nice feature of WorkManager is that it respects power-management features, so that if a job is scheduled to run at a defined time and the device is in Doze at that time, WorkManager will try to run the task during a maintenance window if the constraints are met or after Doze is lifted.

  • If a long-running task is to be scheduled in response to an external event like syncing for new online content, use Firebase Cloud Messaging to notify your app and then create a work request with WorkManager to sync the content. You can learn more about this in "Notifying your users with FCM".
  • If the app needs to complete a user-initiated task without deferring even if the user leaves the app or turns off the screen, such as in the case of music/video playback or navigation, you should use a Foreground service. (The next blog post in this series dives deeper into this use case.)
  • If you need to run a task at an exact time that triggers actions, involves user interactions, and cannot be deferred, use AlarmManager (more specifically the method setExactAndAllowWhileIdle). Examples of time alarms include:
    • a reminder to take medicine
    • a notification that a TV show is about to start.

    When the alarm is triggered, you have very few seconds to finish the work and your app may not have access to the network (for example during Doze or due to App Standby buckets). If you really need network or to do a long task, use WorkManager. Every time a wakeup alarm is triggered, the device comes out of low-power mode and holds a partial wake lock which can significantly impact the battery life over time. This can be monitored via excessive wakeups stats highlighted on Android Vitals, provided via Google Play Console.

In Summary:

Use Case Examples Solution
Guaranteed execution of deferrable work
  • Upload logs to your server
  • Encrypt/Decrypt content to upload/download
WorkManager
A task initiated in response to an external event
  • Syncing new online content like email
FCM + WorkManager
Continue user-initiated work that needs to run immediately even if the user leaves the app
  • Music player
  • Tracking activity
  • Transit navigation
Foreground Service
Trigger actions that involve user interactions, like notifications at an exact time.
  • Alarm clock
  • Medicine reminder
  • Notification about a TV show that is about to start
AlarmManager

Use background execution judiciously so that you can build cool apps that delight users while saving their battery. If you need more information on executing background tasks on Android, there's great content at the Android developer site.

Note: WorkManager is still in public preview. If you need an alternative solution right now, you should use JobScheduler, although it has limitations that don't apply to WorkManager. JobScheduler is part of the Android Framework, and only available for Android API 21 and above; WorkManager works on API 14 and above.

Acknowledgements: This series of blog posts is produced in collaboration between the Android Framework and DevRel teams