安卓服务Service详解

来源:互联网 发布:php工程师中国 编辑:程序博客网 时间:2024/05/16 16:14

service(服务)是安卓中的四大组件之一,它通常用作在后台处理耗时的逻辑,与Activity一样,它存在自己的生命周期,也需要在清单文件中配置相关信息,本博客将对Service的各个知识点进行详细讲解。



一Service的基本用法:

1使用本地服务

1)服务的启动方式

1通过Context的startService()方法启动服务:以该方法启动的服务,开启该服务的应用组件(如Activity)与该Service不存在关联关系,即使开启该服务的Activity被销毁,Service任能够一直在后台运行。通常,开启的服务执行一个单独的操作且不需向调用者返回一个结果。比如,可能从网络进行下载或者上传一个文件。当任务完成,服务就该自我停止。使用服务于使用Activity非常相似,都是先继承其对应的基类,然后重写其中重要的方法,这些方法就是关于其生命周期回调的方法。代码如下所示:

[java] view plain copy
  1. public class MyService extends Service {  
  2.   
  3.     public static final String TAG = "MyService";  
  4.   
  5.     @Override  
  6.     public void onCreate() {  
  7.         super.onCreate();  
  8.         Log.d(TAG, "onCreate() executed");  
  9.     }  
  10.   
  11.     @Override  
  12.     public int onStartCommand(Intent intent, int flags, int startId) {  
  13.         Log.d(TAG, "onStartCommand() executed");  
  14.         return super.onStartCommand(intent, flags, startId);  
  15.     }  
  16.       
  17.     @Override  
  18.     public void onDestroy() {  
  19.         super.onDestroy();  
  20.         Log.d(TAG, "onDestroy() executed");  
  21.     }  
  22.   
  23.     @Override  
  24.     public IBinder onBind(Intent intent) {  
  25.         return null;  
  26.     }  
  27.   
  28. }  
然后再Activity中使用
[java] view plain copy
  1. Intent startIntent = new Intent(this, MyService.class);    
  2. startService(startIntent);   
即可开启该服务,程序运行结果如下:


从程序的运行结果来看,可以知道当启动一个Service的时候,会调用该Service中的onCreate()和onStartCommand()方法。

当我们在次点击启动服务的按钮,程序运行结果如下:


可以看到,此时只输出onStartCommand() executed。这说明此时只执行了onStartCommand()方法,而未执行onCreate(),这说明onCreate()方法只会在Service第一次被创建的时候调用,如果当前Service已经被创建过了,则即使多次调用startService()方法,onCreate()方法都不会再执行,这一点非常类似数据库操作中的open一个数据库。

当然上述的例子仅仅只是为了说明上述知识点,因为Service中的代码也仅仅只是打印出log而已,而事实上Service的使用是为了处理一些耗时操作的,如网络请求,文件上传与下载,但都是重写其某个生命周期函数,如onStart(Intent intent, int startId),onDestroy()在这些函数中完成自己的业务逻辑的处理,下面的代码是使用服务来进行网络通信的一个例子。

[java] view plain copy
  1. public class GetMsgService extends Service {  
  2.     private Client client;  
  3.     private boolean isStart;  
  4.     private SharePreferenceUserInfoUtil util;  
  5.     private ClientInputThread cit;  
  6.     @Override  
  7.     public IBinder onBind(Intent intent) {  
  8.         // TODO Auto-generated method stub  
  9.         return null;  
  10.     }  
  11.   
  12.     @Override  
  13.     public void onCreate() {  
  14.         // TODO Auto-generated method stub  
  15.         super.onCreate();  
  16.         client=((MyApplication) getApplication()).getClient();  
  17.     }  
  18.   
  19.     @Override  
  20.     public void onStart(Intent intent, int startId) {  
  21.         // TODO Auto-generated method stub  
  22.         super.onStart(intent, startId);  
  23.         util = new SharePreferenceUserInfoUtil(getApplicationContext(),  
  24.                 Constants.SAVE_USER);  
  25.          
  26.         new Thread(){  
  27.                public void run()  
  28.                {  
  29.                     try {  
  30.                         isStart=client.create();  
  31.                     } catch (UnknownHostException e) {  
  32.                         // TODO Auto-generated catch block  
  33.                         e.printStackTrace();  
  34.                     } catch (IOException e) {  
  35.                         // TODO Auto-generated catch block  
  36.                         e.printStackTrace();  
  37.                     }  
  38.             //在服务中接受来自服务器端的消息,然后通过广播的形式传递给相应的Activity处理。接受服务器端的消息一般在  
  39.             //服务中,因为服务可以在后台一直运行  
  40.                                       
  41.                 if(isStart)  
  42.                 {  
  43.                     cit=client.getClientInputThread();  
  44.                     if(cit!=null)  
  45.                     {  
  46.                         cit.setMessageListener(new MessageListener() {  
  47.                               
  48.                             public void getMessage(TransportObject msg) {  
  49.                                   
  50.                                 if(msg!=null&&msg instanceof TransportObject)  
  51.                                 {  
  52.                                     //通过广播向Activity传递消息  
  53.                                     Intent intent=new Intent();  
  54.                                     intent.setAction(Constants.ACTION_MSG);  
  55.                                     intent.putExtra(Constants.MSG, msg);  
  56.                                     sendBroadcast(intent);  
  57.                                 }  
  58.                             }  
  59.                         });  
  60.                     }  
  61.                     else {  
  62.                         Log.i("GetMsgService","服务器端连接暂时出错");  
  63.                     //  Toast.makeText(getApplicationContext(), "服务器端连接暂时出错,请稍后重试!",0).show();  
  64.                     }  
  65.                 }  
  66.                     
  67.                }  
  68.            }.start();  
  69.     }  
  70.   
  71.     @Override  
  72.     public void onDestroy() {  
  73.         // TODO Auto-generated method stub  
  74.         super.onDestroy();  
  75.         ClientOutputThread out=client.getClientOutputThread();  
  76.         TransportObject<User> msg=new TransportObject<User>(TranObjectType.LOGOUT);  
  77.         User user=new User();  
  78.         user.setId(Integer.parseInt(util.getId()));  
  79.         msg.setObject(user);  
  80.         out.setMsg(msg);  
  81.         //关闭服务时关闭client  
  82.         out.setStart(false);  
  83.         client.getClientInputThread().setStart(false);  
  84.           
  85.           
  86.           
  87.     }  
  88.       
  89.       
  90.   
  91. }  
可以看到,我们在getMsgService的onStart方法中开启了一个线程用来进行客户端从服务器端读取信息的操作,在onDestroy()方法中关闭网络请求的操作。

2通过Context的bindService()方法启动服务:顾名思义,以该方法启动的服务,开启该服务的应用组件(如Activity)与该Service被绑定在一起,通常用这种方式开启的服务是为了与开启该服务的应用组件(如Activity)进行消息通信。

首先我们来看一下bindService的签名:

[java] view plain copy
  1. bindService(Intent service, ServiceConnection conn, int flags)  
其中service参数是通过intent指定要启动的Service。

conn参数是一个ServiceConnection对象,该对象用于监听访问者与service之间的连接情况,当访问者与Service连接成功时会回调该类的onServiceConnected(ComponentName name, IBinder service)方法,然后将服务中创建的Ibinder对象(此时在Service的onBinder方法中需要返回该Ibinder对象)传递给第二个参数service,通过该Ibinder对象就能与Service进行通信。

第三个参数flags指定绑定时是否自动创建Service,一般我们指定为BIND_AUTO_CREATE(自动创建,如果传入0表示不自动创建)示例代码如下:

Service中的代码:

