Service是Android中四大组件之一,在Android开发中起到非常重要的作用,先来看一下官方对Service的定义:

Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.

翻译过来就是:Service(服务)是一个没有用户界面的在后台运行执行耗时操作的应用组件。其他应用组件能够启动Service,并且当用户切换到另外的应用场景,Service将持续在后台运行。另外,一个组件能够绑定到一个service与之交互(IPC机制),例如,一个service可能会处理网络操作,播放音乐,操作文件I/O或者与内容提供者(content provider)交互,所有这些活动都是在后台进行。

Service有两种状态,“启动的”和“绑定”

StartedA service is "started" when an application component (such as an activity) starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. Usually, a started service performs a single operation and does not return a result to the caller. For example, it might download or upload a file over the network. When the operation is done, the service should stop itself.Bound

A service is "bound" when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.

通过startService()启动的服务处于“启动的”状态,一旦启动,service就在后台运行,即使启动它的应用组件已经被销毁了。通常started状态的service执行单任务并且不返回任何结果给启动者。比如当下载或上传一个文件,当这项操作完成时,service应该停止它本身。

还有一种“绑定”状态的service,通过调用bindService()来启动,一个绑定的service提供一个允许组件与service交互的接口,可以发送请求、获取返回结果,还可以通过夸进程通信来交互(IPC)。绑定的service只有当应用组件绑定后才能运行,多个组件可以绑定一个service,当调用unbind()方法时,这个service就会被销毁了。

另外,在官方的说明文档中还有一个警告:

Caution: 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.

意思是service与activity一样都存在与当前进程的主线程中,所以,一些阻塞UI的操作,比如耗时操作不能放在service里进行,比如另外开启一个线程来处理诸如网络请求的耗时操作。如果在service里进行一些耗CPU和耗时操作,可能会引发ANR警告,这时应用会弹出是强制关闭还是等待的对话框。所以,对service的理解就是和activity平级的,只不过是看不见的,在后台运行的一个组件,这也是为什么和activity同被说为Android的基本组件。

Service生命周期中的一些方法:

通过这个图可以看到,两种启动service的方式以及他们的生命周期,bind service的不同之处在于当绑定的组件销毁后,对应的service也就被kill了。service的声明周期相比与activity的简单了许多,只要好好理解两种启动service方式的异同就行。

service生命周期也涉及一些回调方法,这些方法都不用调用父类方法,具体如下:

  1. <span style="font-family:Comic Sans MS;font-size:18px;">public class ExampleService extends Service {
  2. int mStartMode;       // indicates how to behave if the service is killed
  3. IBinder mBinder;      // interface for clients that bind
  4. boolean mAllowRebind; // indicates whether onRebind should be used
  5. @Override
  6. public void onCreate() {
  7. // The service is being created
  8. }
  9. @Override
  10. public int onStartCommand(Intent intent, int flags, int startId) {
  11. // The service is starting, due to a call to startService()
  12. return mStartMode;
  13. }
  14. @Override
  15. public IBinder onBind(Intent intent) {
  16. // A client is binding to the service with bindService()
  17. return mBinder;
  18. }
  19. @Override
  20. public boolean onUnbind(Intent intent) {
  21. // All clients have unbound with unbindService()
  22. return mAllowRebind;
  23. }
  24. @Override
  25. public void onRebind(Intent intent) {
  26. // A client is binding to the service with bindService(),
  27. // after onUnbind() has already been called
  28. }
  29. @Override
  30. public void onDestroy() {
  31. // The service is no longer used and is being destroyed
  32. }
  33. }</span>

关于Service生命周期还有一张比较易懂的图(来源于网络)

另外,这里要说明Service的一个子类,IntentService,首先看下官方文档的说明:

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.

IntentService使用队列的方式将请求的Intent加入队列,然后开启一个worker thread(线程)来处理队列中的Intent,对于异步的startService请求,IntentService会处理完成一个之后再处理第二个,每一个请求都会在一个单独的worker thread中处理,不会阻塞应用程序的主线程,这里就给我们提供了一个思路,如果有耗时的操作与其在Service里面开启新线程还不如使用IntentService来处理耗时操作。而在一般的继承Service里面如果要进行耗时操作就必须另开线程,但是使用IntentService就可以直接在里面进行耗时操作,因为默认实现了一个worker thread。对于异步的startService请求,IntentService会处理完成一个之后再处理第二个。

  1. <span style="font-family:Comic Sans MS;font-size:18px;color:#222222;">public class HelloIntentService extends IntentService {
  2. /**
  3. * A constructor is required, and must call the super IntentService(String)
  4. * constructor with a name for the worker thread.
  5. */
  6. public HelloIntentService() {
  7. super("HelloIntentService");
  8. }
  9. /**
  10. * The IntentService calls this method from the default worker thread with
  11. * the intent that started the service. When this method returns, IntentService
  12. * stops the service, as appropriate.
  13. */
  14. @Override
  15. protected void onHandleIntent(Intent intent) {
  16. // Normally we would do some work here, like download a file.
  17. // For our sample, we just sleep for 5 seconds.
  18. long endTime = System.currentTimeMillis() + 5*1000;
  19. while (System.currentTimeMillis() < endTime) {
  20. synchronized (this) {
  21. try {
  22. wait(endTime - System.currentTimeMillis());
  23. } catch (Exception e) {
  24. }
  25. }
  26. }
  27. }
  28. }</span>

