Duration 31:20
16+
Play
Video

Android Jetpack: easy background processing with WorkManager

Sumir Kataria
Software Engineer at Google
  • Video
  • Table of contents
  • Video
2018 Google I/O
May 9, 2018, Mountain View, USA
2018 Google I/O
Video
Android Jetpack: easy background processing with WorkManager
Available
In cart
Free
Free
Free
Free
Free
Free
Add to favorites
42.75 K
I like 0
I dislike 0
Available
In cart
Free
Free
Free
Free
Free
Free
  • Description
  • Transcript
  • Discussion

About speaker

Sumir Kataria
Software Engineer at Google

Sumir is a software engineer on the Android team and has been the lead of various Google apps. While at Google, Sumir has been part of YouTube, Google+, and Search. Before Google, he was a gameplay and AI programmer in the video game industry.

View the profile

About the talk

This is an introduction to WorkManager, a new part of Android Architecture Components. WorkManager simplifies background task scheduling in a backwards compatible manner. It introduces powerful new features like chaining of jobs and tracking the status of your work. This talk will also provide an understanding of how to use WorkManager to ensure apps will run safely in the background.

Share

Hi everyone. My name is Samir. Kataria, and I'm an engineer on the Android team. I work on architecture components and today I want to talk to you about a new library have called work manager and background processing in General on Android. Let's talk about background processing in 2018. What are we trying to do these days just this morning. I was trying to send a picture of my lovely wife and my beautiful son to the rest of my family. So that's an example of background processing. We're also sending logs syncing data processing. All of this work is being done in the

background. Add on Android there's a lot of different ways you can do this work. There's a lot of them you can do things on threats and exact letters using job scheduler alarm manager async task Etc. Which one should you use and when should you use it? Meanwhile Android also has a lot of battery optimization is that we've introduced over the last few years, for example, the introduced doze mode in marshmallow. If you've been following Android P. We've had apps that my pockets in oreo restricted background apps Document Services. So

all of these things have to be taken care of as a developer. And finally, we always have to worry about backwards compatibility. So if you want to reach 90% of android devices you want to at least have a minute CK of Kik app. So given all of this what tools do you use and when do you use them? The trick behind this is that you have to look at the types of background work that you're doing. I like to split this up n22 act fee. The vertical axis here is the timing of the work doesn't work need to be done. Right when it's specified

or can it wait for a little bit so that if your app and your device centers bills mode, you can still do it after that. Also on the horizontal axis hear how important is the work doesn't work only need to be done while your apps in the foreground or does it absolutely need to be done at some point. So for example, if you're taking a bitmap and you decide that you want to extract the color from it and update your UI with it, that's an example of foreground only work. He don't care about it. Once the user hits home or back. That work is irrelevant mean while if you're

sending logs, you always want that to happen. That's an example of guaranteed execution. So we're things better best Deptford. You really want to use things like Red Bulls. Rxjava Arco routines. 4 things that require exact timing and guaranteed execution. Do you want to use the forecast service? So an example of this would be that you're the user hit the button and you want to process a transaction and update that you are and the state of the outfits on. That really needs a fork on service that needs to happen. Right? Then your app cannot be killed by the system while that's

happening. The sports categories very interesting. So you want guaranteed execution, but you're okay if it happens later, I don't smoke and kick in and there's a variety of ways to solve it on your API jobscheduler. If you want to go a little further back you can use Firebase job dispatcher to do that. And if you don't have Google Play services, you'll probably end up using alarm manager and broadcast receivers. And if you want to do Target all of those things while you'll use some mixed with these four thing and that's a lot of apis a lot of work to be done. Work manager Falls here. It's

guaranteed execution. That's deferrable. The work manager, let's talk a little bit about its features. I just mentioned during execution is also constrained to wear. So if I want to upload that photo that I talked about I only want to do it when I have a network. The constraint it's also respectful of the system back on restriction. So if your app is Windows mode, it won't execute. It won't wake up your phone just to do this work. It's backwards compatible with or without Google Play services. The API is Perryville. So if you have acute some work, you can actually

check what does it state. Is it running right now? Has it succeeded or failed? These are things that you can find out where they work manager. It's all so charitable so you can create browse of work so you can have work a depending on work DNC which in turn depends on work PC. Also work managers opportunistic. So this means that we will try to execute at work in your process as soon as a constraint Zermatt without actually needing job scheduler to intervene or call you out and pick you up. It doesn't wait for job scheduler to Bachelor work if your process is up and

running already. So let's talk about a little bit of the basics and talk to the code. So I just described the example. I want to upload that photo. So how would I do without using work manager? Let's talk about the core classes. There's the worker class. This is the class that does the work table right most of your business logic, and there's a work request class which comes in two flavors one-time work request or things. I just need to be done once and periodic work request for recurring work at these will both take a worker. I'll show you just now. So here's

my upload photo worker. It extends the worker class and it overrides to do work method. This is the method of run in the background will take care of that on the background thread. You don't need to put it in the background. They simply do not work and it gets her off with the photo synchronously and me return a result. So in this case, let's say we defeated. And the work of resulting I'm here has three values are fairly obvious and retriver says I encountered a transient error. Let's say that the device lost network connection in the retry me after little bit with some back

off. So now that I have this I can create a one-time work request using the upload photo worker and then I can Intuit using work manager. Get instance in queue so cute. It will start running you upload your photo. But I just talked about this what if you lose connectivity in the middle of this or even before this what if you never had connectivity you actually want to use constraints in this case. So an example of the constraint here you want to use as you make them strength Builder and you say that required Network

like to be connected so you need a connected network connection you build it and you also set the constraints on the request that you just felt somebody simply doing this and that in human get you make sure that this work only runs when your network is connected. books everyone observe this work now that we've done it, so I want to show spinner wildest work is executing at that. I want to hide the spinner when it's done. How would I do that? So as I said I went to this request. And then I can say get status by Dionne work manager using the

request ID for each request has an ID and this returns a live date out the works. That is if you guys remember architecture component life tonight is a life cycle or are observable. so now you can just look at you that observable and you can say when. Work has finished high. Caucus for So what is this word status object that you were looking at it the live data. It has and ID. This is the same idea as a request and it has a steak. The state is the current state of execution there 6 volumes are in queued running

succeeded or failed locked and cancel then we'll talk about the last two later. Movie Step Up in concept are about cheating works. I promise that you can actually make directed acyclic graphs of work. How would you do that? Let's say this is my problem. Now. I'm uploading a video. It's a huge video. I want to compress it first then upload it. So these are both eligible for background work because their time intensive team. So let's say I have 2 workers compressed. What a worker and upload for the workers are both Define to do the things

that I just said so you can make work request from them and you can say work manager begin with compressed work then upload work and into it executes first and once it's successful then upload work goes And if you were to write this out because that was a very fluent way of writing it what happens behind the scenes here is that begin with returns the word continuation and a working condition has a method called n that also returns of or continuation a different one. So you're using.

API so you can actually use his work continuations and pass them around if you want etcetera. So let's say that I'm uploading multiple photos. I take lots of photos. No one takes only just one photo of their child. So how would I upload all these in parallel? Felt so let's say I've got a work request for all of them. I can literally just say. In Q and put all of them. There is some Lorex so you can pass more than one thing there and these are all a eligible for running in parallel. They may not actually running parallel depending on your device and executor be used in all that

but they could be She was an even more complex example. Now you want to filter your photo. So you want to apply some kind of I don't know grayscale filter or sieve filter to them. Then you want to compress them how to do that makes it very simple. So first you say they didn't let you do. All the filter work in parallel after does have all completed successfully dead. And after those are completed. If you do your upload work, And don't forget to meet you at the end. So we talked

about all of that but there's a key concept that I want to cover. That's very much related to Channing. This is the inputs and outputs. Let's talk about this problem that I have here is it's a mapreduce and it's really a good way of expanding on that Ford uses to give an example. I love reading of love reading Sherlock Holmes novel since I was a kid the other day. I was thinking well top 10 words. He uses in his book. Well, how would I figure that out? I would go through each book. I want to count the occurrence of each word. And then I

would combine all of that data and sort sort it. So that would find a top 10 of those. This is a distributor problem. We could call him after 2. And for inputs and outputs, the common unit of operation here is a datum. The data is a simple class. That's a key-value map under the hood the keys are strings. The values are pepitas answering and the array versions of each in size and Gomorrah that part later. So how do we create a data and you can make a map very easily. So in this case were mapping

