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

Android 開發文件翻譯:Service 服務元件完全解析

編輯:關於 Android 開發

Android 開發文件翻譯:Service 服務元件完全解析

Service 是一種能在後台長期運行、同時不需要與用戶互動的應用元件。其他元件可以啟動它,啟動後即便用戶已切換到其他應用,它仍能持續運行。此外,元件還可以與 Service 綁定進行互動,哪怕是跨進程的互動(即 Android 的 IPC 機制)。無論是網路操作、播放音樂、執行檔案 IO,還是與內容提供者互動,都可以交給 Service 在後台完成。

Service 的兩種形式

Started(啟動式)
透過呼叫 startService() 可以啟動一個 Service。一旦被啟動,它便能獨立地運行在後台,即使啟動它的元件被銷毀也無妨。通常,被啟動的 Service 用來執行單一操作且不返回值,例如從網路下載一個檔案;操作完成後,Service 應當自行結束。

Bound(綁定式)
透過呼叫 bindService() 可以綁定一個 Service。被綁定的 Service 通常會提供一個介面,供元件互動、發送請求、獲取結果,甚至進行進程間互動(IPC)。它的生命週期與所綁定的元件相同。儘管多個元件可以同時綁定同一個 Service,但當所有元件都解綁後,Service 便會被銷毀。

雖然文件通常把這兩種形式分開介紹,但你完全可以同時啟動並綁定 Service,只需同時覆寫 onStartCommand 和 onBind 兩個回呼即可。無論用哪一種方式啟動,你都能像操作 Activity 一樣,透過 Intent 來操作 Service。若不希望其他應用使用你的 Service,可以在 manifest 檔中將它宣告為私有。

基礎介紹

要使用 Service,你需要繼承 Service 類或其子類,並覆寫一些關鍵的生命週期回呼方法。以下是幾個較為重要的回呼:

onStartCommand()
系統會在你呼叫 startService 後調用該方法。一旦執行,Service 便會啟動並獨立運行在後台。如果你實作了它,就必須在合適的時機呼叫 stopSelf() 或 stopService() 來停止 Service。(若你只提供綁定介面,則可不實作它。)

onBind()
當有其他元件透過 bindService() 綁定 Service 後,系統會調用該方法。你需要在其中提供一個實作了 IBinder 介面的類供 client 使用。這個方法必須覆寫;若不希望提供綁定功能,直接返回 null 即可。

Android 系統會在記憶體吃緊時強制停止 Service:綁定在擁有焦點的 Activity 上的 Service 被 kill 的風險較低;被宣告為前台的 Service 幾乎不會被 kill。反之,長時間開啟的 Service 隨著時間推移優先級會越來越低,被 kill 的風險也隨之升高。若系統 kill 了一個 Service,在資源寬鬆時會依你在 onStartCommand() 的回傳值決定是否重啟。

Service 在清單檔中的宣告

和 Activity 一樣,你需要在清單檔中宣告 Service:

  ...  ...  

在 service 節點中可以宣告一些其他屬性,這些都是可選的,唯有 android:name 是必須的——它用來描述一個唯一的 Service 類名,你應確保不去修改它。為確保應用安全,應使用顯式 Intent 來啟動或綁定 Service,並且不在其中宣告 intent-filters。此外,你可以把 android:exported 屬性設為 false,確保 Service 僅能在自己的應用中被使用,有效阻止其他應用(哪怕透過顯式 Intent)呼叫它。

以啟動方式創建 Service

可以透過 startService() 來啟動 Service,並監聽 onStartCommand() 回呼。當 Service 被啟動後,它將擁有獨立的生命週期並運行在後台,即使開啟它的元件被銷毀。這種情況下,你需要透過 stopSelf() 或 stopService() 來結束它。呼叫 startService() 時傳遞的 Intent 會在 onStartCommand() 回呼時被接收到。

注意:Service 預設運行在宣告它的應用進程中,且運行在主線程裡。所以如果它執行密集或阻塞的操作,可能造成 ANR。為避免這種情況,你需要另開一個執行緒。一般來說,可以透過繼承 IntentService 類來加速開發。

繼承 IntentService 類

由於大部分 Service 都不需要處理並發請求,因此繼承 IntentService 能大幅簡化開發。IntentService 具備以下特性:

1. 創建了一個與主線程分離的工作執行緒來執行由 onStartCommand() 傳遞的 Intent;
2. 創建了一個工作隊列用來依序執行 Intent,因此你無需考慮多執行緒問題;
3. 當所有任務執行完畢後會自動呼叫 stopSelf();
4. 提供了 onBind() 的預設實作(返回 null);
5. 提供了 onStartCommand() 的預設實作,將任務送入隊列並回呼 onHandleIntent()。

