安卓:当使用服务VS辛格尔顿?格尔、VS

2023-09-03 20:42:44 作者:wǒ荟娶o祢﹎

我是很新的Andr​​oid开发。

I'm quite new to Android development.

在仅仅使用一个简单的单例类的一个好主意,以创建一个Android服务呢?

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.

推荐答案

如果它是好的,为你的过程中被杀死(连同单),然后使用一个单例。如果你需要它继续后运行一段时间,使用服务。如果你想继续在用户离开后运行,但可以忍受它不会因为用户现在到别的东西,其中的内存需要更多的,然后使用一个单例。

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.

这两者之间的决定的只有的归结为你的应用程序的生命周期。为了这个目的,那就是所有的服务也 - 问这个平台来修改流程的管理。如果你需要一个上下文单身,只是使用Context.getApplicationContext()来检索全球范围内为您处理。

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.