Work manager android example

Working With WorkManager in Android Like A Pro

How can we schedule our application tasks at a particular time or periodically? How can we add constraints to our scheduled task like network availability(only Wifi some times) or if the device is charging? We see such tasks occurring in our day to day applications like WhatsApp and PlayStore App updates. Can we chain up such tasks together? We have a solution for all these questions and many more in Android Development.

Work Manager

Welcome to the Android-Work Manager blog.

So let’s discuss Work Manager and its use in background processing in this blog.

We have a lot of ways to do background processing in Android, like AsyncTasks, Loaders, Alarm Managers, etc., Which one to use when? How can we come to a decision on the same?

For more information, please refer to background processing guide

As an Android Developer, we should have an idea of the latest optimizations Android is coming up with its newer versions of OS being released for better performance. Also, we cannot guarantee every android device being used in the market contains the latest version of the Android OS installed. So, we should think about backward compatibility to reach the maximum number of devices that are present in the market(at least a min SDK of KitKat).

So how do we categorize our work that needs to be scheduled based on its importance?

Let’s say our work is to open a contacts screen by clicking on the Contacts button. This is something that is only related to the UI part. Hence the main thread or the UI thread is enough to perform this piece of work. We don’t need this to be done when our device is in doze state. This is an example of a Foreground Service. It’s a guaranteed execution and it needs to be done immediately.

Now, let’s say we have to perform a task but it need not be immediate. Like you want to set a reminder for the day after tomorrow at 8 pm. Now, this reminder will occur nearly after 48 hrs. So the device can be in a doze mode or alive during this period. We have a handful of APIs to perform these tasks. Like Job Schedulers, Firebase Job dispatchers, or Alarm manager with Broadcast receivers in the previous versions.

Now, what if we have a functionality that needs all the properties of these APIs. We tend to come with a combination of all the APIs discussed. That’s a lot of APIs to be used for in a single application. This is where WorkManager comes into the picture.

BackWard Compatible

WorkManager is Backward compatible up to API 14 -Uses JobScheduler on devices with API 23+, Uses a combination of BroadcastReceiver + AlarmManager on devices with API 14–22

WorkManager is intended for tasks that are deferrable — that is, not required to run immediately — and required to run reliably even if the app exits or the device restarts. For example:

  • Sending logs or analytics to backend services
  • Backing up user data with Server on a Periodic basis (Eg: WhatsApp, Google, etc.,)

Constraint Aware

WorkManager is constraint aware. In our day to day usage, we see our phone getting the latest software updates and we are requested to keep our devices in charging mode for these updates to happen as it may take time and insufficient charge can lead to improper installation of software. Sometimes, we see our apps getting updated as soon as we connect our phones to our power adapters. These kinds of tasks are constraint aware.

Accepts Queries

WorkManager is Queryable. A work that is handed off to the system by the WorkManager can be in a Blocked State, Running State or a Cancelled State. We can get the state of the work by passing the id of the Work like below:

By doing this, we can improve the UX by displaying a progress bar while the task is being executed by the work manager.

Chainable

WorkManager is Chainable. Let’s say we have a series of works that are dependent on each other, we can chain them up with Work Manager. You can also specify the order in which the works that are chained should be done.

Let’s say we want to upload photos to the server. For this task to be done, let’s say we want to compress the images first and then upload it. These tasks need to be done on a background thread as they are time taking tasks and it is evident in this case that they are dependent on each other. We can chain up these tasks by using the Work Manager.

Читайте также:  Счетчик кадров для андроид

In the above code snippet, work 1, work 2 and work 3 can be referred to as three different images that are extracted in parallel since they are a part of beginWith(). work 4 can be referred for compress and then work 5 can be upload. This way we can chain up our tasks.

WorkManager can be used to perform a unique task(OneTimeWorkRequest) or a recurring task(PeriodicWorkRequest) based on the requirement.

In order to execute a OneTimeWorkRequest or the PeriodicWorkRequest, we have to pass the work to these requests which are our Worker class. This is where our business logic is written in the doWork() method:

The doWork() method runs on the background thread. We can see here a success result is returned once the uploadImages is successful. The other two enum values for the return type are a failure and retry. Return types success and failure are fairly obvious, but what does retry do here? Let’s say we are performing a task with a Work Manager with a constraint that is network connected. If the network get’s disconnected in the midst of the work being done, we can retry the task.

Inputs and Outputs

Not just this, we can create data as inputs and get outputs as data with respect to WorkManager requests. The inputs and outputs are stored as key-value pairs in the Data object.

So, how do we create a data object? Let’s create a simple map in kotlin and convert it into a workData so that it gives a Data object

Now, where can we retrieve this data? It can be done in the overridden doWork method in our Worker class

Now, we see that the compressImages is returning a map of images mapped to their respective sizes. Let’s say we need this data. We can set the output from our worker thread as a Data object.

If we are using a chain of work requests here, the key observation is that the output of a worker will become input for its child workRequests.

Let’s say we use a UploadWorker after the CompressWorker, the compressedImages that is executed in the CompressWorker can be an input to the UploadWorker. It can be retrieved similarly in the doWork method of the UploadWorker class.

This works fine if we have only one worker request chained with another work request. What if we have multiple work requests(running parallel) chained with another work request that needs input from all these parallelly running work requests like

What if the input for work 4 should be the combined output of work 1, work 2 and work 3? InputMerger to the rescue.

InputMerger

InputMerger is a class that combines data from multiple sources into one Data object. There are two different types of InputMergers provided by WorkManager:

OverwritingInputMerger (default) attempts to add all keys from all inputs to the output. In case of conflicts, it overwrites the previously-set keys.

ArrayCreatingInputMerger attempts to merge the inputs, creating arrays when necessary.

Important note:

There might be instances where we get outputs containing similar keys. So, we must be cautious in choosing our Inputmergers. If we want to override the key values, we can go for OverwritingInputMerger. If we want to save all the instances of the respective Key, we have to use ArrayCreatingInputMerger. It creates an array of values(if the values for a key are more than one) for the respective key.

Exception-Example case study for ArrayCreatingInputMerger:

Let’s say we have a key, “age”. One work request has value 30(Int) in it for this key. Another work request has value “three days”(String) in it for the same key. Can the ArrayCreatingInputManager merger these values and create an array for the key “age”? No. It gives an exception. So, it is expected that the datatypes of the values for similar keys should be the same.

How to use InputMerger

Work Manager can cancel the unwanted tasks or tasks that are scheduled by mistake. All that we need to do is to send the task id to cancelWorkById() method :

The Tag Support

The ids that we are referring to here are auto-generated and generally large numbers that are not easily readable by humans. Let’s say we have to log them we are unsure whether we are logging the correct workRequest Id. To overcome this issue, each work request can have zero or more tags. We can query or delete our work requests by using these tags.

Now, if we want to see the status of all the works that are associated with a given tag, we can just use

The above statement returns a LiveData
> as more than one work request can be associated with a single tag. We can use this result to get the statuses like

Similarly, we can use the tags to cancel the work like:

Читайте также:  Лучший видеоплеер для android 2021

Existing Work-Keep it unique or Add Operations with Keep, Replace and Append

Keep, Replace and Append

These three properties add advantage to using Work Manager.

Let’s say we have a work request with tag “image_1” that is already enqueued with the WorkManager.

Let’s say we define this work request to upload a particular image. And if by mistake, we click on upload the same image, this property helps us in not repeating the task.

So, if there is work already with “upload” ongoing, it will keep that request. If there isn’t one, it will enqueue this particular request.

Replace

This will replace any ongoing work with the name “upload” and replaces it by enqueuing this particular work.

Append

This helps in appending the respective work request to an already existing unique work request with the name “upload”(if it exists)

Note: Please be careful when you add the constraints to the work requests in a chain of work requests. Each and every work request that is being chained may not need the same constraints. For example, if our work request contains image upload and we are chaining compress image and upload image work requests together, compressing an image may have constraints related to storage and uploading image can have a constraint with respect to the network connection. So, add the constraints accordingly.

References

Work Manager from the Android Developers Youtube Channel from Google i/o 18.- This video link also describes how the Work Manager operates under the hood. A snapshot of the same is being give here:

That’s all about WorkManager! Hope this article has been of use to you and has given you a basic idea of how Work Manager is useful for us.

Источник

Using Work Manager in Android with Example

In this post, we’ll take a look at how to use the work manager in android. Work manager is a part of the android architecture components and is a good replacement of all the previous scheduling options.

Other scheduling options such as JobScheduler, GcmNetworkManager etc. But they had their shortcomings. GcmNetworkManager required play services, so it won’t work on some chinese OEMs and JobScheduler supported API > 21.

But the work manager in android solves all of these problems and more, elegantly. It’s by far one of the most easy to use APIs in Android.

In this work manager example, we’ll create an app to use Work Manager to download 3 images in the background and add them to a list.

Warning: Work manager shouldn’t be used for tasks such as downloading something on button click. It should only be used for DEFERRABLE tasks. But for the sake of simplicity I’ve taken this example.

Getting Started

Create a new Android Studio Project

I’m going to name my project work manager demo. You can name it anything you want. Make sure to select an empty activity. We’ll be writing everything from scratch.

Add dependency for Work Manager in Android

Let’s add some dependencies. First and foremost for Work Manager. Then I’ll add some extra dependencies for this example. It includes Picasso, Gson, and EventBus.

As of writing this article, the latest version is 2.4.0, you can find the latest version on developers.android.com. Or just search for work manager dependency and it’ll be the first link.

Structure of the app

The diagram below shows the basic flow of our app. Mainly we’ll have a worker (which I’ll explain in the following sections), an ImageUtil class to download images and our MainActivity to start the process.

Using Work Manager in Android

Building the UI

The UI of this app will be very simple, it’s a scrollview with 3 imageviews. And a button at the bottom to kick off the Work Manager.

Adding the data for Images

Add the JSON provided below to the top of your MainActivity.kt file. This will contain a URL for the image to download.

