Reader small image

You're reading from  Modern Android 13 Development Cookbook

Product typeBook
Published inJul 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781803235578
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Madona S. Wambua
Madona S. Wambua
author image
Madona S. Wambua

Madona S. Wambua is a Google Developer Expert in the Android category, an Android Engineer programming in Kotlin, and the founder and Chief Technology Officer of Jibu Labs. She is also a Women Tech Makers Ambassador and Co-Chair of AnitaB. She has over ten years of experience in the field and has worked on consumer-facing applications and building software development kits for developers. She has also worked on the famous Google Glass during her tenure at a startup and got an opportunity to work on interactive AR videos to transform lives through machine learning and computer vision. Madona is also a Keynote Speaker and the host of Tech Talks with Madona, a podcast geared towards supporting women and allies in tech.
Read more about Madona S. Wambua

Right arrow

Getting Started with WorkManager

In Android, WorkManager is an API introduced by Google as part of the Android Jetpack library. It is a powerful and flexible background task scheduling library that allows you to perform deferrable, asynchronous tasks even when your app is not running or the device is in a low-power state.

WorkManager provides a unified API to schedule tasks that need to be executed at a specific time or under certain conditions. It takes care of managing and running tasks efficiently, depending on factors such as device idle state, network connectivity, and battery level.

Furthermore, WorkManager allows observation of work status and chain creation. This chapter will look into how we can implement WorkManager using examples and learn how it works and its use cases.

In this chapter, we’ll be covering the following recipes:

  • Understanding the Jetpack WorkManager library
  • Understanding WorkManager state
  • Understanding threading in WorkManager...

Technical requirements

This chapter utilizes step-by-step examples and does not create a complete project. WorkManager is helpful, but because the use case may vary, utilizing examples to see how the code fits your need is an excellent art to learn in programming.

Understanding the Jetpack WorkManager library

WorkManager is one of the most powerful Jetpack libraries, and it is used for persistent work. The API allows observation of persistent status and the ability to create a complex chain of work. When building Android applications, it might be a requirement to have your data persist; if you need help to refresh your knowledge, you can reference Chapter 6, Using the Room Database and Testing.

WorkManager is the most-recommended API for any background process and is known to handle unique types of ongoing work as shown here:

  • Immediate: As the name suggests, these are tasks that must be done immediately or completed soon
  • Long-Running: Tasks that run for a long time
  • Deferrable: A task that can be rescheduled and can be assigned a different start time and can also run periodically

Some more sample use cases where you can use WorkManager are, for instance, if your company wants to create custom notifications, send analytics...

Understanding WorkManager state

In the previous recipe, Understanding the Jetpack WorkManager library, we looked into how we can use WorkManager. In that recipe, you might have noticed Work goes through a series of state changes, and the doWork function returns a result.

In this recipe, we will explore states in depth.

How to do it…

We will continue working on an example of how you can apply the concepts learned about in this recipe to your already-built project:

  1. You might have noticed we mentioned before that we have three states: Success, Failure, and Retry. Work states, however, have different types of processes; we can have a one-time work state, periodic work state, or blocked state:
    Result
        SUCCESS, FAILURE, RETRY

You can look into this abstract class in more depth by clicking on the result and seeing how it is written.

  1. In the first recipe, Understanding the Jetpack WorkManager library, we looked into the steps of setting...

Understanding threading in WorkManager

You can think of WorkManager as any process that runs in a background thread. When we use the Worker(), and WorkManager calls the doWork() function, this action works in the background thread. In detail, the background thread comes from the Executor specified in the WorkManager configuration.

You can also create your own custom executor for your application needs, but if that’s not needed, you can use the pre-existing one. This recipe will explore how threading in a Worker() works and how to create a custom executor.

Getting ready

In this recipe, since we will be looking at examples, you can follow along by reading and seeing if this applies to you.

How to do it…

Let’s learn how threading works in WorkManager:

  1. In order to configure WorkManager manually, you will need to specify your executor. This can be done by calling WorkManager.initialize(), then passing the context, and the configuration builder...

Understanding chaining and canceling work requests

In Android development, ensuring you properly handle your application’s life cycle is crucial. Needless to say, this also applies to all background work, as a simple mistake can lead to your application draining the user’s battery, memory leaks, or even causing the application to crash or suffer from an application not responding (ANR) error. This could mean terrible reviews in the Play Store, which will later affect your business and causes stress for developers. How do you ensure this issue is handled well?

This can be done by ensuring all conflicts that arise while using WorkManager are appropriately handled or guaranteeing the policy we touched on in the previous recipe is well coded. In this recipe, we will look into chaining and canceling work requests and how to handle long-running work properly.

Say your project requires an order by which the operation should run; WorkManager gives you the ability to enqueue...

How to debug WorkManager

Any operation that requires working in the background and sometimes making network calls need proper exception handling. This is due to the fact that you do not want your users facing issues and a lack of exception handling coming back to haunt your team or you as a developer.

Hence, knowing how to debug WorkManager will come in handy, as this is one of those issues that might last for days if you have a bug. In this recipe, we will look at how to debug WorkManager.

Getting ready

To follow this recipe, you must have completed all previous recipes of this chapter.

How to do it…

You might encounter an issue where WorkManager no longer runs if it is out of sync. Follow this recipe to debug WorkManager:

  1. To be able to set up debugging, we will need to first create a custom initialization in our AndroidManifest.xml file, that is, by disabling the WorkManager initializer:
    <provider
        ...
        tools...

Testing Worker implementations

Testing your Worker implementation is crucial, as it helps ensure your code is well handled and your team follows the proper guidelines for writing great code. This will be an integration test, which means we will add our code to the androidTest folder. This recipe will look into how to add tests for your worker.

Getting ready

To follow along with this recipe, you need to have completed all previous recipes of this chapter.

How to do it…

Follow these steps to get started with testing WorkManager. We will look at examples in this recipe:

  1. First, you need to add the testing dependency in your build.gradle file:
    androidTestImplementation("androidx.work:work-testing:$work_version")

In the scenario where something in the API changes in the future, there’s a stable version that you can use, and you can always find that in the documentation by following this link: https://developer.android.com/jetpack/androidx...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Modern Android 13 Development Cookbook
Published in: Jul 2023Publisher: PacktISBN-13: 9781803235578
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Madona S. Wambua

Madona S. Wambua is a Google Developer Expert in the Android category, an Android Engineer programming in Kotlin, and the founder and Chief Technology Officer of Jibu Labs. She is also a Women Tech Makers Ambassador and Co-Chair of AnitaB. She has over ten years of experience in the field and has worked on consumer-facing applications and building software development kits for developers. She has also worked on the famous Google Glass during her tenure at a startup and got an opportunity to work on interactive AR videos to transform lives through machine learning and computer vision. Madona is also a Keynote Speaker and the host of Tech Talks with Madona, a podcast geared towards supporting women and allies in tech.
Read more about Madona S. Wambua