如何同步获取WorkManager状态

How to get WorkManager Status Synchronously

我正在使用 WorkManager Alpha 05。

我正在开发一项服务,可以根据其他应用程序的需要将任务排入队列。

它有两种方法:

  1. createTask(创建一个新任务,给定一个名称和一组数据,它returns和ID)
  2. checkTaskStatus(应用程序询问服务给定的ID,任务的状态)

通信是使用消息通过绑定服务完成的。这意味着客户端和服务都有正确的实现来传递信息。

方法 1 工作正常。

我对方法 2 有疑问。

 WorkManager.getInstance().getStatusById(taskID)
            .observe(LifecycleOwner, Observer {
                status -> if (status !=null){
                    val myResult = status.state.toString()
                    statusString = myResult
                    Log.d("Task Status",myResult)
                }
            })

观察者正在正确记录状态,但我无法将该消息发送回客户端。有没有办法以同步方式检查状态?

我真的不需要将任务附加到 LiveData。

WorkManager 实例有一个synchronous method which returns the SynchronousWorkManager,这将为您提供一组执行同步操作的方法。考虑到这是要在后台线程中使用的。

似乎 Synchronous WorkManager 已于 10 月 11 日删除:

Removed WorkManager.synchronous() and WorkContinuation.synchronous() and all related methods. Added ListenableFuture as the return type of many methods in the API. This is a breaking API change.

如何使用ListenableFuture:

You can now synchronously get and observe by using ListenableFutures. For example, WorkManager.enqueue() used to return void; it now returns a ListenableFuture. You can call ListenableFuture.addListener(Runnable, Executor) or ListenableFuture.get() to run code once the operation is complete.

可以找到更多信息 here