关于停止Service,如果service是非绑定的,最终当任务完成时,为了节省系统资源,一定要停止service,可以通过stopSelf()来停止,也可以在其他组件中通过stopService()来停止,绑定的service可以通过onUnBind()来停止service。

service and intentservice的更多相关文章

  1. 多线程、Service与IntentService的比较

    资料摘自网络(侵删)     Service Thread IntentService AsyncTask When to use ? Task with no UI, but shouldn't b ...

  2. Android之Service与IntentService的比较

    Android之Service与IntentService的比较  不知道大家有没有和我一样,以前做项目或者练习的时候一直都是用Service来处理后台耗时操作,却很少注意到还有个IntentServ ...

  3. Android Service 与 IntentService

    Service 中的耗时操作必须 在 Thread中进行: IntentService 则直接在 onHandleIntent()方法中进行

  4. [Android] Service和IntentService中显示Toast的区别

    1. 表象     Service中可以正常显示Toast,IntentService中不能正常显示Toast,在2.3系统上,不显示toast,在4.3系统上,toast显示,但是不会消失. 2. ...

  5. Android查缺补漏--Service和IntentService

    Service的运行不依赖界面,即使程序被切换到后台,Service仍然能够保持正常运行.当某个应用程序进程被杀掉时,所有依赖于该进程的Service也会停止运行. Service 分为启动状态和绑定 ...

  6. Android Service、IntentService,Service和组件间通信

    Service组件 Service 和Activity 一样同为Android 的四大组件之一,并且他们都有各自的生命周期,要想掌握Service 的用法,那就要了解Service 的生命周期有哪些方 ...

  7. Service 和 IntentService的区别;

    Srevice不是在子线程,在Srevice中做耗时操作一样ANR,然后我们就会用到IntentService,IntentSrevice不但擅长做耗时操作,还有一个特点,用完即走: 在Srevice ...

  8. android拾遗——Android之Service与IntentService的比较

    不知道大家有没有和我一样,以前做项目或者练习的时候一直都是用Service来处理后台耗时操作,却很少注意到还有个IntentService,前段时间准备面试的时候看到了一篇关于IntentServic ...

  9. Android中Service与IntentService的使用比较

    不知道大家有没有和我一样,以前做项目或者练习的时候一直都是用Service来处理后台耗时操作,却很少注意到还有个IntentService,前段时间准备面试的时候看到了一篇关于IntentServic ...

随机推荐

  1. Android导航栏ActionBar的具体分析

    尊重原创:http://blog.csdn.net/yuanzeyao/article/details/39378825 关于ActionBar,相信大家并不陌生,可是真正能够熟练使用的也不是许多,这 ...

  2. WebSite 文件上传Demo

    知识点: 1 <!--上传文件时:        1.必须使用Post方式来提交数据        2.必须设置表单的enctype属性        3.必须在表单中包含文件域.input t ...

  3. 搭建Myeclipse下Java Web开发环境

    1.准备 先下载软件:Myeclipse:http://www.xiazaiba.com/html/23858.html tomcat:http://files.cnblogs.com/files/l ...

  4. UVa1586 Molar mass

    #include <stdio.h> int GetQuantity(char* q, char** p){    int quantity = 0;    while (*q & ...

  5. 10247 - Complete Tree Labeling(递推高精度)

    Problem B Complete Tree Labeling! Input: standard input Output: standard output Time Limit: 45 secon ...

  6. java时间验证工具

    可以验证2014-02-21这种错误

  7. ISO14443 ISO15693 ISO18000

    [提要]射频标签的通信标准是标签芯片设计的依据,目前国际上与RFID相关的通信标准主要有:ISO/IEC 18000标准(包括7个部分,涉及125KHz, 13.56MHz, 433MHz, 860- ...

  8. 讲讲金融业务(一)--自助结算终端POS

    之前在群里和大家聊天的时候,发现好多人对银行业务比較感兴趣,或许是由于大家对银行不了解,以为非常神奇的样子.全部,从这周開始我打算把我肚子里的墨水慢慢地倒出来,和大家分享分享.   在技术还不发达的时 ...

  9. srm 534

    250 Description 给你一个1*n的棋盘.两人轮流行动,每一个人能够把"o"向右移动到空格子.或者跨越连续两个"o"到空格子. 一个"o& ...

  10. uva Stacks of Flapjacks

                                                     Stacks of Flapjacks  题目链接:Click Here~ 题目描写叙述:     ...