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

Android Service 你必須掌握的五件事

編輯:關於 Android 程式設計

Service 是 Android 四大元件之一,通常在後台執行較耗時的工作。要真正用好它,需要掌握:生命週期、建立方式、AIDL 跨進程通信,以及提高存活率的手段。以下逐一說明。

一、Service 的生命週期

Service 有兩種啟動方式,行為差異很大:

(1)startService

這種方式啟動的服務與呼叫它的 Activity 沒有交互關係。即使啟動它的 Activity 被銷毀,服務仍會繼續運行。只有調用 stopService()(或 stopSelf()),或者服務所在進程被系統回收,它才會停止。

(2)bindService

這種方式啟動的服務可以與 Activity 雙向通信,靠的是 Binder 機制。Activity 拿到 Binder 物件後,透過它調用 Service 對外暴露的方法——注意這不是直接調用 Service 內部實作,而是取得一個代理,再由代理轉發。

因為產生了綁定關係,Service 的生命週期會受 Activity 影響:Activity 銷毀時,綁定的 Service 也會跟著銷毀。記得在 Activity 銷毀前解除綁定,否則會出現記憶體洩漏警告。

不解除綁定的情況下,日誌大致如下:

可以看到 MainActivity 與 MyService 都正常回調了 onDestroy(),但系統仍拋出錯誤:

E/ActivityThread: Activity com.example.servertest.MainActivity has leaked
ServiceConnection com.example.servertest.MainActivity$1@b0ff6638
that was originally bound here

三個容易混淆的重點

  1. 無論用哪種方式啟動,Service 一旦開始執行就會跑完當前的邏輯,stopService() 無法硬中止進行中的操作。
  2. Service 不等於執行緒,兩者沒有必然關聯。
  3. Service 預設與 Activity 位於同一進程、同一主執行緒。因此在 Service 裡做耗時操作,必須另開執行緒,否則會 ANR。

二、建立一個 Service

繼承 Service 類別,覆寫需要的方法即可。

public class MyService extends Service {

    private static final String TAG = "MyService";
    private final MyBinder mBinder = new MyBinder();

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate() executed");
        Log.d(TAG, "MyService thread id is " + Thread.currentThread().getId());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand() executed");
        // 與 Activity 同進程,耗時任務必須另開執行緒,避免 ANR
        new Thread(() -> {
            Log.d(TAG, "Download thread id is " + Thread.currentThread().getId());
            // 執行具體的下载任務
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;   // 只有 bindService 時才會被呼叫
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy() executed");
        // 釋放不再使用的資源
    }

    /** 對外暴露的 Binder */
    class MyBinder extends Binder {
        public void startDownload() {
            new Thread(() -> {
                Log.d(TAG, "startDownload() executed");
                // 執行具體的下载任務
            }).start();
        }
    }
}

onBind() 回傳的 IBinder 是與 Service 通訊的唯一通道,而它只在 bindService 時才會被呼叫。

用 startService 啟動

Intent intent = new Intent(MainActivity.this, MyService.class);
startService(intent);

用 bindService 啟動

Intent intent = new Intent(MainActivity.this, MyService.class);
bindService(intent, serviceConnection, BIND_AUTO_CREATE);

其中 serviceConnection 是實作 ServiceConnection 的物件:

serviceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        // 綁定成功後取得 Binder,即可呼叫 Service 對外的方法
        MyService.MyBinder myBinder = (MyService.MyBinder) service;
        myBinder.startDownload();
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        // 服務異常中斷時回調
    }
};

三、遠程服務與 AIDL 跨進程通信

上面的例子是本地服務:它依附主進程,不需要 AIDL,操作相對簡單。遠程服務則運行在獨立進程,必須用 AIDL 對外暴露接口。

為什麼需要 AIDL?打個比方:遠程服務對你而言是一台陌生機器,你不知道它能提供什麼。AIDL 就像它的說明書,列出所有可用操作;你(客戶端)照著上面的方法呼叫,就能取得服務,而不必關心機器內部怎麼運作。

把本地服務轉為遠程服務很簡單,在清單檔中加上 android:process=":remote":

<service
    android:name=".RemoteService"
    android:process=":remote" />

(1)定義 AIDL 檔

在 Android Studio 中於 java 同層的 aidl 目錄建立檔案(右鍵 → New → AIDL → AIDL File),檔名與套件結構需與 Java 一致。

// IMyAidlInterface.aidl
package com.example.servertest;

interface IMyAidlInterface {
    int plus(int a, int b);
    String toUpperCase(String str);
}

定義好之後執行一次 Make,Studio 會自動產生對應的 Java 接口(Binder 與 Stub 代理都在裡面),不要手動修改它。

(2)在遠程服務中實作 Stub

public class RemoteService extends Service {

    private final IMyAidlInterface.Stub mBinder = new IMyAidlInterface.Stub() {
        @Override
        public int plus(int a, int b) throws RemoteException {
            return a + b;
        }

        @Override
        public String toUpperCase(String str) throws RemoteException {
            return str.toUpperCase();
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
}

Stub 本身就是 Binder 的子類,因此這個物件可以直接作為 onBind() 的回傳值,也就是客戶端在 onServiceConnected() 中拿到的那個 IBinder。

(3)Activity 綁定遠程服務並呼叫

Intent intent = new Intent(MainActivity.this, RemoteService.class);
bindService(intent, serviceConnection, BIND_AUTO_CREATE);
serviceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        // 把 IBinder 轉成 AIDL 接口
        IMyAidlInterface api = IMyAidlInterface.Stub.asInterface(service);
        try {
            int result = api.plus(3, 5);
            String upper = api.toUpperCase("hello world");
            Log.d("iMyAidlService", "result is " + result);
            Log.d("iMyAidlService", "upperStr is " + upper);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName name) { }
};

跨應用呼叫

要讓另一個 App 也能綁定這個遠程服務,有兩個步驟:

  1. 在服務的清單宣告中加上 intent-filter,自訂一個 action 供外部比對。

  1. 把 aidl 檔(包含完整套件目錄結構)複製到另一個專案,再用隱式 Intent 綁定。
Intent intent = new Intent("com.example.servicetest.MyAIDLService");
bindService(intent, serviceConnection, BIND_AUTO_CREATE);

四、提高 Service 存活率的五種做法

(1)提升進程優先級

在 Manifest 中為 Service 的 intent-filter 加上 android:priority="1000"(1000 為最高值,數字越小優先級越低)。這個屬性同樣適用於廣播接收器。

(2)改用前台服務

呼叫 startForeground(id, notification) 把 Service 提到前台,並顯示一則持續性通知,能顯著降低被回收機率。

public class ForegroundService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();

        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Notification notification;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            notification = new Notification.Builder(this)
                    .setAutoCancel(true)
                    .setContentTitle("有通知到來")
                    .setContentText("describe")
                    .setContentIntent(pendingIntent)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setWhen(System.currentTimeMillis())
                    .setOngoing(true)
                    .build();
        } else {
            notification = new Notification.Builder(this)
                    .setContentTitle("有通知到來")
                    .setContentText("describe")
                    .setContentIntent(pendingIntent)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .getNotification();
        }

        startForeground(1, notification);
    }

    @Override
    public void onDestroy() {
        stopForeground(true);   // 別忘了取消前台狀態
        super.onDestroy();
    }
}

(近版 Android 對前台服務與通知權限有更嚴格的限制,實作時請對照目前 targetSdk 的規範調整。)

(3)為 onStartCommand 回傳 START_STICKY

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}

四種回傳值的語意:

  • START_STICKY:進程被 kill 後,系統會重建服務並再次呼叫 onStartCommand(),但未重投的 Intent 會是 null。
  • START_NOT_STICKY:非粘性。執行完 onStartCommand() 後若被異常終止,系統不會自動重啟。
  • START_REDELIVER_INTENT:被 kill 後重啟,並把最後一個未處理的 Intent 重新投遞進來。
  • START_STICKY_COMPATIBILITY:START_STICKY 的相容版本,但不保證一定能重啟。

(4)Service + Broadcast 互相拉拔

建立一個廣播接收器,收到指定廣播時檢查服務是否還活著,沒活著就重新啟動。

<receiver android:name=".MyBroadcastReceiver">
    <intent-filter>
        <action android:name="com.ForegroundService.destroy" />
    </intent-filter>
</receiver>

或者在 onDestroy() 中主動發送自定義廣播,由接收器把服務再拉起來:

@Override
public void onDestroy() {
    Log.d(TAG, "onDestroy() executed");
    stopForeground(true);
    // 銷毀時發送廣播,由接收器重新啟動服務
    sendBroadcast(new Intent("com.ForegroundService.destroy"));
    super.onDestroy();
}

(5)persistent 屬性

在 Manifest 的 <application> 上添加 android:persistent="true"。系統啟動時,AMS 的 systemReady() 會優先加載所有標記為 persistent 的應用。

但要注意:單獨設定這個屬性無效,必須同時滿足 FLAG_SYSTEM(App 需置於 /system/app 目錄)與 FLAG_PERSISTENT 兩個條件。也就是說,這招基本上只有系統簽名或 ROM 定制應用能用。

結語

Service 的思維要點其實只有一句:它是「元件」不是「執行緒」。想清楚它跑在哪個進程、由誰啟動、什麼時候該被解绑,剩下的 API 都是細節。至於提高存活率的各种技巧,在現代 Android 版本上愈發受限,正規做法仍是前台服務加使用者可感知的通知。

本文示例的完整源碼已放在我的 GitHub 上,註解較為詳細,歡迎參閱。

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