android 使用单例还是service?

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


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
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值