workmanager_使用WorkManager立即执行后台

workmanager

When you have to execute long running tasks while your app is in the background, you will encounter restrictions to background execution that were introduced with Android 8.0. These restrictions incentivize developer behavior that improves the user’s experience of the entire platform.To make it easier to accommodate different use cases, we also improved the developer experience when working with background restrictions by adding functionality to WorkManager.

当您必须在后台运行应用程序时执行长时间运行的任务时,您会遇到Android 8.0引入的后台执行限制 。 这些限制激励了开发人员的行为,从而改善了整个平台的用户体验。为了更轻松地适应不同的用例,我们还通过向WorkManager中添加功能来改善了开发人员在使用后台限制时的体验。

We recommend you use WorkManager to execute long running immediate tasks.

我们建议您使用WorkManager执行长时间运行的即时任务

Follow along and learn about the benefits of using WorkManager for immediate execution of long running tasks and how to set everything up.

继续并学习使用WorkManager来立即执行长时间运行的任务的好处以及如何设置所有内容。

API简介 (Introduction to the API)

Starting with WorkManager version 2.3.0, every Worker has access to methods to run tasks in a foreground service. The Worker base class, ListenableWorker, provides a new setForegroundAsync() function.

从WorkManager 版本2.3.0开始 ,每个Worker都可以访问在前台服务中运行任务的方法。 Worker基类ListenableWorker提供了一个新的setForegroundAsync()函数。

This post uses CoroutineWorker for demonstration purposes. In CoroutineWorker, setForegroundAsync() is wrapped in a suspending setForeground() function. The class also provides the suspending doWork function which allows running code off the main thread. But all of this post’s content is also applicable to the corresponding functions for other Worker classes.

这篇文章使用CoroutineWorker进行演示。 在CoroutineWorker中, setForegroundAsync()包装在一个暂停的setForeground()函数中。 该类还提供了悬挂的doWork函数,该函数允许在主线程之外运行代码。 但是,本文的所有内容也适用于其他Worker类的相应功能。

When you use setForeground(Async), the scheduled task will be run in a foreground service, immediately, once the constraints are met. As a bonus, WorkManager takes care of handling the service’s lifecycle for you. And, the ten minute time limit for background work won’t apply to the work you’re doing in a worker running in a foreground service.

使用setForeground(Async)时,一旦满足约束,计划的任务将立即在前台服务中运行。 另外,WorkManager会为您处理服务的生命周期。 而且,后台工作的十分钟时间限制不适用于您在前台服务中运行的工作人员所做的工作。

立即开始执行 (Get started with immediate execution)

Let’s take a look at how to make an existing worker execute work in a foreground service.

让我们看一下如何使现有工作人员在前台服务中执行工作。

Our starting point is a very simplified doWork() function. Code is executed asynchronously, and depending on whether it succeeds or not, the corresponding Result is returned.

我们的起点是非常简化的doWork()函数。 代码是异步执行的,并根据其是否成功返回相应的Result

/* Copyright 2020 Google LLC.
   SPDX-License-Identifier: Apache-2.0 */


override suspend fun doWork(): Result {
    try {
        // code to be executed
        return Result.success()
    } catch (throwable: Throwable) {
        // clean up and log
        return Result.failure()
    }
}

In doWork() you will also tell WorkManager that the task should be run immediately and in a foreground service.

doWork()您还将告诉WorkManager该任务应立即在前台服务中运行。

To do this, you have to create a ForegroundInfo object and provide it to setForeground(). ForegroundInfo takes a notification id as well as the Notification that will be displayed as parameters.This information is used to set up and run the foreground service once constraints are met.

为此,您必须创建一个ForegroundInfo对象并将其提供给setForeground() 。 ForegroundInfo接收通知ID以及将作为参数显示的Notification 。一旦满足约束,此信息将用于设置和运行前台服务。

设置ForegroundInfo (Set up ForegroundInfo)

Correctly setting up ForegroundInfo is as easy as 1, 2, 3:

正确设置ForegroundInfo就像1、2、3一样简单:

  1. Create a Notification

    创建一个通知
  2. Create a Notification Channel

    创建一个通知频道
  3. Provide the Notification to ForegroundInfo

    提供通知给ForegroundInfo

In the code below, createForegroundInfo() calls createNotification(), which in turn populates the notification and creates the corresponding channel.

在下面的代码中, createForegroundInfo()调用createNotification() ,后者依次填充通知并创建相应的通道。

