Android中Service的使用详解和注意点(LocalService)

开始,先稍稍讲一点android中Service的概念和用途吧~

Service分为本地服务(LocalService)和远程服务(RemoteService):

1、本地服务依附在主进程上而不是独立的进程,这样在一定程度上节约了资源,另外Local服务因为是在同一进程因此不需要IPC,也不需要AIDL。相应bindService会方便很多。主进程被Kill后,服务便会终止。

2、远程服务为独立的进程,对应进程名格式为所在包名加上你指定的android:process字符串。由于是独立的进程,因此在Activity所在进程被Kill的时候,该服务依然在运行,不受其他进程影响,有利于为多个进程提供服务具有较高的灵活性。该服务是独立的进程,会占用一定资源,并且使用AIDL进行IPC稍微麻烦一点。

按使用方式可以分为以下三种:

1、startService 启动的服务:主要用于启动一个服务执行后台任务,不进行通信。停止服务使用stopService;

2、bindService 启动的服务:该方法启动的服务可以进行通信。停止服务使用unbindService;

3、startService 同时也 bindService 启动的服务:停止服务应同时使用stepService与unbindService

Service 与 Thread 的区别

很多时候,你可能会问,为什么要用 Service,而不用 Thread 呢,因为用 Thread 是很方便的,比起 Service 也方便多了,下面我详细的来解释一下。

1). Thread:Thread 是程序执行的最小单元,它是分配CPU的基本单位。可以用 Thread 来执行一些异步的操作。

2). Service:Service 是android的一种机制,当它运行的时候如果是Local Service,那么对应的 Service 是运行在主进程的 main 线程上的。如:onCreate,onStart 这些函数在被系统调用的时候都是在主进程的 main 线程上运行的。如果是Remote Service,那么对应的 Service 则是运行在独立进程的 main 线程上。因此请不要把 Service 理解成线程,它跟线程半毛钱的关系都没有!

既然这样,那么我们为什么要用 Service 呢?其实这跟 android 的系统机制有关,我们先拿 Thread 来说。Thread 的运行是独立于 Activity 的,也就是说当一个 Activity 被 finish 之后,如果你没有主动停止 Thread 或者 Thread 里的 run 方法没有执行完毕的话,Thread 也会一直执行。因此这里会出现一个问题:当 Activity 被 finish 之后,你不再持有该 Thread 的引用。另一方面,你没有办法在不同的 Activity 中对同一 Thread 进行控制。

举个例子:如果你的 Thread 需要不停地隔一段时间就要连接服务器做某种同步的话,该 Thread 需要在 Activity 没有start的时候也在运行。这个时候当你 start 一个 Activity 就没有办法在该 Activity 里面控制之前创建的 Thread。因此你便需要创建并启动一个 Service ,在 Service 里面创建、运行并控制该 Thread,这样便解决了该问题(因为任何 Activity 都可以控制同一 Service,而系统也只会创建一个对应 Service 的实例)。

  

因此你可以把 Service 想象成一种消息服务,而你可以在任何有 Context 的地方调用 Context.startService、Context.stopService、Context.bindService,Context.unbindService,来控制它,你也可以在 Service 里注册 BroadcastReceiver,在其他地方通过发送 broadcast 来控制它,当然这些都是 Thread 做不到的。

Service的生命周期

onCreate  onStart  onDestroy  onBind 

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。


下面开始上一个很简单的代码哈~里头的注释也要注意哦,有在上面没有讲到的会在注释里提到哇(尤其适用Bind方法的时候的数据传输哇)~

首先,因为要再Manifest文件里对服务进行注册,所以就先来Manifest的代码吧~

[html]  view plain copy print ?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.test.localservice" android:versionCode="1"  
  4.     android:versionName="1.0">  
  5.     <uses-sdk android:minSdkVersion="8" />  
  6.   
  7.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  8.         <activity android:name=".LocalServiceTestActivity"  
  9.             android:label="@string/app_name">  
  10.             <intent-filter>  
  11.                 <action android:name="android.intent.action.MAIN" />  
  12.                 <category android:name="android.intent.category.LAUNCHER" />  
  13.             </intent-filter>  
  14.         </activity>  
  15.         <service android:name=".MyService">  
  16.             <intent-filter>  
  17.                 <action android:name="com.test.SERVICE_TEST" />  
  18.                 <category android:name="android.intent.category.default" />  
  19.             </intent-filter>  
  20.         </service>  
  21.     </application>  
  22. </manifest>  

然后然后,是服务实现类~

[java]  view plain copy print ?
  1.   
[java]  view plain copy print ?
  1. package com.test.service;  
  2.   
  3. import android.app.Service;  
  4. import android.content.Intent;  
  5. import android.os.Binder;  
  6. import android.os.IBinder;  
  7. import android.util.Log;  
  8.   
  9. public class MyService extends Service {  
  10.   
  11.     public class LocalBinder extends Binder {  
  12.         String stringToSend = "I'm the test String";  
  13.         MyService getService() {  
  14.             Log.i("TAG""getService ---> " + MyService.this);  
  15.             return MyService.this;  
  16.         }  
  17.     }  
  18.   
  19.     private final IBinder mBinder = new LocalBinder();  
  20.   
  21.     @Override  
  22.     public IBinder onBind(Intent intent) {  
  23.         // TODO Auto-generated method stub  
  24.         Log.i("TAG""onBind~~~~~~~~~~~~");  
  25. //      IBinder myIBinder = null;  
  26. //      if ( null == myIBinder )   
  27. //          myIBinder = new LocalBinder() ;   
  28. //      return myIBinder;  
  29.         return mBinder;     //也可以像上面几个语句那样重新new一个IBinder  
  30.         //如果这边不返回一个IBinder的接口实例,那么ServiceConnection中的onServiceConnected就不会被调用  
  31.         //那么bind所具有的传递数据的功能也就体现不出来~\(≧▽≦)/~啦啦啦(这个返回值是被作为onServiceConnected中的第二个参数的)  
  32.     }  
  33.   
  34.     @Override  
  35.     public void onCreate() {  
  36.         // TODO Auto-generated method stub  
  37.         super.onCreate();  
  38.   
  39.         Log.i("TAG""onCreate~~~~~~~~~~");  
  40.     }  
  41.   
  42.     @Override  
  43.     public void onDestroy() {  
  44.         // TODO Auto-generated method stub  
  45.         super.onDestroy();  
  46.         Log.i("TAG""onDestroy~~~~~~~~~~~");  
  47.     }  
  48.   
  49.     @Override  
  50.     public void onStart(Intent intent, int startId) {  
  51.         // TODO Auto-generated method stub  
  52.         super.onStart(intent, startId);  
  53.         Log.i("TAG""onStart~~~~~~");  
  54.     }  
  55.   
  56.     @Override  
  57.     public int onStartCommand(Intent intent, int flags, int startId) {  
  58.         // TODO Auto-generated method stub  
  59.         Log.i("TAG""onStartCommand~~~~~~~~~~~~");  
  60.         return super.onStartCommand(intent, flags, startId);  
  61.     }  
  62.   
  63.     @Override  
  64.     public boolean onUnbind(Intent intent) {  
  65.         // TODO Auto-generated method stub  
  66.         Log.i("TAG""onUnbind~~~~~~~~~~~~~~~~");  
  67.         return super.onUnbind(intent);  
  68.     }  
  69. }  


再来,就是我们的Activity的测试类啦~

