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的代碼吧~

  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>  

然後然後,是服務實現類~

  1.   
  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的測試類啦~

  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.     }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章