/* Copyright 2020 Google LLC.	
   SPDX-License-Identifier: Apache-2.0 */


/**
 * Create ForegroundInfo required to run a Worker in a foreground service.
 */
private fun createForegroundInfo(): ForegroundInfo {
    // Use a different id for each Notification.
    val notificationId = 1
    return ForegroundInfo(notificationId, createNotification())
}


/**
 * Create the notification and required channel (O+) for running work
 * in a foreground service.
 */
private fun createNotification(): Notification {
    // This PendingIntent can be used to cancel the Worker.
    val intent = WorkManager.getInstance(context).createCancelPendingIntent(id)


    val builder = Builder(context, channelId)
        .setContentTitle(title)
        .setTicker(title)
        .setSmallIcon(R.drawable.baseline_gradient)
        .setOngoing(true)
        .addAction(drawable.ic_delete, cancel, intent)
    if (VERSION.SDK_INT >= VERSION_CODES.O) {
        createNotificationChannel(channelId, name).also {
            builder.setChannelId(it.id)
        }
    }
    return builder.build()
}


/**
 * Create the required notification channel for O+ devices.
 */
@TargetApi(VERSION_CODES.O)
private fun createNotificationChannel(
    channelId: String,
    name: String
): NotificationChannel {
    return NotificationChannel(
        channelId, name, NotificationManager.IMPORTANCE_LOW
    ).also { channel ->
        notificationManager.createNotificationChannel(channel)
    }
}

在前台服务中运行工作 (Run work in a foreground service)

Now let’s bring things together. Since we already have an implemented doWork() function, we can call setForeground() and pass required information by calling createForegroundInfo().

现在,让我们把事情放在一起。 由于我们已经实现了doWork()函数,因此可以调用setForeground()并通过调用createForegroundInfo()传递所需的信息。

/* Copyright 2020 Google LLC.
   SPDX-License-Identifier: Apache-2.0 */


override suspend fun doWork(): Result {
    try {
        setForeground(createForegroundInfo())
        // code to be executed
        return Result.success(workDataOf(KEY_RESULT to result))
    } catch (throwable: Throwable) {
        // clean up and log
        return Result.failure()
    }
}

⚠️⚠️⚠️Call setForeground() before your long running task kicks off.Otherwise your worker will be treated as non-foreground service until setForeground() has been called, which might result in unwanted results such as work being cancelled.⚠️⚠️⚠️

long️⚠️⚠️ 在长期运行的任务开始之前调用setForeground() 否则,在调用setForeground()之前,您的工作人员将被视为非前台服务,这可能会导致不必要的结果,例如取消工作.⚠️⚠️⚠️

🐾下一步 (🐾 Next steps)

Now that you know when and how to use long running workers you can go ahead and get started implementing them in your app.

现在,您知道何时以及如何使用长期运行的工作人员,接下来就可以开始在应用程序中实现它们。

👩‍💻👨🏽‍💻 To see this running in an example, check out the WorkManager sample on GitHub. The code to run work in a foreground service can be found in the BaseFilterWorker class and this commit.

💻要在示例中查看运行情况,请在GitHub上查看WorkManager示例 。 可在BaseFilterWorker类和此commit中找到在前台服务中运行工作的代码。

🔖 For a detailed guide on long running workers and foreground services, take a look at the advanced WorkManager guide for long running workers.

🔖有关长期运行的工作人员和前台服务的详细指南,请参阅长期运行的工作人员的高级WorkManager指南

🦮 Make sure to check out the updated Guide to background processing and read through the Kotlin coroutines on Android to learn more about the topic.

🦮确保查看更新后的后台处理指南,并通读Android上的Kotlin协程以了解有关该主题的更多信息。

📚 To learn more about WorkManager, Lyla and Pietro created a blog series to guide you from the basics to advanced features of WorkManager.

📚要了解有关WorkManager的更多信息, LylaPietro创建了一个博客系列,以指导您从WorkManager的基础知识到高级功能。

🐛 Report any issues you face on the Google IssueTracker. This will help us prioritize features and bug fixes as they come in.

Google IssueTracker上报告您遇到的任何问题。 这将有助于我们优先考虑功能和错误修复。

📝 Let me know how running immediate tasks works for you in a comment below or on Twitter.

me在下方或Twitter上的评论中,让我知道运行即时任务的工作方式。

翻译自: https://medium.com/androiddevelopers/use-workmanager-for-immediate-background-execution-a57db502603d

workmanager

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值