[java]  view plain copy print ?
  1. <pre name="code" class="java">package com.test.service;  
  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.media.MediaPlayer;  
  9. import android.os.Bundle;  
  10. import android.os.IBinder;  
  11. import android.util.Log;  
  12. import android.view.View;  
  13. import android.view.View.OnClickListener;  
  14. import android.widget.Button;  
  15.   
  16. public class ServiceTestActivity extends Activity {  
  17.     private Button startButton, bindButton;  
  18.     private Button stopButton, unbindButton;  
  19.     private ServiceConnection sc;  
  20.     private MediaPlayer mediaPlayer = null;  
  21.     private MyService myService;// 类似于MediaPlayer mPlayer = new  
  22.                                 // MediaPlayer();只不过这边的服务是自定义的,不是系统提供好了的  
  23.   
  24.     /** Called when the activity is first created. */  
  25.     @Override  
  26.     public void onCreate(Bundle savedInstanceState) {  
  27.         super.onCreate(savedInstanceState);  
  28.         setContentView(R.layout.main);  
  29.   
  30.         startButton = (Button) findViewById(R.id.startbutton_id);  
  31.         stopButton = (Button) findViewById(R.id.stopbutton_id);  
  32.         bindButton = (Button) findViewById(R.id.bindbutton_id);  
  33.         unbindButton = (Button) findViewById(R.id.unbindbutton_id);  
  34.   
  35.         sc = new ServiceConnection() {  
  36.             /* 
  37.              * 只有在MyService中的onBind方法中返回一个IBinder实例才会在Bind的时候 
  38.              * 调用onServiceConnection回调方法 
  39.              * 第二个参数service就是MyService中onBind方法return的那个IBinder实例,可以利用这个来传递数据 
  40.              */  
  41.             @Override  
  42.             public void onServiceConnected(ComponentName name, IBinder service) {  
  43.                 // TODO Auto-generated method stub  
  44.                 myService = ((MyService.LocalBinder) service).getService();  
  45.                 String recStr = ((MyService.LocalBinder) service).stringToSend;  
  46.                 //利用IBinder对象传递过来的字符串数据(其他数据也可以啦,哪怕是一个对象也OK~~)  
  47.                 Log.i("TAG","The String is : " + recStr);  
  48.                 Log.i("TAG""onServiceConnected : myService ---> " + myService);  
  49.             }  
  50.   
  51.             @Override  
  52.             public void onServiceDisconnected(ComponentName name) {  
  53.                 /* SDK上是这么说的: 
  54.                  * This is called when the connection with the service has been unexpectedly disconnected 
  55.                  * that is, its process crashed. Because it is running in our same process, we should never see this happen. 
  56.                  * 所以说,只有在service因异常而断开连接的时候,这个方法才会用到*/  
  57.                 // TODO Auto-generated method stub  
  58.                 sc = null;  
  59.                 Log.i("TAG""onServiceDisconnected : ServiceConnection --->"  
  60.                         + sc);  
  61.             }  
  62.   
  63.         };  
  64.         startButton.setOnClickListener(new OnClickListener() {  
  65.   
  66.             @Override  
  67.             public void onClick(View v) {  
  68.                 // TODO Auto-generated method stub  
  69.                 Intent intent = new Intent(ServiceTestActivity.this,  
  70.                         MyService.class);  
  71.                 startService(intent);  
  72.                 Log.i("TAG""Start button clicked");  
  73.             }  
  74.         });  
  75.   
  76.         stopButton.setOnClickListener(new OnClickListener() {  
  77.   
  78.             @Override  
  79.             public void onClick(View v) {  
  80.                 // TODO Auto-generated method stub  
  81.   
  82.                 /* 
  83.                  * Intent intent = new 
  84.                  * Intent(LocalServiceTestActivity.this,MyService.class); 
  85.                  * stopService(intent); 这种方法也是可以的哈~ 
  86.                  */  
  87.   
  88.                 Intent intent = new Intent();  
  89.                 intent.setAction("com.test.SERVICE_TEST");  
  90.                 stopService(intent);  
  91.                 Log.i("TAG""Stop Button clicked");  
  92.             }  
  93.         });  
  94.   
  95.         bindButton.setOnClickListener(new OnClickListener() {  
  96.   
  97.             @Override  
  98.             public void onClick(View v) {  
  99.                 // TODO Auto-generated method stub  
  100. //              Intent intent = new Intent(LocalServiceTestActivity.this,  
  101. //                      MyService.class);//这样也可以的  
  102.                 Intent intent = new Intent();  
  103.                 intent.setAction("com.test.SERVICE_TEST");  
  104.                 bindService(intent, sc, Context.BIND_AUTO_CREATE);//bind多次也只会调用一次onBind方法  
  105.                 Log.i("TAG""Bind button clicked");  
  106.             }  
  107.         });  
  108.   
  109.         unbindButton.setOnClickListener(new OnClickListener() {  
  110.   
  111.             @Override  
  112.             public void onClick(View v) {  
  113.                 // TODO Auto-generated method stub  
  114.                 unbindService(sc);  
  115.                 // 这边如果重复unBind会报错,提示该服务没有注册的错误——IllegalArgumentException:  
  116.                 // Service not registered: null  
  117.                 // 所以一般会设置一个flag去看这个service  
  118.                 // bind后有没有被unBind过,没有unBind过才能调用unBind方法(这边我就不设置了哈~\(≧▽≦)/~啦啦啦)  
  119.                 Log.i("TAG""Unbind Button clicked");  
  120.             }  
  121.         });  
  122.     }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值