Android:何时使用服务与单例?
我对 Android 开发还很陌生。
什么时候创建 Android 服务而不是仅仅使用简单的 Singleton 类是个好主意?
以数据层从互联网下载信息源为例。
在某些情况下使用服务似乎太多了,但有时我可能需要访问Context
,所以我有点不确定如何设计应用程序。
I'm quite new to Android development.
When is it a good idea to create an Android Service instead of just using a simple Singleton class?
Take, for example, the data layer downloading information feeds from the internet.
Using a Service seems too much for some cases but sometimes I might need access to a Context
so I'm a little unsure about how to design the app.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您的进程可以在用户离开其活动后立即被终止(与单例一起),那么请使用单例。如果您需要它在此后继续运行一段时间,请使用服务。如果您想在用户离开后继续运行,但可以忍受它,而不是因为用户现在正在执行需要更多内存的其他操作,那么请使用单例。
这两者之间的决定仅取决于应用程序的生命周期。为此,这就是服务所做的全部工作——要求平台修改其对流程的管理。如果您需要单例中的上下文,只需使用 Context.getApplicationContext() 来检索进程的全局上下文。
If it is okay for your process to be killed (along with the singleton) immediately after the user leaves its activities, then use a singleton. If you need it to continue running for some duration after that, use a service. If you would like to continue running after the user leaves it, but can live with it not because the user is now on to something else where memory is needed more, then use a singleton.
The decision between these two only comes down to the lifecycle of your app. For this purpose, that is all a service does -- ask the platform to modify its management of your process. If you need a context in a singleton, just use Context.getApplicationContext() to retrieve the global context for your process.