本文介绍了从 Workmanager 更新 UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 Android WorkManager 更新 UI.

How do I update the UI from Android WorkManager.

Android Workmanager 可以接收 Boolean、Integer、Long、Float、Double、String

Android Workmanager can receive Boolean, Integer, Long, Float, Double, String

文档说:

public Data.Builder putAll (Map<String, Object> values)

将所有输入的键值对放入构建器.有效类型是:布尔型、整数、长整型、浮点型、双精度、字符串和每种类型的数组版本.无效类型会抛出 IllegalArgumentException."

"Puts all input key-value pairs into the Builder. Valid types are: Boolean, Integer, Long, Float, Double, String, and array versions of each of those types. Invalid types throw an IllegalArgumentException."

  1. 如何传递用于更新 UI 的回调.
  2. 如何在没有数据库调用的情况下传递 POJO.

Result.SUCCESS 或 Result.FAILURE 不是解决方案,因为只有在工作完成时才会返回.

Result.SUCCESS or Result.FAILURE is not the solution as this will be returned only when the work is completed.

推荐答案

首先,WorkManager 是一个用于可延迟后台工作的 API.如果您希望应用程序在前台显示更新,则它可能是错误的 API.WorkManager 文档涵盖了这一点.

First of all, WorkManager is an API for deferrable background work. If you are expecting to have the app in the foreground to display updates, it maybe the wrong API. WorkManager documentation covers this.

二、androidx.work.Data 文档 状态:

这是一个轻量级容器,不应被视为您的数据存储.因此,对有效负载的序列化(字节数组)大小有强制的 MAX_DATA_BYTES 限制.如果您尝试序列化或反序列化超过此限制,此类将抛出 IllegalStateExceptions.

由于 WorkManager 是 Android 架构组件的一部分,一个好的解决方案是使用 LiveData 在后台作业和(最终在前台)UI 之间传递状态更新.

As WorkManager is part of Android Architecture Components a good solution is to use LiveData to pass status updates between the background job and the (eventually in foreground) UI.

这显示在 WorkManager 代码实验室中.

第 8 步:标记和显示工作状态,涵盖了这一点点.

这篇关于从 Workmanager 更新 UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 09:12