浅谈Service

1.Start一个Service的状态是:首次Start:onCreate--》OnStartCommand--》OnStart(已废弃)

                                              非首次Start:OnStartCommand--》OnStart(已废弃)

    Stop一个Service的状态是:OnDestory()

2.Service与主线程是处于同一个线程中;

 

 

Should you use a service or a thread?
A service is simply a component that can run in the background even when the user is not interacting with your application. Thus, you should create a service only if that is what you need.

If you need to perform work outside your main thread, but only while the user is interacting with your application, then you should probably instead create a new thread and not a service. For example, if you want to play some music, but only while your activity is running, you might create a thread in onCreate(), start running it in onStart(), then stop it in onStop(). Also consider using AsyncTask or HandlerThread, instead of the traditional Thread class. See the Processes and Threading document for more information about threads.

Remember that if you do use a service, it still runs in your application's main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations.

译文:
什么时候使用Service还是线程?
service是一个可以在后台运行的组件,即使当用户不在与应用程序交互。因此,当你需要时,你可以可以创建一个service;

但是,当用户与程序交互是,而需要在主线程之外执行一些操作,这时候应该创建一个新线程而不是一个service。

举个例子,播放音乐,当只是需要在activity运行时播放,这时候可以在activity的onCreate()方法中创建一个线程,播放的方法放在activity的onStart()中,停止的方法放在activity的onStop()中。当然在这里还可以考虑使用AsyncTask 或HandlerThread,而不是简单的使用一个线程类。(注:异步任务和HandlerThread都是新起一个线程完成一些任务)

记住:线程模式是运行在程序的主线程中,所以,在需要完成一系列或阻塞操作时,应该在service创建一个新的线程。
还有一个IntentService:
This is a subclass of Service that uses a worker thread to handle all start requests, one at a time. This is the best option if you don't require that your service handle multiple requests simultaneously. All you need to do is implement onHandleIntent(), which receives the intent for each start request so you can do the background work.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值