the key filename2 the value of study in Scarlet. Text. That's the novel that I'm going to look at and I'll converted to a work day. So this is a data object. And once I quit my work request Builder, I can set the input date on it. So this is the info data off. And I pass it along inside my worker. I can actually retrieve this in potatoes. I just calling to get an update on method. And from that I can get the string for the file names and now I have the file name and I can say count all the word occurrences in this file name. That's the message that

everything somewhere else and I can return my success. Are you don't want to do just that you actually want to also have outputs right? Now. You've done all this work. It should do something. There should be an outlook for it. So let's say that that's a good we have returns off words to their occurrences. We can convert that to a work data and we can call a medical set out today. That's that's the stayed up. So get it set out the data. So the key observation that you need to know here is a the workers outputs become the

inputs for its children. So what happens if the fine top 10 towards worker which goes next its input data is coming from the previous worker. So in this case you can pass the data. All the way through find the top 10 words and return out. So I'll pass it to the Fine top 10 words worker. It'll is input data will be whatever I passed through and it'll do the Sorting or whatever it needs to do. But here's a really picky tank. What happens when you have multiple book. What's

the input for the Pine top 10 worst worker you're passing multiple pieces of data, but I've only been able to get one in potato what happens to the rest of them or how do they combine? Or this you want to look at input mergers. The input murder is a class that combines data from multiple sources into one data object and we provide to implementations out-of-the-box overriding you put motor which is the default and a re-creating input merger. You can also pay to run. First all riding in with murder. So we have to date objects are each

with their own is it values? What does overriding input merger do? The first takes the first piece of data and it just puts everything in on you didn't like Jack so it's an exact copy of this. Then it takes a second piece of data and copies it over so over writing anything. That's the same key when disc is the name Alice becomes Bob and the age of 30 become 3 Day number became a stranger. The scores key was new so I just got added know that if we did this in

Reverse instead of Bob, you wouldn't have Alice's to find log book. So this is something a little tricky you want to make sure that's already been put in charge of the right tool for the job, but it is very simple. What about a recruiting in this is the one that actually takes care of those Collision case? So in this case, let's go just keep biking the name becomes an array of Alice and Bob color becomes a Singleton array of blue because there's only two find in one of them. Scores notice that there is one integer and one array of integers these

combined together order is not specified but all the values come through what happens or age or there's an integer and there's a string. This is an exception. We do except expect it to be the same Basic Value type. So let's go back to that example of a telling you about Sherlock Holmes. Implicitly there's an input murder before the stage so we can combine all of that data and we don't want to throw away any of this calculation that we've done. So we actually want to use in the rake raining at the merger was preserve all of the

data and get the through. So, how do we do that? Well, we just say set input murder on the request Builder off to find top 10 worst, but it merges they are using an array grading and put merger. See you say you get with account Works workers. Then do the Pine top 10 worst worker. And then thank you. So for example, if the first book had 10 instances of the word Sherlock 5 of Watson and 30 of Elementary and the second one had full 15 and 5. You will get a raise like this would be 1012 Watson would be 5:15. Elementary would be 35. So in your fight top

10 Wordsworth, are you with some all of that sort them trying to talk to her and that's in Rockford. And I just thought. To route with right so you can actually observe the output in your work status using add life Aid on so you can actually get that out of data. So that's super useful because you can display it in your UI. How do you cancel work? So I just decided to send off a picture but I'm like wait a sec. This is not the picture I meant to send off. How do you cancel that upload? Very simply to say cancelled work by ID, but do note

that cancellation is best efforts. So the work may have already finished. These are all asynchronous things. They may be happening in the background before you had a chance to do the council work in may already be running or finished. So it's best ever. Okay. So let's talk a little bit more about tag and tags are solving this problem IDs that I just told you about our auto-generated. They're not human readable. So they're actually uuid under the hood and you can't really understand them. They're not useful for

de bugging. If you log them. They're not going to make sense. What kind of work was running? I don't know. It's just a number. I don't know what that is. Text Falls official a readable way to identify your work. So tags are Developer specified strings by you and each worker quest in have zero or more tags. You can query and Castle work by pack. It's like an example. So I used to work on the G+ team here and the G+ app supports multi login. So you can have multiple users logged in at the same time. And each of those

users could be doing several kinds of background for if you could be getting if you have three users logged in on your phone and they're doing two kinds of work. You have six things happening. How do you identify what you're looking at it at any given time? Well, you can use tag. So for example. In this water particles, are you can add tags to say this is our one and this is a get favourites operation. So now you can actually identify that work. And if you wanted to look at the status as you could say give me all the work for using one and this will return a list of work status is as a

