Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

深入解析 Android 四大組件之 Service 服務

編輯:關於 Android 程式設計

在 Android 的四大組件當中,Service 是與 Activity 最為相似的一員,但兩者之間又有著本質的分別。理解 Service 的定位與用法,是掌握 Android 開發的關鍵一步。

一、Service 是什麼

Activity 與 Service 都代表正在執行的程序,但 Service 沒有使用者介面,它始終在後台默默運行,不會走到前台與使用者直接互動。一旦被啟動,Service 就和 Activity 一樣擁有自己的生命週期,並能獨立於畫面之外持續運作。

那麼,什麼時候該選 Activity,什麼時候該選 Service 呢?判斷標準其實很直觀:

如果某個組件需要在執行時向使用者呈現介面,或者需要與使用者進行互動,就應該使用 Activity;否則,就應該考慮用 Service 來實現。

舉個常見的例子:下載檔案、播放音樂。我們希望能一邊下載、一邊播放,同時還能去做別的事情。這正是 Activity 難以勝任的場景——一旦 Activity 被關閉或縮小到後台,程序也跟著停擺;而 Service 則能讓這些任務在背景裡穩定延續。

二、Service 的主要特點

1. 沒有使用者介面(UI)。

2. 適合執行耗時較長、或與使用者沒有直接互動的功能。

3. 擁有較高的優先級,比處於 stop 狀態的 Activity 更難被系統回收,僅次於前台 Activity。

4. 生命週期較長,能長時間存活於後台。

三、Service 的使用方式

1. 創建

自訂一個類並繼承 Service,同時實作 onBind() 方法。由於 Service 與 Activity 都是從 Context 派生出來的,因此可以直接使用 Context 提供的各項方法,例如 getResources() 等。

2. 配置

在 AndroidManifest.xml 中添加相應的標籤,透過 android:name 屬性指定 Service 類,也可以配置相關元素。

3. 啟動

Service 需要依賴其他組件來啟動,通常可由 Activity 或 Receiver 擔任呼叫者。呼叫者有兩種啟動形式:

(1)startService

透過 startService 啟動 Service 時,涉及以下生命週期方法:

onCreate() → onStartCommand() / onStart() → onDestroy()

a) onCreate():在建立 Service 實例時回呼,若實例不存在則觸發一次,之後重複啟動不會再觸發。

b) onStartCommand():每次啟動 Service 都會回呼,可透過 startId 參數取得啟動次數;第二個參數 flags 表示啟動服務的方式。

c) onStart():在新版本中已被淘汰。

d) onDestroy():銷毀 Service 實例。

注意:onStartCommand() 的返回值用於指定當系統在用戶未手動關閉 Service 前、因資源回收而終止 Service 時的重啟行為:

a) START_STICKY:若 Service 進程被 kill,系統會保留其「開始」狀態(但不保留傳送的 Intent 物件),隨後嘗試重新建立 Service。由於服務狀態為開始狀態,重建後一定會呼叫 onStartCommand(),此時若無啟動命令傳入,Intent 參數將為 null。

b) START_NOT_STICKY:「非黏性的」。執行完 onStartCommand 後,若服務被異常 kill,系統不會自動重啟。

c) START_REDELIVER_INTENT:執行完 onStartCommand 後,若服務被異常 kill,系統會自動重啟並把原本的 Intent 值再次傳入。

d) START_STICKY_COMPATIBILITY:START_STICKY 的相容版本,但不保證服務被 kill 後一定能重啟。

透過這種方式啟動的 Service 是一個獨立實例,與呼叫者沒有關聯,呼叫者的生命週期不會影響 Service。即使呼叫者退出,Service 仍然繼續運行。

(2)bindService

這個方法用來將 Service 實例與呼叫者建立關聯,兩者之間可以進行資料共享。此時呼叫者的生命週期會影響 Service,一旦呼叫者退出,Service 也會隨之終止。

bindService 有三個參數:

第一個參數是包含要綁定 Service 資訊的 Intent 物件。

第二個參數是 ServiceConnection 物件,用於監聽呼叫者與 Service 之間的連線狀態。當連線成功時,回呼 onServiceConnected(ComponentName, IBinder);當 Service 所在宿主進程異常中止或基於其他原因斷開連線時,回呼 onServiceDisconnected(ComponentName)。其中 onServiceConnected 的 IBinder 參數可實現與被綁定 Service 的溝通。開發 Service 時,必須提供 IBinder onBind() 方法,其回傳的 IBinder 物件會傳入 onServiceConnected 的參數中,呼叫者便可透過它與 Service 通訊。實務上通常繼承 Binder(IBinder 的實作類)來實作自訂的 IBinder。

