本文介绍了Android WorkManager中的异步工作者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Google最近宣布了新的 WorkManager 体系结构组件.通过在 Worker 类中实现 doWork() 可以轻松地安排同步工作,但是如果我想在后台进行一些异步工作怎么办?例如,我想使用翻新进行网络服务呼叫.我知道我可以发出一个同步网络请求,但是它将阻塞线程,并且感觉不对.对此有什么解决方案还是暂时不支持?

Google recently announced new WorkManager architecture component. It makes it easy to schedule synchronous work by implementing doWork() in Worker class, but what if I want to do some asynchronous work in the background? For example, I want to make a network service call using Retrofit. I know I can make a synchronous network request, but it would block the thread and just feels wrong.Is there any solution for this or it is just not supported at the moment?

推荐答案

WorkManager文档:

因此,如果您不使用synchronous(),则可以安全地从doWork()执行网络同步呼叫.从设计的角度来看,这也是一种更好的方法,因为回调是杂乱的.

Therefore, if you don't use synchronous(), you can safely perform sync network calls from doWork(). This is also a better approach from design perspective because callbacks are messy.

也就是说,如果您确实要从doWork()触发异步作业,则需要暂停执行线程,并使用wait/notify机制(或某些其他线程管理机制,例如).在大多数情况下,我不建议这样做.

That said, if you really want to fire async jobs from doWork(), you'll need to pause the execution thread and resume it upon async job completion using wait/notify mechanism (or some other thread management mechanism e.g. Semaphore). Not something I would recommend in most cases.

请注意,WorkManager处于早期测试阶段.

As a side note, WorkManager is in very early alpha.

这篇关于Android WorkManager中的异步工作者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 22:24