live betta because each talking horse wanted more than one work request. So this is a list of work statuses. Similarly, you can also cancel all work by tag cancellation is best effort again, but you can cancel all of one particular kind of work in this game. Text are also useful for a couple of other reasons tax namespace your type of work as I just told you like you can have tags for the kinds of operations. You're doing get favorite get my preferences etcetera, but they also named space light reason modules. So you're a librarian or a module

owner. You should always tag you're worth so you can get it later. Let's say that you have a library and you move to a new version of that library in your half. Maybe you want to cancel all the work you had you can cancel all work by your tag. So always use tax when you are using a library. I'm worth that has also has tags available. And it's like you're ever looking at a work status. You can get the tax rate at work and see what what you yourself called it in the past when you're into it. One more thing I wanted to talk about is unique work. So unique worth

solve a few different problems. But one of the common ones that almost every app has is thinking you want to think when you first launch the app you want to think maybe every 12 to 24 hours to get the freshest stayed up and you may also want to think when your language changes maybe you have a version of your data in a different language. So you want to think at that point too. So you're doing all this thinking but you really only want one thing active at a time. You don't want forcing corporations running which one is the right one which one wins. You don't know. Do you just want one?

Unique work consultant so it is a chain of work can be given a unique name. You can in queue Cory and cancel using that name and there can only be one channel with that name. We'll take a look at think examples. So if I say big in younique work. With my name, let's say think in this case. Next argument is what I call the existing work policy. So if there is work with this name think what should I do with it? In this case? I say keep it. I want to keep the existing work ignore what I'm doing

right now. The next argument is actually your work request in this case the sink request and you into it if there's work with the name bank already in Flight. It will keep that if there isn't it belong to this and executed. So this is how you do if your sink? So here at Google we love chat apps and maybe you're updating your chat status. So you want to say I'm bored and then 10 seconds later. I'm watching TV then I'm bored again. Okay, and you in a bad network connection State you you have bad Wi-Fi and maybe the first thing hasn't gone through when you

type your second chat status update and really the second one should win and everyone should win over. So you want to make sure that the last one win. How would you solve this? Here's a simple function. You don't even need to read the rest of it. It's the last line that I want you to care about which is begin unique work. It's your name is update status and you choose to replace option replace castles. I delete any existing in Flight operations off that name. So the last one always does when in this case, if you have to update chat. It's called the last one will win.

And finally, I love music. I love the Foo Fighters. I was building a playlist the other day with all their songs. There's a lot of songs is like 150 or 200 songs and I was doing all of this. I was hiding a song I was shuffling to songs around. I was moving something to the bottom of the list. I was deleting a song cuz I had it already somewhere else. These are all things that I want to do using work manager. But how would they do that? These tanks all have to execute in order. SOC order is important. We provide the ability to use the app and existing work

policy that says do this work. At the end of the list of update playlist operation. So appendix to the end of this thing. So everything else must successfully execute before diss execute so you can add operations to the end. The existing work policy as a summary. There's three type Heap replaced in a pan. Few notes about periodic work. It works very similarly to everything you've seen so far just a couple notes on it. So the minimum. Length is the same as job scheduler. It is 15 minutes. It is

still subject dos mode and Os background restrictions. Just like any of the other work we've talked about it can't be chanted can't have initial delays and we think that that just makes good API stands that much more reasonable to think of it in those terms. All right. So we talked a lot about code. Let's talk about how it all works under the hood. So you got off work you and Q it restoring our database what happens after that? Well, if the work is eligible for execution, we just send it to the executor right away. By the way

this executor you can actually specify it, but we do provide one. That's default. But let's say that your process gets killed while what happens then how did they get woken up and how does this work run again? so if you're on a pack 23 + We sat at the job scheduler as well and job scheduler in books and IPC wakes up your process. It goes to the same exact at her and that's where it runs. If it's an older device. And you use Firebase job dispatcher and user optional dependency. We can send it to harvest your dispatcher same thing and walk the night PC runs another executor. What if you

don't have that or you're not using a Google Play services device, so you're using something else. We havin a custom alarm manager and broadcast receiver implementation and the same thing uses the night PC wakes up Rob when the time is right. I want the job. A couple implementation details of job scheduler and partners job dispatcher to Google Play services. Do they provide Central load balancing mechanism for execution. So if every app on your device is trying to run you off balance, then we'll make sure that's like you're not running too much work on

