Android 工作管理器与服务? [英] Android Work Manager vs Services?

查看:48
本文介绍了Android 工作管理器与服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Android 应用程序中,我有多个意图服务,它们一个接一个地运行,第一个意图服务由广播触发.几天前我遇到了 Work Manager 并且非常喜欢 Worker 的简单性和 WorkManager 类.与常规意图服务相比,工作管理器的优缺点是什么?考虑到我将来可能需要编写更多意图服务,我现在应该切换到工作经理吗?还有哪个选项可以帮助我轻松测试代码?

In my Android app i have multiple intent services which run one after another and the very first intent service is trigerred by a broadcast. I came across Work Manager a few days ago and really liked the simplicity of the Worker and the WorkManager classes. What are the pros and cons of Work Manager over regular intent services? Should i switch to work manager now considering the fact that i may have to write more intent services in the future? Also which option would help me test the code easily?

推荐答案

WorkManager 具有以下功能:

  • 提供可以在进程死亡中幸存的任务
  • 它可以唤醒应用程序和应用程序的进程来完成工作,从而保证工作将被执行.
  • 允许观察工作状态并能够创建复杂的工作链
  • 允许工作链,允许将大块工作分成小块并根据不同的约束执行它们
  • 优雅地管理打盹模式或操作系统施加的其他限制.

以下情况会有所帮助:

  • 执行长时间运行的后台任务,例如上传媒体
  • 在数据库中解析和存储数据.
  • 需要在进程死亡中幸存的关键任务

考虑到我将来可能需要编写更多意图服务,我现在是否应该切换到工作经理?

在大多数情况下,它应该是 IntentService 的替代品,但您必须在使用前仔细考虑.可能 IntentService 一开始就不是最佳选择.

In most cases it should be replacement for IntentService but you have to consider carefully before using it. It could be that IntentService was not the best choice at first place.

WorkManager 不是所有后台任务的答案.例如.你不应该用它来处理付款,因为它不需要在进程死亡后继续存在,而且这些任务需要立即执行.考虑使用前台服务.使用它们来解析视图的数据和内容也不是一个好主意.

WorkManager is not answer to all of the background tasks. E.G. You shouldn't use it for processing payments since it doesn't need to survive process death and these task needs to be executed immediately. Consider using Foreground Service. Its also not a great idea to use them for parsing data and contents of view.

在使用它之前,您确实需要权衡是否需要它的功能.由于 Google 几乎要重新设计我们的编码方式,WorkManager 将是我们后台处理问题的解决方案.当然,这将是最重要的选择,因为它抽象了操作系统强加的几个约束的处理.您应该考虑在未来的实现中使用它.

You really need to weigh whether you need capabilities of it before using it. Since Google is almost re-vamping the way we code, WorkManager would be solution of our Background processing woes. For sure it would be most important option since it abstracts handling of several constraints imposed by OS. You should consider using it for future implementations.

还有哪个选项可以帮助我轻松测试代码?

Google 还提供了测试库,方便 WorkManager 的测试.它仍在开发中,但在发布之前应该会变得更强大.

Google has also provided testing library which facilitates WorkManager's test at ease. Its still under development but should become more powerful before its released.

这篇关于Android 工作管理器与服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