Also, let’s go ahead and add a click listener to the button. Upon clicking the button, we’ll call a method startWorker() . Now this is where the fun starts!

Passing Data to our Worker

The Work Manager takes a Worker which contains the task that we want to perform. What we’ll do is, we’ll pass the JSON to our worker which then would download all the images.

To pass data in the work manager, we’ve to use a special Data object provided by the Work Manager in android. Here’ how to create the data object:

Data takes all the primitive types. Hence we use the putString method.

Very Important: The limit for data is 10KB. If you try to pass things such as bitmap (by converting to Base64), it’d fail. So be very cautious when passing data to the worker.

Adding Constraints in Work Manager

Constraints are a very powerful feature of the work manager. It allows us to specify certain conditions which have to be met in order for work to start.

If the conditions are not met, work will not be started no matter if we’ve started the process in code.

There’s no guarantee that the work manager will start your work at the exact time. Hence tasks such as downloads should be done using DownloadManager in android. Use work manager for deferrable tasks only. For example: syncing logs in the background, taking backups of chat etc….

Читайте также:  Как установить квик андроид

To add constraints, all you need to do is build a constraint object using builder pattern as shown:

You can specify many constraints such as:

  1. Require device idle: Will trigger work only if the device is idle and not in use.
  2. Require charging: Will trigger only if phone is plugged in for charging.
  3. Battery not low: Requires battery to be at a certain level.
  4. Storage not low: Storage should not be low

You can find all the constraints at: developer.android.com

Creating a OneTimeRequest for Work Manager

We’ll be creating a one time request. As the name suggests, it’ll fire once and stop. If you want to schedule periodic tasks, consider using PreiodicWorkRequest.

Use the builder pattern from OneTimeRequest. Pass ImageDownloadWorker::class.java in the builder constructor. We’ll be creating the worker in the next section.

Also pass the data and the constraints using the builder functions:

This creates our OneTimeRequest.

Starting the Work Manager

Finally, we can start the worker as below:

We get an instance of the work manager and then enqueue the work. Pass a UNIQUE work name. This will be used to refer to the work in future. If you append another work with this work.

Next we tell what ExistingPolicy to use. ExistingPolicy defines what will happen if a work with same name is already present.

There are 4 policies that can be used:

  1. REPLACE: If a work already exists with the same name, replace it with this new work. Previous work will be stopped and deleted.
  2. KEEP: If a work already exists with same name, do nothing. Original work will continue as it is.
  3. APPEND: append the new work to already existing work.
  4. APPEND_OR_REPLACE: If previous work failed, it’ll create a new sequence, else it behaves like APPEND.

Finally we pass our request object. This will trigger the work manager and if conditions are met, it’ll start the ImageDownloadWorker. Let’s go ahead and create the worker.

Creating Worker for Work Manager in Android

Our worker will do two things:

  1. Download the images.
  2. Display a notification for progress.

For creating the worker, create a class called ImageDownloadWorker.kt and extend if from Worker.

Implement the doWork method. This is where our work starts. First let’s go ahead and implement the downloading.

Downloading the images

Get the JSON data you passed in the MainActivity using inputData.getString:

We’ll convert it into a list of image objects using Gson. Image is a data class that I created for storing info about images easily.

The Image class:

Next up, we’ll iterate through each image object, download the image and store it in our storage. Add the download function below to your worker:

It uses the ImageUtil class provided below. I created it to keep my logic for downloading the image separate. Create a new ImageUtil class and add the code below:

Displaying the notification

To display a notification for progress, add the following method to your worker. Also invoke it at the start of doWork method.

We’ll also have to cancel the notification when the worker stops. So override the onStopped method and add the following:

And we’re done! Finally this is what your ImageDownloadWorker file would look like:

Display the images in MainActivity

We’re sending an event from our worker. We’ll catch it in our MainActivity class and display the image.

Simply initialise the EventBus in onStart and stop it in onStop. Here’s what your final MainActivity.kt file would look like:

Here’s the final app:

This brings us to the end of our work manager in android tutorial. If you have any problems with the application let me know in the comments below and I’ll be happy to help you out.

You can find the repository for this project here on github: https://github.com/Ayusch/WorkManagerDemo

Want to be a better developer ?!

AndroidVille is a community of Mobile Developers where we share knowledge related to Android Development, Flutter Development, React Native Tutorials, Java, Kotlin and much more.

If you’re comfortable in Hindi, then you should Subscribe to our channel DesiCoder: Click Here

We have a SLACK workspace where we share updates related to new job opportunities, articles on Mobile Development/updates from the industry. We also have channels to help you with any questions, dev-help that you require. Just post a question and people would be ready to help you out 🙂

If you like any article, do give it a share on Facebook, Linkedin. You can follow me on LinkedIn, Twitter, Quora, and Medium where I answer questions related to Mobile Development, especially Android and Flutter.

If you want to stay updated with all the latest articles, subscribe to the weekly newsletter by entering your email address in the form on the top right section of this page.

Click the image below to join our slack channel

Get more stuff

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for subscribing.

Something went wrong.

we respect your privacy and take protecting it seriously

Источник

Оцените статью