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

Android Service 全面剖析:生命週期、Local Service、IntentService 與 AIDL 遠程服務

編輯:關於 Android 開發

Service 是 Android 四大元件中最容易被誤解的一個。很多人以為它是「比較長命的 Activity」,也以為它天生就能跑背景耗時任務。事實上,Service 既不會自己開線程,也不保證永遠不被系統回收。本文從概念出發,依序拆解 Service 的生命週期、Local Service 的兩種啟動方式、如何用多線程處理延時任務,最後談 Remote Service 與 AIDL 跨進程通信。

引言

Android 之所以提供 Service,主要有兩個目的:一是簡化背景任務的實作,二是讓同一台裝置上的應用能夠跨進程交換資訊。

Service 大致分為 Local Service(本地服務)與 Remote Service(遠程服務)。前者只能被同一進程內的應用存取;後者透過 AIDL(Android Interface Definition Language)技術支援跨進程呼叫。啟動方式上,Service 可以透過 Context.startService() 或 Context.bindService() 拉起來——Local Service 兩種都能用,但 Remote Service 只能透過 bindService() 綁定。這兩種呼叫方式在使用情境與執行流程上有明顯差異,也是本文要重點釐清的地方。

目錄

  1. Service 的概念與類型
  2. Service 的生命週期
  3. Local Service 的應用原理與開發實例
  4. 以多線程處理 Service 的延時操作與 IntentService
  5. Remote Service 與 AIDL 跨進程通信

一、Service 的概念與類型

1.1 定義

Service 的概念與 Windows 系統上的服務有相似之處,熟悉 Windows 開發的人應該不難理解。當 App 需要持續監聽某些資料,或者需要為 Activity 提供資料支援時,就會用到 Service。典型例子包括:持續追蹤使用者地理位置、定時掃描 SD 卡、定期抓取當地氣候資料等等。Service 通常運行在背景,不需要使用者介面參與。

這裡有個關鍵認知:Service 不會自動建立線程。如果你沒有為它添加任何非同步處理,它就跑在主線程裡,和 Activity 共用同一條消息佇列。這也是為什麼在 Service 裡做網路請求一樣會觸發 ANR。

1.2 兩種分類視角

依生命週期模型分類:

  • 第一類透過 Context.startService() 啟動、Context.stopService() 結束。優點是呼叫簡單、易於控制;缺點是一旦啟動,除了再次下指令或結束服務之外,你幾乎無法與服務內部狀態互動,靈活性不足。
  • 第二類透過 Context.bindService() 啟動、Context.unbindService() 結束。它允許你透過 IBinder 取得 Service 的句柄,主動監控與呼叫服務的狀態。

從系統設計架構來看,startService() 偏向用於啟動本地服務,bindService() 則多用於綁定遠程服務。當然兩者也可以混用:先用 startService() 把服務拉起來並帶入初始化參數,再用 bindService()/unbindService() 反覆取用服務狀態,最後用 stopService() 收尾。第三節會有完整範例。

依寄存方式分類:

  • 本地服務(Local Service):寄存於當前進程,進程結束服務也跟著結束,可隨時與 Activity 等元件交換資訊。同樣地,若沒有手動開線程,它就在主線程中運行。
  • 遠程服務(Remote Service):獨立寄存於另一個進程,透過 AIDL 描述介面,實現 Android 裝置上的行程間通信(IPC)。AIDL 的 IPC 機制建立在 RPC(Remote Procedure Call)遠程過程呼叫協議之上,用來約束兩個進程之間的通訊規則,並交由編譯器產生對應的 Java 程式碼。跨進程傳遞的資訊會先被序列化成 AIDL 協議訊息,對方收到後再還原成物件。

二、Service 的生命週期