這些特性使得你只需實作 onHandleIntent()(外加一個簡單的建構子)即可完成 client 端的任務。以下是一個 IntentService 的實作:

 public class HelloIntentService extends IntentService { /** * A constructor is required, and must call the super IntentService(String) * constructor with a name for the worker thread. */ public HelloIntentService() { super("HelloIntentService"); } /** * The IntentService calls this method from the default worker thread with * the intent that started the service. When this method returns, IntentService * stops the service, as appropriate. */ @Override protected void onHandleIntent(Intent intent) { // Normally we would do some work here, like download a file. // For our sample, we just sleep for 5 seconds. try { Thread.sleep(5000); } catch (InterruptedException e) { // Restore interrupt status. Thread.currentThread().interrupt(); } } }

對比一下,若你直接繼承 Service 來實現相同功能,所需撰寫的程式碼:

 public class HelloService extends Service { private Looper mServiceLooper; private ServiceHandler mServiceHandler; // Handler that receives messages from the thread private final class ServiceHandler extends Handler { public ServiceHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { // Normally we would do some work here, like download a file. // For our sample, we just sleep for 5 seconds. try { Thread.sleep(5000); } catch (InterruptedException e) { // Restore interrupt status. Thread.currentThread().interrupt(); } // Stop the service using the startId, so that we don't stop // the service in the middle of handling another job stopSelf(msg.arg1); } } @Override public void onCreate() { // Start up the thread running the service. Note that we create a // separate thread because the service normally runs in the process's // main thread, which we don't want to block. We also make it // background priority so CPU-intensive work will not disrupt our UI. HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND); thread.start(); // Get the HandlerThread's Looper and use it for our Handler mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show(); // For each start request, send a message to start a job and deliver the // start ID so we know which request we're stopping when we finish the job Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; mServiceHandler.sendMessage(msg); // If we get killed, after returning from here, restart return START_STICKY; } @Override public IBinder onBind(Intent intent) { // We don't provide binding, so return null return null; } @Override public void onDestroy() { Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show(); } }

是不是累覺不愛?果斷用 IntentService 好啊。然而,如果你希望實現並發操作——即不等上一個請求執行完畢就進行下一個——那麼直接繼承 Service 就是必要的選擇。

另外要注意,onStartCommand() 方法必須回傳一個整數,用來指定系統殺死 Service 後應如何處理。以下是各回傳值的含義:

START_NOT_STICKY:系統殺死 Service 後不會重新創建,除非有待傳遞的 pending intents。適用於能簡單重啟未完成任務的 Service。

START_STICKY:系統殺死 Service 後會重啟它並調用 onStartCommand(),但不會重發上一個 intent,而是回傳一個 null intent(除非有 pending intents)。很適合音樂播放器這種需要獨立運行、等待任務的 Service。

START_REDELIVER_INTENT:系統殺死 Service 後會重啟它並調用 onStartCommand(),且會傳遞上一個 intent。適合那些需要立即重新處理的 Service,例如下載檔案。

以綁定方式啟動 Service

詳見《Android 開發文件翻譯之-Bound Services》。

給用戶發送通知

一旦 Service 運行,你可以透過 Toast Notifications 或 Status Bar Notifications 來告知用戶某些事件。Toast Notifications 是一段短時間內出現在當前視窗表面的訊息;Status Bar Notifications 則是提供圖示與訊息的通知欄,用戶點擊後可執行某個動作(例如開啟一個 Activity)。

前台 Service

前台 Service 通常用來執行一些需要用戶意識到正在進行的操作,因此系統在低記憶體時也不會 kill 掉它。前台 Service 需要在狀態列上提供一個不會消失的通知,直到 Service 被停止或從前台移除為止。例如,音樂播放器的 Service 就應該設為前台 Service,因為用戶應該一直意識到這個操作,狀態列應顯示當前播放的歌曲,點擊後可跳轉到能與用戶互動的 Activity。透過呼叫 startForeground() 即可讓 Service 運行在前台:

 Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text), System.currentTimeMillis()); Intent notificationIntent = new Intent(this, ExampleActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(this, getText(R.string.notification_title), getText(R.string.notification_message), pendingIntent); startForeground(ONGOING_NOTIFICATION_ID, notification);

管理 Service 的生命週期

Service 的生命週期相對 Activity 要簡單得多,卻更需要你多加留意,因為它通常運行在後台,容易被忽略。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved