ITeye博客

Service学习

bolutes · 2011-08-29 00:12 · Markdown

什么是Service
有些用时比较长的操作我们希望他在后台运行,不耽误我们当前的操作。这就引入了Service的概念。常见的比如:访问网络,文件IO操作,大数据的数据库任务,播放音乐等。
Service在后台运行,并不用户进行交互。在默认的情况下,Service运行在应用程序进程的主线程中,如果要在Service中处理一些网络连接等耗时的操作,那么应当将这些任务放到单独的线程中处理,避免阻塞用户界面

What is a service?

API解释:
Most confusion about the Service class actually revolves around what it is not:
A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.
A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).

启动服务,不用多线程,界面是否会阻塞 Yes

启动服务后,按Home键,服务是否还在运行 Yes

启动服务后,退出进程,是否服务还会运行 No

当按home键的时候程序正常执行,但是当按back键的时候出现ANR错误:

这也就证明了service是在主线程里面执行的,而在service里面新建一个线程就可以正常的执行。

当单击StopService按钮时,在主线程里面的会出现按钮不可点击,出现ANR错误。当以一个线程启动的时候,可以正常停止服务,但是已经启动的线程还是继续在运行。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。