2.1 常用回呼方法

  • void onCreate():Service 被啟動時觸發。無論用 startService 還是 bindService,整個生命週期內只會觸發一次。
  • int onStartCommand(Intent intent, int flags, int startId):透過 startService 啟動時觸發,bindService 不會觸發。intent 是啟動時傳入的物件,flags 代表啟動方式,startId 是本次啟動的唯一標識。返回值決定服務被回收後的處理策略。
  • void onStart(Intent intent, int startId):2.0 之前的舊方法,已被棄用,不建議使用。
  • IBinder onBind(Intent intent):bindService 時呼叫,回傳一個 IBinder 物件,遠程服務正是靠它進行遠端操控。
  • void onRebind(Intent intent):當 onUnbind 回傳 true 之後,下一次 bindService 會改為觸發此方法。
  • boolean onUnbind(Intent intent):unbindService 時觸發,預設回傳 false;回傳 true 之後,再次 bindService 會走 onRebind。
  • void onDestroy():服務結束時觸發。三種情況:以 stopService 結束;以 unbindService 解除綁定;先 startService 再 bindService 的混合模式下,必須先 unbind 再 stop 才會觸發。

2.2 onStartCommand 的返回值與 flags

手機的 RAM 與內部資源有限,Service 隨時可能因為資源不足被系統回收。返回值決定了被回收之後的行為:

  • START_STICKY:進程被回收後系統會嘗試重建 Service;若期間沒有新的啟動指令送達,重建時傳入的 intent 會是 null。
  • START_NOT_STICKY:onStartCommand 執行完後若服務被異常回收,系統不會自動重啟。
  • START_REDELIVER_INTENT:服務被回收後系統自動重啟,並把最後一次未處理的 intent 重新送進來。
  • START_STICKY_COMPATIBILITY:START_STICKY 的相容版本,但不保證一定能重啟。

而 flags 參數則描述本次 onStartCommand 的啟動情境。正常啟動時 flags 為 0;被回收後重啟時有兩種可能:

  • START_FLAG_RETRY:由於上次返回值為 START_STICKY,重啟時 intent 為 null。
  • START_FLAG_REDELIVERY:由於上次返回值為 START_REDELIVER_INTENT,重啟時會帶著原本未處理的 intent。

2.3 兩條執行流程

startService 流程:onCreate() → onStartCommand() →(服務持續運行)→ stopService() → onDestroy()。其中 onCreate() 只會在第一次啟動時觸發一次,但每一次呼叫 startService() 都會觸發一次 onStartCommand()。服務不會自己結束,除非系統因資源不足將其回收。

bindService 流程:onCreate() → onBind() → ServiceConnection.onServiceConnected() →(服務持續運行)→ unbindService() → onUnbind() → onDestroy()。取得句柄之後,使用者就能在 onServiceConnected() 裡透過 IBinder 操作 Service。

關鍵差異在這裡:即使重複呼叫 bindService(),只要沒有先 unbind,系統只會在第一次綁定時觸發 onBind() 與 onServiceConnected()。字面上就不難理解——「start」是可以重複執行的動作,所以 onStartCommand 會多次觸發;「bind」是綁定關係,綁好了就不會重複綁。

三、Local Service 實作

3.1 以 startService 啟動

先建立 MyService 繼承 Service,實作 onCreate()、onDestroy()、onStartCommand() 等方法並用日誌記錄運行軌跡;Activity 端則透過 Intent 綁定目標服務。

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void btnStart_onclick(View view) {
        // 透過 Intent 綁定 MyService,並帶入參數
        Intent intent = new Intent(MainActivity.this, MyService.class);
        intent.putExtra("Name", "Leslie");
        Log.i(Context.ACTIVITY_SERVICE, "----------onClick startService-----------");
        startService(intent);
    }

    public void btnStop_onclick(View view) {
        Intent intent = new Intent(MainActivity.this, MyService.class);
        Log.i(Context.ACTIVITY_SERVICE, "----------onClick stopService------------");
        stopService(intent);
    }
}

public class MyService extends Service {

