深入了解android jetpack库workmanager

总览 (Overview)

One thing that’s continually changing in the Android environment is how we handle background tasks. This is because when the number of apps increases on the phone, the number of tasks that run in the background will also increase. Most app developers won’t check for battery health before starting their job, which leads to the battery draining in a short time.

在Android环境中不断变化的一件事是我们如何处理后台任务。 这是因为当手机上的应用程序数量增加时,在后台运行的任务数量也会增加。 大多数应用程序开发人员在开始工作之前不会检查电池的运行状况,这会导致电池在很短的时间内耗尽。

We have many solutions to work with background tasks, but WorkManager is preferable for both developers and users. WorkManager has the power to control which tasks should execute under what circumstances.

我们有许多解决方案可用于后台任务,但是WorkManager对于开发人员和用户都是更可取的。 WorkManager有权控制在何种情况下应执行哪些任务。

If your battery is low, then it’ll stop all the tasks running in the background and restart them when the mobile is charged. With WorkManager, it’s also easy for developers to maintain periodic requests without the trouble of maintaining timestamps.

如果电池电量不足,它将停止所有在后台运行的任务,并在手机充电后重新启动它们。 使用WorkManager,开发人员还可以轻松地维护定期请求,而无需维护时间戳。

WorkManager是: (WorkManager is:)

  • Compatible with API level 14

    兼容API级别14
  • Runs with/without Google Play Services

    与/不与Google Play服务一起运行

积分 (Integration)

WorkManager is a Jetpack library, and it’s been constantly updating with new features. WorkManager is compatible with coroutines and RxJava out of the box. Integrate the following WorkManager libraries to your liking.

WorkManager是Jetpack库,并且一直在不断更新以提供新功能。 WorkManager开箱即用地兼容协程和RxJava。 根据您的喜好集成以下WorkManager库。

使用WorkManager之前应了解的事项 (Things to Know Before Using WorkManager)

There are two things you should know before using WorkManager: constraints and types of work requests.

使用WorkManager之前,您应该了解两件事: 约束工作请求的类型

约束条件 (Constraints)

Constraints are nothing but a way to communicate to WorkManager that the system should satisfy certain conditions to execute a work request. These conditions may be anything from the system needing an internet connection to not working if the system is in battery-saver mode.

约束不过是向WorkManager传达系统应满足某些条件才能执行工作请求的一种方式。 这些情况可能是任何情况,从需要Internet连接的系统到处于节电模式的系统都无法正常工作。

Constraints
约束条件

工作要求 (Work requests)

There are two types of work requests: OneTime and Periodic.

工作请求有两种类型: OneTimePeriodic

一次性工作要求 (One-time work request)

From the name itself, we can ascertain that this request executes only once.

从名称本身,我们可以确定该请求仅执行一次。

One-time work request
一次性工作要求

定期工作要求 (Periodic work request)

This request executes periodically once we start the worker. We have to mention a specific time interval between executions while building a worker object.

一旦启动工作程序,此请求就会定期执行。 我们必须提到在构建工作程序对象时两次执行之间的特定时间间隔。

Periodic work request
定期工作要求

创造工人 (Creating a Worker)

Kotlin is the first-class citizen for Android development, and coroutines are the recommended way to deal with background tasks. So here we’re using coroutine workers in examples.

Kotlin是Android开发的一流公民,协程是处理后台任务的推荐方法。 因此,这里我们在示例中使用协程工人。

To create a worker class, we need to extend the class with CoroutineWorker and implement the override function doWork() (in which we’ll perform the task). Have a look:

要创建一个工作器类,我们需要使用CoroutineWorker扩展该类并实现重写函数doWork() (在该函数中我们将执行任务)。 看一看:

建立请求 (Building a request)

Now that we have a worker class, let’s start the background job. For this, first, we need to create a constraint set, and using that, we need to build a work request, as shown below:

现在我们有了一个工人阶级,让我们开始后台工作。 为此,首先,我们需要创建一个约束集,并使用它来构建工作请求,如下所示:

观察你的状态 (Observing Your Status)

Now that we started our request, there’ll be some cases where we want to know the status of the work — like whether it succeeded or failed. In some cases, when the constraints aren’t satisfied, the request won’t even start, so it’s vital to know the current status of the request.

现在,我们开始了请求,在某些情况下,我们想知道工作的状态-例如成功还是失败。 在某些情况下,当不满足约束条件时,请求甚至不会启动,因此了解请求的当前状态至关重要。

WorkManager has a way to do this. It has various states, each representing the respective stages of the request. The following are some of the important states from WorkManager.

WorkManager可以执行此操作。 它具有各种状态,每个状态代表请求的各个阶段。 以下是WorkManager的一些重要状态。

  • ENQUEUED: This state represents the request is enqueued and ready to run once the constraints are met

    ENQUEUED :这个状态表示请求排队,准备运行一次满足约束条件

  • RUNNING: This state represents that the request has started executing

    RUNNING :此状态表示请求已开始执行

  • SUCCEEDED: This state represents that the request is successfully executed

    SUCCEEDED :该状态表示执行成功,请求

  • FAILED: This state represents that the request has failed for some reason

    FAILED :此状态表示请求由于某种原因而失败

You can find the full list of states here.

您可以在此处找到状态的完整列表。

WorkManager provides live data to monitor the state changes of the request using its id. Have a look:

WorkManager使用其id提供实时数据来监视请求的状态变化。 看一看:

Observing the work-request status
观察工作请求状态

观察你的进度 (Observing Your Progress)

In some cases, observing state changes won’t be enough — like when you want to show the progress of the request to the user if the app is in the foreground.

在某些情况下,仅观察状态变化是不够的,例如当应用程序在前台时,您想向用户显示请求的进度。

The work manager has had a way to do this since the stable release of 2.3.1. We can set the progress in the worker class using the setProgress() function asynchronously. We can set an intermediate progress that can be observed by the UI.

自从2.3.1的稳定版本发布以来,工作经理已经可以执行此操作。 我们可以使用setProgress()函数异步地在worker类中设置进度。 我们可以设置UI可以观察到的中间进度。

Observing progress information is the same as observing your status. You can use the getWorkInfoById() or getWorkInfoByIdLiveData methods and get a reference to WorkInfo. Here we use the progress variable in the WorkInfo class instead of the state. Have a look:

观察进度信息与观察您的状态相同。 您可以使用getWorkInfoById()getWorkInfoByIdLiveData方法并获取对WorkInfo的引用。 在这里,我们在WorkInfo类中使用progress变量而不是状态。 看一看:

Observing the work-request progress
观察工作请求进度

链接请求 (Chaining Requests)

There will be use cases where we want to make a set of requests in parallel or, in some cases, sequentially. For example, we may have an image to upload, but before that, we need to apply filters to it. In this case, the series of actions should be sequential; first, we should apply all the filters, and then the upload task should perform.

在某些情况下,我们想要并行或在某些情况下顺序地发出一组请求。 例如,我们可能要上传一张图片,但在此之前,我们需要对其应用过滤器。 在这种情况下,一系列动作应该是顺序的; 首先,我们应应用所有过滤器,然后执行上传任务。

WorkManager covers this type of scenario out of the box. Have a look:

WorkManager开箱即用地涵盖了这种类型的方案。 看一看:

Chaining requests
链接请求

First, we get the instance of the WorkManager by invoking the getInstance function. Then we call thebeginWith function along with a list of work requests that can be executed in parallel (filters). After that, we use the then function to invoke sequential workers (upload). We can add multiple then functions to invoke multiple sequential workers.

首先,我们通过调用getInstance函数获得WorkManager的实例。 然后,我们调用beginWith函数以及可以并行执行的工作请求列表(过滤器)。 之后,我们使用then函数调用顺序工作程序(上载)。 我们可以添加多个then函数来调用多个顺序工作程序。

取消工作 (Canceling Work)

If a work that has started previously has no use, then we can cancel the request to save resources. We can cancel the request using cancelWorkById, which takes the request id as an argument. Have a look:

如果先前开始的工作没有用,那么我们可以取消请求以节省资源。 我们可以使用cancelWorkById取消请求,该请求将请求id作为参数。 看一看:

WorkManager.cancelWorkById(downloadWork.id)

Here the important thing that we need to keep in mind is canceling a request will also result in canceling the requests that are dependent on it.

在这里,我们需要牢记的重要一点是取消请求也将导致取消依赖于该请求的请求。

奖金 (Bonus)

To know more about WorkManager — like how to use WorkManager with RxJava, the mechanics of the inputs and outputs of the worker, and how to tag a request — read this article.

要了解有关WorkManager的更多信息(例如如何将WorkManager与RxJava一起使用,工作程序的输入和输出的机制以及如何标记请求),请阅读本文

Thank you for reading.

感谢您的阅读。

翻译自: https://medium.com/better-programming/a-deep-dive-into-the-android-jetpack-library-workmanager-5aee2f57e07b

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值