[java] view plain copy
  1. public class MyService extends Service {  
  2.   
  3.     public static final String TAG = "MyService";  
  4.   
  5.     private MyBinder mBinder = new MyBinder();  
  6.   
  7.     @Override  
  8.     public void onCreate() {  
  9.         super.onCreate();  
  10.         Log.d(TAG, "onCreate() executed");  
  11.     }  
  12.   
  13.     @Override  
  14.     public int onStartCommand(Intent intent, int flags, int startId) {  
  15.         Log.d(TAG, "onStartCommand() executed");  
  16.         return super.onStartCommand(intent, flags, startId);  
  17.     }  
  18.   
  19.     @Override  
  20.     public void onDestroy() {  
  21.         super.onDestroy();  
  22.         Log.d(TAG, "onDestroy() executed");  
  23.     }  
  24.   
  25.     @Override  
  26.     public IBinder onBind(Intent intent) {//在onBind(Intent intent)中返回IBinder对象  
  27.         return mBinder;  
  28.     }  
  29.   
  30.     class MyBinder extends Binder {//定义一个类实现IBinder接口( Binder实现了IBinder接口)  
  31.   
  32.         public void doSomething() {  
  33.             Log.d("TAG""doSomething() executed");  
  34.               
  35.         }  
  36.   
  37.     }  
  38.   
  39. }  
Activity中的代码:
[java] view plain copy
  1. public class MainActivity extends Activity  
  2. {  
  3.   ...  
  4. private ServiceConnection connection = new ServiceConnection() {    
  5.     
  6.         @Override    
  7.         public void onServiceDisconnected(ComponentName name) {    
  8.         }    
  9.     
  10.         @Override    
  11.         public void onServiceConnected(ComponentName name, IBinder service) {    
  12.             myBinder = (MyService.MyBinder) service;    
  13.             myBinder.doSomething();    
  14.         }    
  15.     };    
  16.     protected void onCreate(Bundle savedInstanceState) {    
  17.         super.onCreate(savedInstanceState);    
  18.         setContentView(R.layout.activity_main);    
  19.     Intent bindIntent = new Intent(this, MyService.class);    
  20.         bindService(bindIntent, connection, BIND_AUTO_CREATE);//此时使用bindService开启服务  
  21.     }  
  22.   ...  
  23.   
  24. }  
即在服务中定义一个IBinder的实例,然后在Service的public IBinder onBind(Intent intent)方法中将其返回,在Activity中定义一个ServiceConnection类的实例,在其onServiceConnected(ComponentName name, IBinder service)方法中获取Service中 返回IBinder对象,利用该对象即可调用Service中的方法进行相互通信。

注意:一个服务在进程中的主线程运行——一个服务不会创建自己的线程,也不会在另外的进程运行(除非另外指定)。这意味着,如果服务需要做一些频繁占用CPU的工作或者会发生阻塞的操作,你需要在服务中另开线程执行任务。避免程序出现ANR。


2使用AIDL跨进程调用服务:

此种情况与上述介绍的使用bindService方法开启的绑定本地的大的框架基本相同,只不过使用AIDL来实现跨进程调用,关于此种情况的介绍,请参看我的博客:安卓中不同APP之间的消息通信中相关的内容。



二Service与线程的关系及IntentService:

事实上Service与线程之间没多大关系,我们之所以把Service与线程放在一起谈论,是为了更清楚的明白在哪些情况下用服务哪些情况下用线程,哪些情况下在服务中开启一个线程,因为Service默认在主线程中运行,不能进行耗时操作,这也是IntentService存在的原因。因为IntentService会创建单独的worker线程来处理intent请求,不需要自己创建一个子线程。

IntentService处理流程
创建默认的一个 worker 线程处理传递给 onStartCommand() 的所有 intent ,不占据应用的主线程
创建一个工作队列一次传递一个 intent 到你实现的 onHandleIntent() 方法,避免了多线程
在所有启动请求被处理后自动关闭服务,不需要调用 stopSelf()
默认提供 onBind() 的实现,且返回 null
默认提供 onStartCommand() 的实现,实现发送intent到工作队列再到onHandleIntent() 方法实现。

