读书人

android系列学习【1】service和intent

发布时间: 2012-11-23 22:54:33 作者: rapoo

android系列学习【一】service和intentservice

每天进步一点,许多年后再回首就会发现现在的成就,是以前点滴努力的串联。

?

1.什么是service:

?

A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use. Each service class must have a corresponding?<service>?declaration in its package's?AndroidManifest.xml. Services can be started withContext.startService()?and?Context.bindService().

?

service是一个应用程序组件,用来执行一个长时间运行的操作而不是与用户交互或提供其他应用程序使用的功能。每个service服务必须在AndroidManifest.xml文件中注册?<service>?。可以使用Context.startService()?和

?Context.bindService()方法启动一个sevice。

?

注意:service不是一个单独的进程,也不是一个线程。即service域ui共享一个线程,如果在service中执行耗时操作会导致主线程阻塞。

?

2.什么是intentservice:

?

IntentService is a base class for?Services that handle asynchronous requests (expressed as?Intents) on demand. Clients send requests through?startService(Intent)?calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

?

intentservice是一个service的子类,提供异步请求处理intent。可以使用startService(Intent)启动它;当intentservice启动后,会使用一个work线程异步处理intent,每次只能处理一个intent。

?

3.效果演示:

?

创建service

?

?
比较:sevice处理不会自动开启线程,所以对于耗时操作例如mp3下载等需要开启新线程;intentservice会开启work线程处理,进行异步处理,但每次只有一个intent被处理。

读书人网 >Android

热点推荐