    @Override
    public void onCreate() {
        Log.i(Context.ACTIVITY_SERVICE, "Service onCreate");
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        Log.i(Context.ACTIVITY_SERVICE, "Service onDestroy");
        super.onDestroy();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        Log.i(Context.ACTIVITY_SERVICE, "Service onStart");
        super.onStart(intent, startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(Context.ACTIVITY_SERVICE, "Service onStartCommand");
        String name = intent.getStringExtra("Name");
        Log.i(Context.ACTIVITY_SERVICE, "His name is " + name);
        return super.onStartCommand(intent, flags, startId);
    }
}

別忘了在 AndroidManifest.xml 中註冊服務:

<activity
    android:name=".MainActivity"
    android:label="@string/title_activity_main" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
<service
    android:name="android.services.MyService"
    android:enabled="true">
</service>

Service 標籤的常用屬性:

  • android:name:服務類名。若 Service 與 Activity 不在同一個套件,必須寫上完整路徑。
  • android:label:服務名稱,為空則預設顯示類名。
  • android:icon:服務圖示。
  • android:permission:宣告此服務的權限,只有具備該權限的應用才能控制或連線。
  • android:process:指定服務運行於另一個進程,設定後會在套件名後附加該字串作為進程名。
  • android:enabled:設為 true 時服務可被系統啟動。
  • android:exported:是否允許其他應用控制或連線此服務。

從日誌可以清楚看到:多次呼叫 startService() 之後再 stopService(),onCreate() 與 onDestroy() 各自只被觸發一次,唯一被反覆呼叫的是 onStartCommand()。

3.2 以 bindService 綁定

在動手之前先認識兩個配角。IBinder 是 Binder 遠程物件的基本介面,是為高效能設計的輕量級遠程呼叫機制核心,它定義了與遠程物件互動的協議,但同樣適用於進程內呼叫。ServiceConnection 則是綁定成功後用來處理 Service 物件的回呼介面,包含 onServiceConnected(ComponentName, IBinder) 與 onServiceDisconnected(ComponentName)。前者在綁定完成後呼叫,後者一般不會被觸發,只有服務被意外回收時才可能呼叫。

public class MainActivity extends Activity {
    private MyServiceConnection serviceConnection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        serviceConnection = new MyServiceConnection();
    }

    public void btnBind_onclick(View view) {
        Intent intent = new Intent(this, MyService.class);
        Log.i(Context.ACTIVITY_SERVICE, "----------onClick bindService-----------");
        bindService(intent, this.serviceConnection, Context.BIND_AUTO_CREATE);
    }

    public void btnUnbind_onclick(View view) {
        Log.i(Context.ACTIVITY_SERVICE, "----------onClick unbindService----------");
        unbindService(serviceConnection);
    }
}

public class MyService extends Service {
    private MyBinder myBinder;

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(Context.ACTIVITY_SERVICE, "Service onBind");
        return this.myBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(Context.ACTIVITY_SERVICE, "Service onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(Context.ACTIVITY_SERVICE, "Service onCreate");
        myBinder = new MyBinder();
    }

    @Override
    public void onDestroy() {
        Log.i(Context.ACTIVITY_SERVICE, "Service onDestroy");
        super.onDestroy();
    }

    public String getDate() {
        Calendar calendar = Calendar.getInstance();
        return calendar.getTime().toString();
    }

    public class MyBinder extends Binder {
        public MyService getService() {
            return MyService.this;
        }
    }
}

public class MyServiceConnection implements ServiceConnection {

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Log.i(Context.ACTIVITY_SERVICE, "Service Connected");
        // 透過 IBinder 取得 Service 句柄
        MyService.MyBinder myBinder = (MyService.MyBinder) service;
        MyService myService = myBinder.getService();
        String data = myService.getDate();
        Log.i(Context.ACTIVITY_SERVICE, data);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.i(Context.ACTIVITY_SERVICE, "Service Disconnected");
    }
}

運行時可以發現,Service 會依序走完 onCreate() → onBind() → onUnbind() → onDestroy()。而即使重複點擊綁定按鈕,只要沒有 unbind,onBind() 與 onServiceConnected() 都只會觸發一次。

注意:bindService() 之後只能呼叫 unbindService() 一次,重複呼叫會拋出異常。實務上常見的處理方式是加一個 boolean 旗標做保護:

public class MainActivity extends Activity {
    private MyServiceConnection serviceConnection;
    private static boolean connected;

    public void btnBind_onclick(View view) {
        connected = true;
        Intent intent = new Intent(this, MyService.class);
        bindService(intent, this.serviceConnection, Context.BIND_AUTO_CREATE);
    }

    public void btnUnbind_onclick(View view) {
        if (connected) {
            unbindService(serviceConnection);
            connected = false;
        }
    }
}

3.3 兩者混合:讓服務長駐背景

前面的示範裡,Service 的壽命都是階段性的——一 stopService 或 unbindService 就結束了。但真實場景中,Service 往往是長駐背景的:它記錄程式運行狀態、保存重要資料,隨時接受查詢。

此時常見的組合是:startService() 負責啟動服務並帶入初始化參數,bindService() 負責隨時取得服務狀態做檢測。流程規律是「startService 啟動 → 反覆 bindService/unbindService 取用 → 最後 stopService 收尾」。注意在這個過程中,unbind 只是解除綁定,服務並未結束,仍在背景運行。

public class MyService extends Service {
    private MyBinder myBinder;
    private double param;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(Context.ACTIVITY_SERVICE, "Service onStartCommand");
        // 取得 startService 時帶入的初始參數
        this.param = intent.getDoubleExtra("param", 1.0);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(Context.ACTIVITY_SERVICE, "Service onBind");
        return this.myBinder;
    }

    // 提供給外界呼叫的公開方法
    public double getValue(int value) {
        return value * param;
    }

    public class MyBinder extends Binder {
        public MyService getService() {
            return MyService.this;
        }
    }
}

public class MyServiceConnection implements ServiceConnection {

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        MyService.MyBinder myBinder = (MyService.MyBinder) service;
        MyService myService = myBinder.getService();
        // 生成隨機數並交給服務端運算
        Random random = new Random();
        double value = myService.getValue(random.nextInt(10) * 1000);
        Log.i(Context.ACTIVITY_SERVICE, String.valueOf(value));
    }
}

運行結果顯示,onBind() 與 onUnbind() 只在第一次綁定流程中觸發,後續的 bindService() 都只會觸發 onServiceConnected()。原因是系統在綁定時會先搜尋既有的 IBinder 介面,若 Service 已綁定了 Binder 物件,系統會直接跳過 onBind()。

那如果每次綁定都想要不同的處理邏輯呢?Android 預留了 onRebind() 這個方法。只要把 onUnbind() 的返回值改成 true,從第二次 bindService() 開始就會改為觸發 onRebind():

public class MyService extends Service {

    @Override
    public void onRebind(Intent intent) {
        Log.i(Context.ACTIVITY_SERVICE, "Service onRebind");
        super.onRebind(intent);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(Context.ACTIVITY_SERVICE, "Service onUnbind");
        return true;   // 關鍵:回傳 true
    }
}

注意:這個用法只在 startService() 與 bindService() 同時被呼叫的情況下有效。若只呼叫其中一種,無論 onUnbind() 回傳什麼值,onRebind() 都不會被觸發。

四、用多線程處理 Service 的延時操作

4.1 為什麼必須開線程

Android 對 CPU、RAM、GPU 都有獨立的資源調度機制,對畫面反應與使用者體驗的要求也很高。一旦主線程裡出現大檔案讀寫、批次圖片處理、網路連線逾時這類操作,時間超過 5 秒,系統就會跳出「應用程式無回應」的提示,Logcat 上也會出現 "The application may be doing too much work on its main thread" 之類的警告。

Service 跑在主線程這件事很容易被忽略,所以在 Service 裡做耗時工作,一樣會被 ANR 找上門。最直覺的解法就是自己開一條線程。

public class MyService extends Service {

    @Override
    public void onCreate() {
        Log.i(Context.ACTIVITY_SERVICE, "Service onCreate");
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(Context.ACTIVITY_SERVICE, "Service onStartCommand");
        Log.i(Context.ACTIVITY_SERVICE,
                "Main thread id is " + Thread.currentThread().getId());
        // 以非同步方式進行模擬操作
        Thread background = new Thread(new AsyncRunnable());
        background.start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.i(Context.ACTIVITY_SERVICE, "Service onDestroy");
        super.onDestroy();
    }
}

public class AsyncRunnable implements Runnable {

    @Override
    public void run() {
        try {
            Log.i(Context.ACTIVITY_SERVICE,
                    "Async thread id is " + Thread.currentThread().getId());
            // 模擬耗時工作
            for (int n = 0; n < 8; n++) {
                Thread.sleep(1000);
                Log.i(Context.ACTIVITY_SERVICE, "****Do Work****");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

從日誌可以確認,onStartCommand() 與 AsyncRunnable 內部執行的程式碼分屬不同線程。

4.2 IntentService:系統已經幫你寫好的版本

「Service 裡要做延時操作」實在太常見,於是 Android 乾脆提供了一個現成子類 IntentService。當 IntentService 收到 startService() 時,系統會把請求丟進一個工作線程的佇列中排隊執行。它的原始碼其實非常精簡:

public abstract class IntentService extends Service {
    private volatile Looper mServiceLooper;
    private volatile ServiceHandler mServiceHandler;
    private String mName;
    private boolean mRedelivery;

    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            onHandleIntent((Intent) msg.obj);
            stopSelf(msg.arg1);
        }
    }

    public IntentService(String name) {
        super();
        mName = name;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        thread.start();

        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        mServiceHandler.sendMessage(msg);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        onStart(intent, startId);
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        mServiceLooper.quit();
    }

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

    protected abstract void onHandleIntent(Intent intent);
}

讀一遍原始碼,幾個設計意圖就很清楚了。系統沒有在 onStartCommand() 裡開新線程,而是在 onCreate() 中建立了一條獨立的工作線程——因為 onCreate() 只會被呼叫一次,這正是為了讓所有非同步任務共用同一條線程、序列化執行。每次 startService() 會透過 onStart() 把 Intent 包成 Message 丟進佇列,由 ServiceHandler.handleMessage() 取出並呼叫抽象方法 onHandleIntent(),做完再 stopSelf()。所以使用者只需要繼承並實作 onHandleIntent(),就免費獲得了「背景線程 + 任務排隊」的能力。

4.3 IntentService 應用範例

public class MyIntentService extends IntentService {

    public MyIntentService() {
        super(null);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String msg = intent.getStringExtra("msg");
        Log.i(Context.ACTIVITY_SERVICE,
                msg + "'s thread id is " + Thread.currentThread().getId());
    }
}

public class MainActivity extends Activity {

    public void btnStart_onclick(View view) {
        Log.i(Context.ACTIVITY_SERVICE, "----------onClick startService--------------");
        Log.i(Context.ACTIVITY_SERVICE,
                "Main thread id is " + Thread.currentThread().getId());

        Intent intent1 = new Intent(this, MyIntentService.class);
        intent1.putExtra("msg", "intentService1");
        startService(intent1);

        Intent intent2 = new Intent(this, MyIntentService.class);
        intent2.putExtra("msg", "intentService2");
        startService(intent2);

        Intent intent3 = new Intent(this, MyIntentService.class);
        intent3.putExtra("msg", "intentService3");
        startService(intent3);
    }
}
<application>
    ......
    <service
        android:name="android.services.MyIntentService"
        android:enabled="true">
    </service>
</application>

運行結果驗證了前面的推論:連續三次 startService() 觸發的任務,全部在同一條非同步線程中序列執行,而不是各開一條線程。

五、Remote Service 與 AIDL

5.1 什麼時候需要跨進程

前面所有範例都是 Local Service,服務端與客戶端在同一個進程裡,App 被卸除時服務也一起消失。若希望服務端與客戶端分屬不同進程,讓一方卸除時另一方不受影響,就需要 Remote Service。

這在企業級應用中很常見。大型集團往往同時擁有多個獨立 App,此時把共用服務放在一個獨立進程中,作為各 App 之間的資訊橋樑就非常合理:使用者資訊、登入狀態、身份驗證等共用模組都能集中在 Service 裡實作,供不同 App 呼叫。而且 App 關閉後,Service 仍能寄存於背景持續監聽。

5.2 技術背景

Android 的通信原則與多數系統一致:進程就是安全策略的邊界,一個進程不能直接存取另一個進程的資源。要跨進程,就得靠 IPC(Inter-Process Communication)。Android 的 IPC 機制建立在 RPC 協議之上,與 Java 的 RMI 相比,差別在於 Android 用 AIDL 介面描述語言來定制進程間的通訊規則,系統會依 AIDL 規則把資料序列化後送到另一個進程。

5.3 IPC 的底層運作

從底層來看,Android 的 IPC 主要依賴兩個核心元件:

  • ServiceManager:系統內的服務管理器,負責 Service 的註冊、查找與調用。原始碼位於 frameworks/base/cmds/servicemanager,核心函數包括 svcmgr_handler()、do_add_service()、do_find_service() 與 binder_loop()。啟動後它以 binder_loop 迴圈監聽 Binder Driver,發現有新的服務請求時呼叫 svcmgr_handler() 處理;先用 do_find_service() 在 svclist 中查找,若不存在則以 do_add_service() 註冊,把服務及其唯一標識加入清單。當 Client 呼叫時,ServiceManager 依標識找到對應的 Binder 實體,並把實體的引用交給 Client。由於 Binder 實體是強型別的,即使被多次引用也會指向同一個實體,直到所有連結都結束才釋放。
  • Binder Driver:運行於內核,以「字符驅動設備」中的 misc 設備形式存在於 /dev/binder。它提供 open()、mmap()、poll()、ioctl() 等標準化檔案操作,負責 Binder 通信的建立、Binder 實體在進程間的傳遞、引用計數管理,以及資料包在進程間的傳遞與交互等一連串底層工作。

5.4 應用層的關鍵介面

IBinder 是遠程服務最常用的介面,Binder 是它的實作類。IBinder 內部最重要的方法是 boolean transact(int code, Parcel data, Parcel reply, int flags),負責在服務器與客戶端之間交換資訊、呼叫遠端方法,並把返回值轉換成可序列化的物件送回客戶端。

5.5 第一個遠程服務:回傳伺服器時間

先建立服務端專案,新增 AIDL 檔案 ITimerService.aidl。編譯後系統會自動在 gen 目錄下產生對應的 Java 介面。

package com.example.remoteservice;

interface ITimerService {
    String getTimeNow();
}

自動產生的 ITimerService.java 中,Stub 繼承了 android.os.Binder,並透過 onTransact() 把介面方法的呼叫轉譯成 Binder 交易;Proxy 則是客戶端使用的代理類,負責把參數寫進 Parcel、發出 transact()、再把結果讀回來。這是 AIDL 最關鍵的一組骨架:

public static abstract class Stub extends android.os.Binder
        implements com.example.remoteservice.ITimerService {

    private static final java.lang.String DESCRIPTOR =
            "com.example.remoteservice.ITimerService";

    public static com.example.remoteservice.ITimerService asInterface(
            android.os.IBinder obj) {
        if ((obj == null)) {
            return null;
        }
        android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
        if (((iin != null) &&
                (iin instanceof com.example.remoteservice.ITimerService))) {
            return ((com.example.remoteservice.ITimerService) iin);
        }
        return new com.example.remoteservice.ITimerService.Stub.Proxy(obj);
    }

    @Override
    public boolean onTransact(int code, android.os.Parcel data,
                              android.os.Parcel reply, int flags)
            throws android.os.RemoteException {
        switch (code) {
            case INTERFACE_TRANSACTION: {
                reply.writeString(DESCRIPTOR);
                return true;
            }
            case TRANSACTION_getTimeNow: {
                data.enforceInterface(DESCRIPTOR);
                java.lang.String _result = this.getTimeNow();
                reply.writeNoException();
                reply.writeString(_result);
                return true;
            }
        }
        return super.onTransact(code, data, reply, flags);
    }

    private static class Proxy implements com.example.remoteservice.ITimerService {
        private android.os.IBinder mRemote;

        @Override
        public java.lang.String getTimeNow() throws android.os.RemoteException {
            android.os.Parcel _data = android.os.Parcel.obtain();
            android.os.Parcel _reply = android.os.Parcel.obtain();
            java.lang.String _result;
            try {
                _data.writeInterfaceToken(DESCRIPTOR);
                mRemote.transact(Stub.TRANSACTION_getTimeNow, _data, _reply, 0);
                _reply.readException();
                _result = _reply.readString();
            } finally {
                _reply.recycle();
                _data.recycle();
            }
            return _result;
        }
    }
    static final int TRANSACTION_getTimeNow =
            (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
}

接著建立 TimerService,用內部類實作 Stub。由於遠程服務只能用 bindService() 綁定,所以必須透過 onBind() 把實作物件交出去。

public class TimerService extends Service {

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

    public class TimerServiceImpl extends ITimerService.Stub {

        @Override
        public String getTimeNow() throws RemoteException {
            // 回傳伺服器端時間與服務端進程 Id
            Date date = new Date();
            SimpleDateFormat formatter =
                    new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
            return "Time now is " + formatter.format(date)
                    + "\nService processId is " + Process.myPid();
        }
    }
}

在 AndroidManifest.xml 中註冊,關鍵是 android:process 指定獨立進程,並在 intent-filter 中綁定介面名稱:

<application>
    ........
    <service android:name=".TimerService" android:process=":remote">
        <intent-filter>
            <action android:name="com.example.remoteservice.ITimerService"/>
        </intent-filter>
    </service>
</application>

服務端就緒後建立客戶端專案,把 ITimerService.aidl 複製過去,客戶端同樣會自動產生 Stub/Proxy。呼叫時要注意版本差異:Android 4.0 及以下可以直接用 Intent(String action) 建構後呼叫;Android 5.0 以上必須額外以 setPackage() 指定 action 所屬的套件名稱。

public class MainActivity extends Activity {
    private MyServiceConnection serviceConnection;
    private boolean connected;

    public void btnBind_onclick(View view) {
        Intent intent = new Intent();
        // 綁定遠程服務介面
        intent.setAction("com.example.remoteservice.ITimerService");
        intent.setPackage("com.example.remoteservice");
        this.connected = true;
        bindService(intent, this.serviceConnection, Context.BIND_AUTO_CREATE);
    }

    public void btnUnbind_onclick(View view) {
        if (connected) {
            unbindService(serviceConnection);
            connected = false;
        }
    }
}

public class MyServiceConnection implements ServiceConnection {

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        // 取得遠程物件
        ITimerService timerService = ITimerService.Stub.asInterface(service);
        try {
            String data = timerService.getTimeNow()
                    + "\nClient processId is " + Process.myPid();
            Log.i(Context.ACTIVITY_SERVICE, data);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}

運行結果清楚顯示 Service 與 Client 的 processId 不同,證明兩者確實運行於不同進程。

5.6 傳輸自訂義物件:Parcelable

當遠程服務需要傳遞自訂義型別時,物件必須先序列化。Android 提供兩種方式:常用的 Serializable 介面,以及 Android 專屬的 Parcelable 介面。Serializable 會產生大量暫存物件,容易引發頻繁的 GC 而拖累效能,因此 Android 設計了 Parcelable——它可以被理解為一個 Parcel 容器,透過 writeToParcel() 與 createFromParcel() 完成物件的讀寫。

public interface Parcelable {
    // 內容描述
    public int describeContents();
    // 序列化
    public void writeToParcel(Parcel dest, int flags);

    // 反序列化
    public interface Creator<T> {
        public T createFromParcel(Parcel source);
        public T[] newArray(int size);
    }
}

先在服務端新增 Person.aidl,宣告這個自訂型別:

package com.example.remoteservice;

parcelable Person;

再讓 Person 類實作 Parcelable。這裡有個容易出錯的細節:createFromParcel() 的讀取順序必須與 writeToParcel() 的寫入順序完全一致。

public class Person implements Parcelable {
    private String name;
    private Integer age;
    private String desc;

    public Person() {
    }

    public Person(String name, Integer age, String desc) {
        this.name = name;
        this.age = age;
        this.desc = desc;
    }

    // getter / setter 略

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(age);
        dest.writeString(desc);
    }

    public static final Parcelable.Creator<Person> CREATOR =
            new Creator<Person>() {

        /** 建立一個用於序列化的陣列 */
        @Override
        public Person[] newArray(int size) {
            return new Person[size];
        }

        /** 依寫入順序還原物件 */
        @Override
        public Person createFromParcel(Parcel source) {
            String name = source.readString();
            int age = source.readInt();
            String desc = source.readString();
            Person person = new Person();
            person.setName(name);
            person.setAge(age);
            person.setDesc(desc);
            return person;
        }
    };
}

接著定義服務介面。注意使用自訂型別時必須 import 該類別:

package com.example.remoteservice;

import com.example.remoteservice.Person;

interface IPersonService {
    Person getPerson(String number);
}

自動產生的 IPersonService.java 中,Stub 端會把結果以 writeInt(1) 標記「非 null」再呼叫 writeToParcel(),Proxy 端則對應地判斷旗標後用 CREATOR.createFromParcel() 還原物件——這正是 Parcelable 跨進程的完整閉環。

服務端實作:

public class PersonService extends Service {

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

    public class PersonServiceImpl extends IPersonService.Stub {

        @Override
        public Person getPerson(String number) throws RemoteException {
            switch (number) {
                case "0":
                    return new Person("Jack Mokei", 34, "Project Manager");
                case "1":
                    return new Person("Mike Tlea", 24, "Team Leader");
                default:
                    return null;
            }
        }
    }
}
<application>
    ........
    <service android:name=".PersonService" android:process=":remote">
        <intent-filter>
            <action android:name="com.example.remoteservice.IPersonService"/>
        </intent-filter>
    </service>
</application>

客戶端把 Person.aidl 與 IPersonService.aidl 一起複製過去,然後就能像呼叫本地方法一樣取得遠端物件:

public class MyServiceConnection implements ServiceConnection {

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        // 綁定遠程物件
        IPersonService personService = IPersonService.Stub.asInterface(service);
        try {
            Person person = personService.getPerson("0");
            String data = person.getName() + "'s age is " + person.getAge();
            Log.i(Context.ACTIVITY_SERVICE, data);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}

運行結果:

本章總結

把整篇串起來,其實只有幾個需要記牢的重點:

  • Service 不是線程,預設跑在主線程,耗時工作一定要自己開線程或改用 IntentService。
  • startService 的重點是 onStartCommand,適合「下指令」;bindService 的重點是 onBind 與 IBinder,適合「取狀態、做互動」。
  • onCreate() 與 onDestroy() 一生各觸發一次,這是判斷服務是否真正被建立或結束的依據。
  • onStartCommand 的返回值決定服務被回收後的重啟策略,正式專案通常選 START_STICKY 或 START_REDELIVER_INTENT。
  • Remote Service 只能透過 bindService() 綁定,跨進程傳自訂物件時務必實作 Parcelable,並注意 Parcel 的讀寫順序一致。

理解這些差異之後,就能依實際的開發情境靈活選用,而不是一律用最熟悉的那種寫法。

作者:風塵浪子
原文出處:https://www.cnblogs.com/leslies2/p/5401813.html

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