码迷,mamicode.com
首页 > 移动开发 > 详细

【Android基础】-Service组件使用详解

时间:2015-08-29 21:45:39      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:

Service是Android四大组件之一,它与Activity的区别是:它一直在后台运行,没有前台界面。一旦Service被启动起来后,他就跟Activity一样,完全具有自己的生命周期。


一、创建Service,定义一个继承Service的子类

Service中定义了一系列生命周期方法,如下:

  • IBinder onBind(Intent intent):该方法是Service必须实现的方法。该方法返回一个IBinder对象,应用程序可以通过该对象与Service组件通信。
  • void onCreate():当Service第一次被创建时调用该方法。
  • void onDestory():当Service被关闭之前调用该方法。
  • void onStartCommand():该方法的早起版本是onStart()方法,每次调用startService(Intent intent)方法Service都会调用onStartCommand()。
  • boolean onUnbind(Intent intent):当该Service上绑定的所有客户端都断开连接时Service会执行该方法。
  • void onRebind(Intent intent):当onUnbind放回true,客户端调用unbindServie后,在调用bindService时会执行onRebind方法。

二、在AndroidManifest.xml文件中配置Service;
        <service
            android:name="org.iti.tailyou.servicedemo.MService"
            android:exported="false" >
            <intent-filter>
                <action android:name="org.iti.tailyou.MService" >
                </action>
            </intent-filter>
        </service>
配置的时候可以设置<intent-filter>,在过滤器中定义启动Service的action。
  1. 如果配置Service的时候设置了<intent-filter>,默认情况下其他应用程序的组件可以启动该Service,可以通过设置 android:exported="false"来禁止其他应用程序组件启动Service。
  2. 如果配置Service的时候没有设置<intent-filter>,默认情况下其他应用程序的组件不可以启动该Service

三、Service的启动方式
  • 通过Context的startService()方法:通过该方法启动Service,访问者与Service没有关联,即使启动Service的组件退出了,Service依然运行。
  • 通过Context的bindService()方法:通过该方法启动Service,访问者与Service绑定在一起,一旦访问者退出,Service也就终止。

四、Service的生命周期
根据启动Service的方式不同,Service的生命周期也有差异:
  1. startService启动,执行onCreate、onStartCommand方法,Service自己停止或调用者停止,执行onDestory方法。每调用一次startService方法就会执行一次onStartCommand方法。
  2. bindService启动,执行onCreate、onBind方法,调用unbindService或者调用者退出,执行onUnbind、onDestory方法,不管客户端调用多少次bindService方法,都只执行一次onBind方法。
  3. 绑定到一个已经启动的Service,这时候调用unbindService方法,只执行onUnbind方法,再次调用bindService方法,会执行onRebind方法。

五、Service与Thread的区别
  • Thread:程序执行的最小单元,是cpu调度的最小单位,可以用Thread来执行一些异步操作。
  • Service:Service是Android中的一种机制,是Android中在后台运行的组件,和Activity一样,它是在程序的主线中运行。不能在Service中做耗时操作,如果要在Service中执行耗时任务,建议在Service中启动新的线程来执行。
  • 为什么需要Service而不直接用Thread?1、没法在不同的Activity中对同一线程进行控制;2、在Activity中启动线程,Activity退出后,线程依然在运行,但是Activity已经没有线程的引用的了,不能再控制该线程。

六、IntentService
1)为什么要引入IntentService?
  1. 启动Service不会启动新的进程,它与所在的应用程序位于同一进程;
  2. Service也不是一条新的线程,它运行在程序的主线程当中,因此不能在Service中直接处理耗时操作。
2)IntentService实现机制
IntentService使用队列来管理客户端发来的Intent请求,每当客户端通过Intent请求来启动IntentService时,IntentService会将该Intent加入队列,然后开启一条新的worker线程来依次处理队列中的Intent。
3)IntentService的特征
  1. IntentService会创建单独的worker线程来处理所有的Intent请求;
  2. 所有Intent请求处理完后,IntentService会自动停止;
  3. 继承IntentService只需重写onHandleIntent()方法。

版权声明:本文为博主原创文章,未经博主允许不得转载。

【Android基础】-Service组件使用详解

标签:

原文地址:http://blog.csdn.net/tailyou0506/article/details/48089221

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!