第三個參數指定綁定時是否自動建立 Service,可設為 0(不自動建立)或 BIND_AUTO_CREATE(自動建立)。

透過 bindService 啟動的生命週期為:onCreate() → onBind() → onUnbind() → onDestroy()。

a) onCreate():同 startService。

b) onBind():在建立關聯時使用,回傳一個 IBinder 實例給呼叫者,作為 Service 在呼叫者端的代理。

c) onUnbind():Service 與呼叫者解除綁定。

d) onDestroy():同 startService。

e) onRebind():重新連線。

5. 停止

針對不同的啟動方式,可在呼叫者中手動關閉 Service:

stopService(Intent it);

unbindService(ServiceConnection conn);

6. IntentService

需要特別強調的是,Service 並不是獨立的進程,也不是獨立的線程,它依賴於應用程式的主線程。因此,並不建議在 Service 中編寫耗時邏輯,否則容易引發 ANR(Application Not Responding)。

當耗時邏輯不得不交由 Service 管理時,就該引入 IntentService。IntentService 繼承自 Service,因此保留了 Service 的全部特性與生命週期。與 Service 不同的是,IntentService 在執行 onCreate 時,內部會開啟一條子線程來執行耗時操作,並保證同一時刻只處理一個 Intent,這樣就不會阻塞主線程。使用方式與 Service 類似,只需重寫 onHandleIntent(Intent intent) 方法即可。

注意:若在 Activity 中綁定了服務,卻沒有在 onDestroy 中呼叫 unbind,就會出現「Service was originally bound here」的錯誤。解決方式是在 Activity 的 onDestroy 方法中呼叫 unbindService(sc),這是 Context 提供的方法。

 package com.xspacing.service; import com.xspacing.service.SecondService.MyBinder; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.view.View; public class MainActivity extends Activity { private Intent intent; private Intent intent2; private BindServiceConnection conn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void startService(View v) { intent = new Intent(this, FirstService.class); startService(intent); } public void stopService(View v) { stopService(intent); } public void startBindService(View v) { intent2 = new Intent(this, SecondService.class); conn = new BindServiceConnection(); bindService(intent2, conn, BIND_AUTO_CREATE); } public void stopBindService(View v) { unbindService(conn); conn=null; } public void intentService(View v) { Intent intent = new Intent(this, MyItentService.class); startService(intent); } class BindServiceConnection implements ServiceConnection { private static final String TAG = "BindServiceConnection"; @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.i(TAG, "onServiceConnected()"); MyBinder binder=(MyBinder) service; int count = binder.getCount(); Log.i(TAG, count+""); } @Override public void onServiceDisconnected(ComponentName name) { Log.i(TAG, "onServiceDisconnected()"); } } @Override protected void onDestroy() { if (conn != null) { unbindService(conn); } super.onDestroy(); } } 
 package com.xspacing.service; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class FirstService extends Service { private static final String TAG = "FirstService"; private boolean flag; private int count; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { Log.i(TAG, "onCreate()"); flag = true; new Thread(new Runnable() { @Override public void run() { while (flag) { count++; try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } Log.i(TAG, count + ""); } } }).start(); super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i(TAG, "onStartCommand()"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { Log.i(TAG, "onDestroy()"); flag = false; super.onDestroy(); } } 
 package com.xspacing.service; import android.app.IntentService; import android.content.Intent; import android.util.Log; public class MyItentService extends IntentService { private static final String TAG = "MyItentService"; private int count; private boolean flag = true; public MyItentService(String name) { super(name); } public MyItentService() { this("MyItentService"); } @Override protected void onHandleIntent(Intent intent) { while (flag) { count++; try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } Log.i(TAG, count + ""); } } @Override public void onDestroy() { flag = false; super.onDestroy(); } } 
 package com.xspacing.service; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.util.Log; public class SecondService extends Service { private static final String TAG = "SecondService"; private int count; boolean flag; @Override public IBinder onBind(Intent intent) { return new MyBinder(); } @Override public void onCreate() { super.onCreate(); Log.i(TAG, "onCreate()"); Log.i(TAG, "onBind()"); flag = true; new Thread(new Runnable() { @Override public void run() { while (flag) { count++; try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } Log.i(TAG, count + ""); } } }).start(); } @Override public boolean onUnbind(Intent intent) { Log.i(TAG, "onUnbind()"); return super.onUnbind(intent); } @Override public void onDestroy() { Log.i(TAG, "onDestroy()"); flag = false; super.onDestroy(); } public class MyBinder extends Binder { public int getCount() { return count; } } } 
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved