zoukankan      html  css  js  c++  java
  • Service

    转自http://www.cnblogs.com/newcj/archive/2011/05/30/2061370.html

    按运行地点分类:

    类别 区别  优点 缺点   应用
    本地服务(Local) 该服务依附在主进程上,  服务依附在主进程上而不是独立的进程,这样在一定程度上节约了资源,另外Local服务因为是在同一进程因此不需要IPC,也不需要AIDL。相应bindService会方便很多。  主进程被Kill后,服务便会终止。  非常常见的应用如:HTC的音乐播放服务,天天动听音乐播放服务。
    远程服务(Remote 该服务是独立的进程,  服务为独立的进程,对应进程名格式为所在包名加上你指定的android:process字符串。由于是独立的进程,因此在Activity所在进程被Kill的时候,该服务依然在运行,不受其他进程影响,有利于为多个进程提供服务具有较高的灵活性。  该服务是独立的进程,会占用一定资源,并且使用AIDL进行IPC稍微麻烦一点。  一些提供系统服务的Service,这种Service是常驻的。

    其实remote服务还是很少见的,并且一般都是系统服务。

    按运行类型分类:

    类别 区别 应用
    前台服务 会在通知一栏显示 ONGOING 的 Notification, 当服务被终止的时候,通知一栏的 Notification 也会消失,这样对于用户有一定的通知作用。常见的如音乐播放服务。
    后台服务 默认的服务即为后台服务,即不会在通知一栏显示 ONGOING 的 Notification。 当服务被终止的时候,用户是看不到效果的。某些不需要运行或终止提示的服务,如天气更新,日期同步,邮件同步等。

    有同学可能会问,后台服务我们可以自己创建 ONGOING 的 Notification 这样就成为前台服务吗?答案是否定的,前台服务是在做了上述工作之后需要调用 startForeground ( android 2.0 及其以后版本 )或 setForeground (android 2.0 以前的版本)使服务成为 前台服务。这样做的好处在于,当服务被外部强制终止掉的时候,ONGOING 的 Notification 任然会移除掉。

    按使用方式分类:

    类别 区别
    startService 启动的服务 主要用于启动一个服务执行后台任务,不进行通信。停止服务使用stopService
    bindService 启动的服务 该方法启动的服务要进行通信。停止服务使用unbindService
    startService 同时也 bindService 启动的服务 停止服务应同时使用stepService与unbindService

    以上面三种方式启动的服务其生命周期也有区别,将在随后给出。

    2、onStartCommand  

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            return super.onStartCommand(intent, flags, startId);
        }

    onStartCommand()执行后,业务代码马上同时执行,不像IntentService那样以队列排队执行。但是,因为你自己处理每个onStartCommand()方法的调用,你就能够同时执行多个请求。如果你想要这么做的话,那么你就能够给每个请求创建一个新的线程,并且立即运行它们(而不是等待前一个请求完成)。

       注意:onStartCommand()方法必须返回一个整数,这个整数是一个描述了在系统的杀死事件中,系统应该如何继续这个服务的值(虽然你能够修改这个值,但是IntentService处理还是为你提供了默认实现)。从onStartCommand()方法中返回的值必须是以下常量:

    START_NOT_STICKY

      如果系统在onStartCommand()方法返回之后杀死这个服务,那么直到接受到新的Intent对象,这个服务才会被重新创建。这是最安全的选项,用来避免在不需要的时候运行你的服务。

    START_STICKY

      如果系统在onStartCommand()返回后杀死了这个服务,系统就会重新创建这个服务并且调用onStartCommand()方法,但是它不会重新传递最后的Intent对象,系统会用一个null的Intent对象来调用onStartCommand()方法,在这个情况下,除非有一些被发送的Intent对象在等待启动服务。这适用于不执行命令的媒体播放器(或类似的服务),它只是无限期的运行着并等待工作的到来。

    START_REDELIVER_INTENT

      如果系统在onStartCommand()方法返回后,系统就会重新创建了这个服务,并且用发送给这个服务的最后的Intent对象调用了onStartCommand()方法。任意等待中的Intent对象会依次被发送。这适用于那些应该立即恢复正在执行的工作的服务,如下载文件。

    IntentService的实现

    1   @Override
    2     public int onStartCommand(Intent intent, int flags, int startId) {
    3         onStart(intent, startId);
    4         return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    5     }
    View Code

    START_STICKY和 START_STICKY:当进程被杀死后onDestroy()是不会被执行的!

    START_REDELIVER_INTENT :当进程被杀死后onDestroy()会被执行!

    注意:以上行为只有在System kill event的情况下有效,stopSelf和stopService都不会过问onStartCommand的返回状态。

    3、Service的生命周期

    1). 被启动的服务的生命周期:如果一个Service被某个Activity 调用 Context.startService 方法启动,那么不管是否有Activity使用bindService绑定或unbindService解除绑定到该Service,该Service都在后台运行。如果一个Service被startService 方法多次启动,那么onCreate方法只会调用一次,onStart将会被调用多次(对应调用startService的次数),并且系统只会创建Service的一个实例(因此你应该知道只需要一次stopService调用)。该Service将会一直在后台运行,而不管对应程序的Activity是否在运行,直到被调用stopService,或自身的stopSelf方法。当然如果系统资源不足,android系统也可能结束服务。

    2). 被绑定的服务的生命周期:如果一个Service被某个Activity 调用 Context.bindService 方法绑定启动,不管调用 bindService 调用几次,onCreate方法都只会调用一次,同时onStart方法始终不会被调用。当连接建立之后,Service将会一直运行,除非调用Context.unbindService 断开连接或者之前调用bindService 的 Context 不存在了(如Activity被finish的时候),系统将会自动停止Service,对应onDestroy将被调用。

    3). 被启动又被绑定的服务的生命周期:如果一个Service又被启动又被绑定,则该Service将会一直在后台运行。并且不管如何调用,onCreate始终只会调用一次,对应startService调用多少次,Service的onStart便会调用多少次。调用unbindService将不会停止Service,而必须调用 stopService 或 Service的 stopSelf 来停止服务。

    4). 当服务被停止时清除服务:当一个Service被终止(1、调用stopService;2、调用stopSelf;3、不再有绑定的连接(没有被启动))时,onDestroy方法将会被调用,在这里你应当做一些清除工作,如停止在Service中创建并运行的线程。

    特别注意:

    1、你应当知道在调用 bindService 绑定到Service的时候,你就应当保证在某处调用 unbindService 解除绑定(尽管 Activity 被 finish 的时候绑定会自      动解除,并且Service会自动停止);

    2、你应当注意 使用 startService 启动服务之后,一定要使用 stopService停止服务,不管你是否使用bindService; 

    3、同时使用 startService 与 bindService 要注意到,Service 的终止,需要unbindService与stopService同时调用,才能终止 Service,不管 startService 与 bindService 的调用顺序,如果先调用 unbindService 此时服务不会自动终止,再调用 stopService 之后服务才会停止,如果先调用 stopService 此时服务也不会终止,而再调用 unbindService 或者 之前调用 bindService 的 Context 不存在了(如Activity 被 finish 的时候)之后服务才会自动停止;

    4、当在旋转手机屏幕的时候,当手机屏幕在“横”“竖”变换时,此时如果你的 Activity 如果会自动旋转的话,旋转其实是 Activity 的重新创建,因此旋转之前的使用 bindService 建立的连接便会断开(Context 不存在了),对应服务的生命周期与上述相同。

    5、在 sdk 2.0 及其以后的版本中,对应的 onStart 已经被否决变为了 onStartCommand,不过之前的 onStart 任然有效。这意味着,如果你开发的应用程序用的 sdk 为 2.0 及其以后的版本,那么你应当使用 onStartCommand 而不是 onStart。  

    4、startService 启动服务

    想要用 startService  启动服务,不管Local 还是 Remote 我们需要做的工作都是一样简单。当然要记得在 Androidmanifest.xml 中注册 service。

    根据上面的生命周期,我们便会给出 Service 中的代码框架:

     1 package com.newcj.test;
     2  
     3 import android.app.Service;
     4 import android.content.Intent;
     5 import android.os.IBinder;
     6  
     7 public class LocalService1 extends Service {
     8  
     9     /**
    10      * onBind 是 Service 的虚方法,因此我们不得不实现它。
    11      * 返回 null,表示客服端不能建立到此服务的连接。
    12      */
    13     @Override
    14     public IBinder onBind(Intent intent) {
    15         return null;
    16     }
    17      
    18     @Override
    19     public void onCreate() {
    20         super.onCreate();
    21     }
    22      
    23     @Override
    24     public void onStart(Intent intent, int startId) {
    25         super.onStart(intent, startId);
    26     }
    27      
    28     @Override
    29     public void onDestroy() {
    30         super.onDestroy();
    31     }
    32  
    33 }
    View Code

        对应生命周期系统回调函数上面已经说明,在对应地方加上适当的代码即可。下面是启动与停止 Service 的代码: 

    1 // 启动一个 Activity
    2 startActivity(new Intent(this, LocalService1.class));
    3 ...
    4 // 停止一个 Activity
    5 stopService(new Intent(this, LocalService1.class));
    View Code

        对应的 Intent 为标志服务类的 Intent。

    5、Local 与 Remote 服务绑定

    同样记得在 Androidmanifest.xml 中注册 service

    1). Local 服务绑定:Local 服务的绑定较简单,首先在 Service 中我们需要实现 Service 的抽象方法 onBind,并返回一个实现 IBinder 接口的对象。

    Service 中的代码: 

     1 package com.newcj.test;
     2  
     3 import android.app.Service;
     4 import android.content.Intent;
     5 import android.os.Binder;
     6 import android.os.IBinder;
     7  
     8 public class LocalService extends Service {
     9  
    10     /**
    11      * 在 Local Service 中我们直接继承 Binder 而不是 IBinder,因为 Binder 实现了 IBinder 接口,这样我们可以少做很多工作。
    12      * @author newcj
    13      */
    14     public class SimpleBinder extends Binder{
    15         /**
    16          * 获取 Service 实例
    17          * @return
    18          */
    19         public LocalService getService(){
    20             return LocalService.this;
    21         }
    22          
    23         public int add(int a, int b){
    24             return a + b;
    25         }
    26     }
    27      
    28     public SimpleBinder sBinder;
    29      
    30     @Override
    31     public void onCreate() {
    32         super.onCreate();
    33         // 创建 SimpleBinder
    34         sBinder = new SimpleBinder();
    35     }
    36      
    37     @Override
    38     public IBinder onBind(Intent intent) {
    39         // 返回 SimpleBinder 对象
    40         return sBinder;
    41     }
    42  
    43 }
    View Code

    上面的代码关键之处,在于 onBind(Intent) 这个方法 返回了一个实现了 IBinder 接口的对象,这个对象将用于绑定Service 的 Activity 与 Local Service 通信。下面是 Activity 中的代码:

     1 package com.newcj.test;
     2  
     3 import android.app.Activity;
     4 import android.content.ComponentName;
     5 import android.content.Context;
     6 import android.content.Intent;
     7 import android.content.ServiceConnection;
     8 import android.os.Bundle;
     9 import android.os.IBinder;
    10 import android.util.Log;
    11 import android.view.View;
    12 import android.view.View.OnClickListener;
    13  
    14 public class Main extends Activity {
    15     private final static String TAG = "SERVICE_TEST";
    16     private ServiceConnection sc;
    17     private boolean isBind;
    18  
    19     @Override
    20     public void onCreate(Bundle savedInstanceState) {
    21         super.onCreate(savedInstanceState);
    22         setContentView(R.layout.main);
    23         sc = new ServiceConnection() {
    24              
    25             @Override
    26             public void onServiceDisconnected(ComponentName name) {
    27  
    28             }
    29              
    30             @Override
    31             public void onServiceConnected(ComponentName name, IBinder service) {
    32                 LocalService.SimpleBinder sBinder = (LocalService.SimpleBinder)service;
    33                 Log.v(TAG, "3 + 5 = " + sBinder.add(3, 5));
    34                 Log.v(TAG, sBinder.getService().toString());
    35             }
    36         };
    37         findViewById(R.id.btnBind).setOnClickListener(new OnClickListener() {
    38              
    39             @Override
    40             public void onClick(View v) {
    41                 bindService(new Intent(Main.this, LocalService.class), sc, Context.BIND_AUTO_CREATE);
    42                 isBind = true;
    43             }
    44         });
    45         findViewById(R.id.btnUnbind).setOnClickListener(new OnClickListener() {
    46              
    47             @Override
    48             public void onClick(View v) {
    49                 if(isBind){
    50                     unbindService(sc);
    51                     isBind = false;
    52                 }
    53             }
    54         });
    55     }
    56 }
    View Code

    在 Activity 中,我们通过 ServiceConnection 接口来取得建立连接 与 连接意外丢失的回调。bindService有三个参数,第一个是用于区分 Service 的Intent 与 startService 中的 Intent 一致,第二个是实现了 ServiceConnection 接口的对象,最后一个是 flag 标志位。有两个flag,BIND_DEBUG_UNBIND 与 BIND_AUTO_CREATE,前者用于调试(详细内容可以查看javadoc 上面描述的很清楚),后者默认使用。unbindService 解除绑定,参数则为之前创建的 ServiceConnection 接口对象。另外,多次调用 unbindService 来释放相同的连接会抛出异常,因此我创建了一个 boolean 变量来判断是否 unbindService 已经被调用过。

    运行结果:

    2). Remote 服务绑定:Remote 的服务绑定由于服务是在另外一个进程,因此需要用到 android 的 IPC 机制。这将又是一个很长的话题,因此,我打算写另外一篇 android 的 IPC 机制分析 ,并在其中进行详述,然后在这里更新链接,敬请关注。 

    特别注意:

    1、Service.onBind如果返回null,则调用 bindService 会启动 Service,但不会连接上 Service,因此 ServiceConnection.onServiceConnected 不会被调用,但你任然需要使用 unbindService 函数断开它,这样 Service 才会停止。

     6、创建前台服务

    前台服务的优点上面已经说明,但设置服务为前台服务,我们需要注意在 sdk 2.0 及其以后版本使用的方法是 startForeground 与 stopForeground,之前版本使用的是 setForeground ,因此如果你应用程序的最低运行环境要求是 2.0,那么这里可以直接运用新方法,如果运行环境是2.0以下,那么为了保证向后兼容性,这里必须使用反射技术来调用新方法。

    下面是我仿照 ApiDemos 重新敲的代码,对某些地方进行了修改,因此更具有说明性:

      1 package com.newcj.test;
      2  
      3 import java.lang.reflect.InvocationTargetException;
      4 import java.lang.reflect.Method;
      5  
      6 import android.app.Notification;
      7 import android.app.NotificationManager;
      8 import android.app.PendingIntent;
      9 import android.app.Service;
     10 import android.content.Context;
     11 import android.content.Intent;
     12 import android.os.IBinder;
     13  
     14 public class ForegroundService extends Service {
     15  
     16     private static final Class[] mStartForegroundSignature = new Class[] {
     17         int.class, Notification.class};
     18     private static final Class[] mStopForegroundSignature = new Class[] {
     19         boolean.class};
     20     private NotificationManager mNM;
     21     private Method mStartForeground;
     22     private Method mStopForeground;
     23     private Object[] mStartForegroundArgs = new Object[2];
     24     private Object[] mStopForegroundArgs = new Object[1];
     25      
     26     @Override
     27     public IBinder onBind(Intent intent) {
     28         return null;
     29     }
     30      
     31     @Override
     32     public void onCreate() {
     33         super.onCreate();
     34         mNM = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
     35         try {
     36             mStartForeground = ForegroundService.class.getMethod("startForeground", mStartForegroundSignature);
     37             mStopForeground = ForegroundService.class.getMethod("stopForeground", mStopForegroundSignature);
     38         } catch (NoSuchMethodException e) {
     39             mStartForeground = mStopForeground = null;
     40         }
     41          // 我们并不需要为 notification.flags 设置 FLAG_ONGOING_EVENT,因为
     42          // 前台服务的 notification.flags 总是默认包含了那个标志位
     43         Notification notification = new Notification(R.drawable.icon, "Foreground Service Started.",
     44                 System.currentTimeMillis());
     45         PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
     46                 new Intent(this, Main.class), 0);
     47         notification.setLatestEventInfo(this, "Foreground Service",
     48                 "Foreground Service Started.", contentIntent);
     49         // 注意使用  startForeground ,id 为 0 将不会显示 notification
     50         startForegroundCompat(1, notification);
     51     }
     52      
     53     @Override
     54     public void onDestroy() {
     55         super.onDestroy();
     56         stopForegroundCompat(1);
     57     }
     58      
     59     // 以兼容性方式开始前台服务
     60     private void startForegroundCompat(int id, Notification n){
     61         if(mStartForeground != null){
     62             mStartForegroundArgs[0] = id;
     63             mStartForegroundArgs[1] = n;
     64              
     65             try {
     66                 mStartForeground.invoke(this, mStartForegroundArgs);
     67             } catch (IllegalArgumentException e) {
     68                 e.printStackTrace();
     69             } catch (IllegalAccessException e) {
     70                 e.printStackTrace();
     71             } catch (InvocationTargetException e) {
     72                 e.printStackTrace();
     73             }
     74              
     75             return;
     76         }
     77         setForeground(true);
     78         mNM.notify(id, n);
     79     }
     80      
     81     // 以兼容性方式停止前台服务
     82     private void stopForegroundCompat(int id){
     83         if(mStopForeground != null){
     84             mStopForegroundArgs[0] = Boolean.TRUE;
     85              
     86             try {
     87                 mStopForeground.invoke(this, mStopForegroundArgs);
     88             } catch (IllegalArgumentException e) {
     89                 e.printStackTrace();
     90             } catch (IllegalAccessException e) {
     91                 e.printStackTrace();
     92             } catch (InvocationTargetException e) {
     93                 e.printStackTrace();
     94             }
     95             return;
     96         }
     97          
     98         //  在 setForeground 之前调用 cancel,因为我们有可能在取消前台服务之后
     99         //  的那一瞬间被kill掉。这个时候 notification 便永远不会从通知一栏移除
    100         mNM.cancel(id);
    101         setForeground(false);
    102     }
    103  
    104 }
    View Code

     特别注意:

      1、使用 startForeground ,如果 id 为 0 ,那么 notification 将不会显示。 

    7、在什么情况下使用 startService 或 bindService 或 同时使用startService 和 bindService

    如果你只是想要启动一个后台服务长期进行某项任务那么使用 startService 便可以了。如果你想要与正在运行的 Service 取得联系,那么有两种方法,一种是使用 broadcast ,另外是使用 bindService ,前者的缺点是如果交流较为频繁,容易造成性能上的问题,并且 BroadcastReceiver 本身执行代码的时间是很短的(也许执行到一半,后面的代码便不会执行),而后者则没有这些问题,因此我们肯定选择使用 bindService(这个时候你便同时在使用 startService 和 bindService 了,这在 Activity 中更新 Service 的某些运行状态是相当有用的)。另外如果你的服务只是公开一个远程接口,供连接上的客服端(android 的 Service 是C/S架构)远程调用执行方法。这个时候你可以不让服务一开始就运行,而只用 bindService ,这样在第一次 bindService 的时候才会创建服务的实例运行它,这会节约很多系统资源,特别是如果你的服务是Remote Service,那么该效果会越明显(当然在 Service 创建的时候会花去一定时间,你应当注意到这点)。

    8、在 AndroidManifest.xml 里 Service 元素的常见选项
          android:name  -------------  服务类名
          android:label  --------------  服务的名字,如果此项不设置,那么默认显示的服务名则为类名
          android:icon  --------------  服务的图标
          android:permission  -------  申明此服务的权限,这意味着只有提供了该权限的应用才能控制或连接此服务
          android:process  ----------  表示该服务是否运行在另外一个进程,如果设置了此项,那么将会在包名后面加上这段字符串表示另一进程的名字
          android:enabled  ----------  如果此项设置为 true,那么 Service 将会默认被系统启动,不设置默认此项为 false
          android:exported  ---------  表示该服务是否能够被其他应用程序所控制或连接,不设置默认此项为 false

  • 相关阅读:
    Linux Systemcall By INT 0x80、Llinux Kernel Debug Based On Sourcecode
    ELF(Executable and Linkable Format)
    Linux文件权限;ACL;Setuid、Setgid、Stick bit特殊权限;sudo提权
    Linux System Calls Hooking Method Summary
    GCC、Makefile编程学习
    Linux Process/Thread Creation、Linux Process Principle、sys_fork、sys_execve、glibc fork/execve api sourcecode
    Linux中断技术、门描述符、IDT(中断描述符表)、异常控制技术总结归类
    浅议SNMP安全、SNMP协议、网络管理学习
    DNS安全浅议、域名A记录(ANAME),MX记录,CNAME记录
    RIP、OSPF、BGP、动态路由选路协议、自治域AS
  • 原文地址:https://www.cnblogs.com/mingfeng002/p/3421340.html
Copyright © 2011-2022 走看看