android 使用单例还是service?

来源:互联网 发布:手机免费网络电话软件 编辑:程序博客网 时间:2024/06/05 05:49

stackover看到的回答,挺不错的。


26down votefavorite
11

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.


1 Answer


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.

4 
The last sentence of the first paragraph is a bit confusing. Can you rephrase it a bit? –  chakrit Aug 25 '10 at 17:28
 
I think it means: Use a singleton when you would prefer the process to continue running after the user leaves it, but only if memory is not needed more somewhere else. –  mparaz Jun 9 '12 at 6:51
1 
So, for your example of the information feed downloads, I guess if those feeds were buffered on the Internet server that provides them, so that you could catch up whenever the user returned to your app, or if you only cared about processing new items from the feed, and not about displaying an uninterrupted history, then you would be OK with a singleton, but if you needed your app to keep monitoring the feed while the user was doing something else, you would then want a service. Just trying to make this a little more real...interesting question. –  Carl May 16 '13 at 23:43



http://stackoverflow.com/questions/3567667/android-when-to-use-service-vs-singleton

0 0