your device and running up your battery the alarm manager implementation that we have unfortunately can't do that because it's only available for your own app. Of course your Concepts like haunted you're right triggers Idol Jose mode etcetera are only available at the API levels that they were introduced that so appropriate API level. We take care of a penny wakelocks when necessary. So especially this is true for the alarm manager implementation. Don't take away clocks in your workers. You don't need to do that. We take care of it

for you. Finally look talk a little bit about testing you want to test this app? We provide a testing Library. It has a synchronous executor use work manager as normal to into your request and we provide a classical test driver which constrains so we can just pretend that the constraints in math. So if you wanted to look at the code for it, you can initialize the test work manager. Got the test driver. Create an interior work as you normally would with a constraint in this case, then you can tell the test driver. Your work executes at that point they cannot lie and you can

verify the state if you're up and make sure that everything's right. I also want to talk a little bit about best practices with Ryan to hear. It's very important to know when to use work Manager work manager is for tasks that can survive process death. It can even wake up your app and your apps process to do the work. Surprised that was okay when you want to use it to upload media to server. It's also okay when you part one of our state and stored in your database. It's not okay. For example, I gave earlier you're extracting the pallet color from an image and updating an image

of you with it because that's for rent. Only work. It's also not okay, when you're in the context of of you because you could switch screens you could go in the background. It's not work that needs to use work manager. It doesn't need to survive Frost that also it's not okay to process payment transactions if there care about timing right then so if you click by anyone update the state of the app that really need something else so that last one needs a foreground service the other two major threat tools are all right.

Also work manager is not your data store instances of data are limited Transportation information. You can put file you arise or keys to other databases in there. If you want you can put simple information to update your UI. If you want to use the full date of store, I would recommend using room it would be very happy that I'm saying this. It's an awesome database. Finally be opportunistic with your work. So here's the filter compressed up one example again. The reason that these are not just one big job is because they all have different strengths

so they can execute a different time. Let's say I'm getting on an airplane and I'm uploading a bunch of images and and running this chain of work. Well I go into airplane mode. Maybe I don't have Network for the next 12 hours cuz I'm flying across the world while the other work and still execute and it should so if you architect like this, you can't do that this also by the way makes it a little bit more because he can write a test for a filtering that isn't conflated with compression and upload. All right, and I want to talk about a few next steps for you.

If you need to reach us and talk to us about work manager. We are in the Android sent box. Android.com Arts work. More information on the official developer website about work manager. The second one is if you use Firebase job dispatcher also include that it's a testing library. And of course we have gotten extensions as well. I work manager is part of the architecture components in Android jetpack and we have a bunch of talk to her tomorrow navigation controller. 8:30 A M. I hope you guys make it there.

And thanks for being part of the talk. We look forward to hearing back from you soon. Thank you.

Cackle comments for the website

Buy this talk

Access to the talk “Android Jetpack: easy background processing with WorkManager”
Available
In cart
Free
Free
Free
Free
Free
Free

Access to all the recordings of the event

Get access to all videos “2018 Google I/O”
Available
In cart
Free
Free
Free
Free
Free
Free
Ticket

Interested in topic “Software development”?

You might be interested in videos from this event

September 28, 2018
Moscow
16
159
app store, apps, development, google play, mobile, soft

Similar talks

Fred Chung
Developer Platform Manager at Google
+ 2 speakers
Dan Galpin
Team Lead at Google
+ 2 speakers
Eric Kuxhausen
Software Engineer at Google
+ 2 speakers
Available
In cart
Free
Free
Free
Free
Free
Free
Lukas Bergstrom
Product Manager at Google
+ 1 speaker
Yigit Boyar
Software Engineer at Google
+ 1 speaker
Available
In cart
Free
Free
Free
Free
Free
Free
Kat Fang
Software Engineer at Google
+ 1 speaker
Kiana McNellis
Engineer at Google
+ 1 speaker
Available
In cart
Free
Free
Free
Free
Free
Free

Buy this video

Video

Access to the talk “Android Jetpack: easy background processing with WorkManager”
Available
In cart
Free
Free
Free
Free
Free
Free

Conference Cast

With ConferenceCast.tv, you get access to our library of the world's best conference talks.

Conference Cast
558 conferences
22059 speakers
8245 hours of content