您的位置:首页 > 其它

Service与线程和进程的关系

2014-11-06 20:46 232 查看
一直搞不懂Service到底和进程线程的关系,因为这里我曲解了一个概念,就是Activity与主线程之间的关系,Activity在主线程中,但是Activity并不代表主线程,换句话来说,Activity的Destroy并不会导致主线程的销毁。

官方API Guid上有这样一段话:

A service runs in the main thread of its hosting process—the service does not create
its own thread and does not run in a separate process (unless you specify
otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work.By using a separate thread, you will reduce
the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.


看到有些中文书中对于main thread的翻译是主UI线程,包括我看到的书也是这样写的,所以导致了我的误解,main thread就是主线程。Service在默认的情况下也在这个线程中,Activity也在,而Activity的Destroy并不会导致主线程出现destroy,在startService的情况下,自然也就不会导致Service的销毁了,Service还好好的运行在主线程中。(这个可以自己写一个demo,对Activity调用finish,会发现Service还在运行,当然不要把finish和系统中的任务管理器混淆,任务管理器就直接把这个主进程都关了)

之前并未理解,Component的概念,现在可以想象成一张白纸上面的几个块,每一个块就是一个组件,主线程的作用,就是在这张白纸上面以一定的规则巡逻,activity的destroy自然不会影响到这张白纸,Service仍然会被巡逻到(运行到)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: