8

How do I update the UI from Android WorkManager.

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

Documentation says:

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

"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. How do I pass a callback for updating the UI.
  2. How to pass POJO without DB call.

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

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
D-D
  • 954
  • 2
  • 12
  • 27
  • https://medium.com/mindorks/lets-work-manager-do-background-processing-58356e1ab844 – Madhur Sep 20 '18 at 04:59
  • Progress report is now available natively. [See this answer](https://stackoverflow.com/a/58081057/5214620) – Paulo Pereira Sep 24 '19 at 13:18
  • Possible duplicate of [Showing detailed progress for running WorkManager workers](https://stackoverflow.com/questions/50542223/showing-detailed-progress-for-running-workmanager-workers) – Paulo Pereira Sep 24 '19 at 13:19
  • Only use WorkManager do to background intensive tasks (not update UI). Use `runOnUiThread` (the main thread) to update your views. – 6rchid Aug 09 '20 at 02:52

3 Answers3

7

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.

Second, androidx.work.Data documentation states:

This is a lightweight container, and should not be considered your data store. As such, there is an enforced MAX_DATA_BYTES limit on the serialized (byte array) size of the payloads. This class will throw IllegalStateExceptions if you try to serialize or deserialize past this limit.

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.

This is shown in the WorkManager codelab.

Step 8. Tag and Display Work Status, covers this point.

pfmaggi
  • 6,116
  • 22
  • 43
0

For exactly that problem (I upload files with the WorkManager and want to monitor progress, not only result), I used EventBus. Super easy, put the listener anywhere you want - in my case the MainActivity, since I use a single activity pattern.

mrj
  • 589
  • 1
  • 7
  • 17
-1

if you want to update ui from service you may use bound service, check this question for more details Android update activity UI from service

Hazem Ashraf
  • 310
  • 2
  • 8
  • Please see : https://developer.android.com/reference/androidx/work/WorkManager https://developer.android.com/topic/libraries/architecture/workmanager/ – D-D Sep 18 '18 at 18:33