正因为如此,所以使用IntentService无需重写onBind(),onStartCommand(),只需重写onHandleIntent() 即可。示例代码如下:

[java] view plain copy
  1. 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. }  


三Service的生命周期

我们先来看一下谷歌官方图片:


从上述图片可以看到两种不同的启动方式其生命周期也不同:

启动的服务: 
startService()->onCreate()->onStartCommand()->running->stopService()/stopSelf()->onDestroy()->stopped 
其中,服务未运行时会调用一次onCreate(),运行时不调用。
绑定的服务: 
bindService()->onCreate()->onBind()->running->onUnbind()->onDestroy()->stopped
服务起始于 onCreate() ,终止于 onDestory()

服务的开关过程,只有 onStartCommand() 可多次调用,其他在一个生命周期只调用一次。

这两个过程不是完全独立,也可以绑定一个由 startService() 启动过的服务



四如何创建不被系统杀死的服务

服务不被杀死包括三种情况

1.系统根据资源分配情况杀死服务

2.用户通过 settings -> Apps -> Running -> Stop 方式杀死服务
3.用户通过 settings -> Apps -> Downloaded -> Force Stop 方式杀死服务
第一种情况:

用户不干预,完全靠系统来控制,办法有很多。比如 onStartCommand() 方法的返回值设为 START_STICKY ,服务就会在资源紧张的时候被杀掉,然后在资源足够的时候再恢复。当然也可设置为前台服务,使其有高的优先级,在资源紧张的时候也不会被杀掉。

关于 onStartCommand() 方法的返回值做一下简单的介绍:

START_STICKY:如果service进程被kill掉,保留service的状态为开始状态,但不保留递送的intent对象。随后系统会尝试重新创建service,由于服务状态为开始状态,所以创建服务后一定会调用onStartCommand(Intent,int,int)方法。如果在此期间没有任何启动命令被传递到service,那么参数Intent将为null。
START_NOT_STICKY:“非粘性的”。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统不会自动重启该服务。
START_REDELIVER_INTENT:重传Intent。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统会自动重启该服务,并将Intent的值传入。
START_STICKY_COMPATIBILITY:START_STICKY的兼容版本,但不保证服务被kill后一定能重启。

第二种情况:
用户干预,主动杀掉运行中的服务。这个过程杀死服务会通过服务的生命周期,也就是会调用 onDestory() 方法,这时候一个方案就是在 onDestory() 中发送广播开启自己。这样杀死服务后会立即启动。如下:

在onCreate中注册广播,用来开启服务,在服务的onDestroy()中发送广播通知服务开启自己,代码如下:

[java] view plain copy
  1. public void onCreate() {  
  2.   // TODO Auto-generated method stub  
  3.   super.onCreate();  
  4.   mBroadcast = new BroadcastReceiver() {  
  5.     @Override  
  6.     public void onReceive(Context context, Intent intent) {  
  7.       // TODO Auto-generated method stub  
  8.       Intent a = new Intent(ServiceA.this, ServiceA.class);  
  9.       startService(a);  
  10.     }  
  11.   };  
  12.   mIF = new IntentFilter();  
  13.   mIF.addAction("listener");  
  14.   registerReceiver(mBroadcast, mIF);  
  15. }  
  16. @Override  
  17. public void onDestroy() {  
  18.   // TODO Auto-generated method stub  
  19.   super.onDestroy();  
  20.   Intent intent = new Intent();  
  21.   intent.setAction("listener");  
  22.   sendBroadcast(intent);  
  23.   unregisterReceiver(mBroadcast);  
  24. }  

第三种情况:
强制关闭就不好解决。这个好像是从包的level去关的,不是走的Service的完整的生命周期。所以在服务里加代码是无法被调用的。处理这个情况的唯一方法是屏蔽掉 force stop 和 uninstall 按钮,让其不可用。

好了,以上就是本人理解的关于Service的相关知识,看官如果觉得不错请不要吝啬点击一下下方的“顶”按钮给我一点鼓励哦!微笑