Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 初階開發

Android Service 與 AIDL 使用全解

編輯:初階開發

Service 有兩種啟動方式(startService 與 bindService),而當 Service 位於另一個應用(遠程 Service)時,還需要透過 AIDL 才能呼叫它的方法。本文依序說明這三種情況。

一、Service 的基本概念

Service 是一個在背景運行的服務。你啟動的 Service 所做的較耗時工作,最好放在另一個線程中執行——因為 Service 運行於主線程,會阻塞呼叫它的線程。

建立與啟動 Service 有兩種方式:

Intent in = new Intent(...);
startService(in);   // 或
bindService(in, ...);

與之對應,停止 Service 也有兩種方式:

stopService(in);    // 或
unbindService(sc);

Intent 怎麼寫

本地(同一個應用內)的 Service:

Intent in = new Intent(this, LocalService.class);

同時要在 Manifest 中標明它的名稱:

<service android:name=".ServiceA"/>

非本地(跨應用)的 Service:在 Intent 中直接指明 action:

Intent in = new Intent("com.test.A");

此時該 Service 在 Manifest 中必須同時宣告 name 與 intent-filter:

<service android:name=".ServiceA">
    <intent-filter>
        <action android:name="com.test.A"/>
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</service>

二、startService 與 stopService

這種方式比較簡單,直接在呼叫端的 Activity 中寫上即可。

2.1 呼叫端 Activity

package com.D_activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class D_activity extends Activity {
    Button b;
    private boolean running = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b = (Button) findViewById(R.id.button);
    }

    @Override
    protected void onResume() {
        // 指定一個 Intent
        final Intent in = new Intent("com.test.A");
        super.onResume();

        b.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (running) {
                    running = false;
                    stopService(in);
                    b.setText("start");
                } else {
                    running = true;
                    startService(in);
                    b.setText("stop");
                }
            }
        });
    }
}

2.2 被 startService 啟動的 Service

透過 startService 啟動的 Service,其生命週期會依序呼叫:onCreate() → onStartCommand() → onDestroy()。onCreate 僅在第一次建立時呼叫;onStartCommand 在每次 startService 後呼叫;onDestroy 則在 stopService 時呼叫。

以下實作一個每 5 秒輸出系統時間的 Service。程式架構參考官方文件,重點在於用 HandlerThread 建立獨立線程,避免阻塞主線程:

package com.A_s;

import java.text.SimpleDateFormat;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.util.Log;
import android.widget.Toast;

public class ServiceA extends Service {
    private boolean flag = true;
    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) {
            // 正常情況下這裡會做一些實際工作,如下載檔案。
            // 本範例只是每 5 秒輸出一次時間。
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            while (flag) {
                synchronized (this) {
                    try {
                        Log.i("TEST", "A :" + sdf.format(System.currentTimeMillis()));
                        wait(5 * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                // 用 startId 停止服務,避免在其他工作處理到一半時被中止
                stopSelf(msg.arg1);
            }
        }
    }

    @Override
    public void onCreate() {
        // 啟動執行服務的線程。注意這裡另外建立一個線程,
        // 因為 Service 預設運行於 process 的主線程,我們不希望它被阻塞。
        // 同時設為背景優先級,讓 CPU 密集工作不會影響 UI。
        HandlerThread thread = new HandlerThread("ServiceStartArguments",
                Process.THREAD_PRIORITY_BACKGROUND);
        thread.start();

        // 取得 HandlerThread 的 Looper 並用於我們的 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();

        // 對每個啟動請求,送一個訊息啟動一項工作,並帶入 start ID,
        // 這樣我們就知道完成時要停止的是哪一個請求
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        mServiceHandler.sendMessage(msg);

        // 若被系統殺掉,此行返回後會重新啟動
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // 不提供綁定,回傳 null
        return null;
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
        flag = false;
    }
}

Manifest 中的宣告:

<service android:name=".ServiceA">
    <intent-filter>
        <action android:name="com.test.A"/>
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</service>

三、bindService 與 unbindService

這種方式啟動的 Service,生命週期為:onCreate() → onBind() → onDestroy()。

與 startService 最大的不同是:這次改用 onBind() 而非 onStartCommand。因此 Service 端的程式碼與上一節幾乎相同,只要把原本放在 onStartCommand 中的邏輯搬到 onBind 裡即可:

@Override
public IBinder onBind(Intent intent) {
    Toast.makeText(this, "service starting in onBind", Toast.LENGTH_SHORT).show();
    Message msg = mServiceHandler.obtainMessage();
    mServiceHandler.sendMessage(msg);
    return IBinder;
}

3.1 使用 bindService 的呼叫端

這次的 Activity 比之前多了一個 ServiceConnection。當 bindService 完成時,系統會自動呼叫 ServiceConnection 中的 onServiceConnected()。

package com.C_activity;

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.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class C_activity extends Activity {
    Button b;
    private boolean running = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b = (Button) findViewById(R.id.button);
    }

    @Override
    protected void onResume() {
        final Intent in = new Intent("com.test.E");
        super.onResume();

        b.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (running) {
                    running = false;
                    unbindService(sc);
                    b.setText("start");
                } else {
                    running = true;
                    // bindService 的最後一個參數有特定意義(如 BIND_AUTO_CREATE),
                    // 建議查文件確認自己需要哪一種
                    bindService(in, sc, 1);
                    b.setText("stop");
                }
            }
        });
    }

    private ServiceConnection sc = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
        }

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

四、用 AIDL 進行遠程 Service 呼叫

當 Service 不是本地的,就無法把 onServiceConnected 提供的 IBinder 直接轉型成 Service 類別來呼叫其方法。這時就需要 AIDL(Android Interface Definition Language)。

直觀地看,遠程服務若能被操作,就必須提供一個操作介面;而這個介面不只要在伺服器端實作,呼叫端也得知道怎麼呼叫。因此我們定義一個 AIDL 檔來描述這個服務——也就是透過雙方共享同一份 AIDL 檔來共享同一個介面。

4.1 定義 AIDL 檔

例如建立 test_aidl.aidl:

package com.E_s;

interface test_aidl {
    int getCount();
}

寫好之後,Android 的 IDE 會自動在 gen 目錄下產生對應的 test_aidl.java。這個檔案裡會生成一個介面 test_aidl(extends android.os.IInterface),並包含一個關鍵的樁類別:

public static abstract class Stub extends android.os.Binder implements test_aidl

接著在 Service 中實作這個介面:

private final test_aidl.Stub IBinder = new test_aidl.Stub() {
    @Override
    public int getCount() throws RemoteException {
        return i;
    }
};

4.2 使用 AIDL 的 Service 端完整程式碼

package com.E_s;

import java.text.SimpleDateFormat;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

public class ServiceA extends Service {
    private boolean flag = true;
    private Looper mServiceLooper;
    private ServiceHandler mServiceHandler;
    public static int i = 0;

    // 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) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            while (flag) {
                synchronized (this) {
                    try {
                        i++;
                        Toast.makeText(ServiceA.this, "E_s", Toast.LENGTH_SHORT).show();
                        Log.i("liyufei", "E(A) :" + sdf.format(System.currentTimeMillis()));
                        wait(5 * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    @Override
    public void onCreate() {
        HandlerThread thread = new HandlerThread("ServiceStartArguments",
                Process.THREAD_PRIORITY_BACKGROUND);
        thread.start();

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

    @Override
    public IBinder onBind(Intent intent) {
        Toast.makeText(this, "service starting in onBind", Toast.LENGTH_SHORT).show();
        Message msg = mServiceHandler.obtainMessage();
        mServiceHandler.sendMessage(msg);
        return IBinder;
    }

    private final test_aidl.Stub IBinder = new test_aidl.Stub() {
        @Override
        public int getCount() throws RemoteException {
            return i;
        }
    };

    @Override
    public void onDestroy() {
        Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
        flag = false;
    }
}

4.3 呼叫端如何接上 AIDL

首先,呼叫端的專案中也要建立相同套件名稱並放入同一份 AIDL 檔。例如把 test_aidl.aidl 也放進呼叫端的 com.E_s 套件中,這樣呼叫端也會自動產生 test_aidl.java。

然後只需在原本使用 bindService 的 ServiceConnection 中補上幾行:

test_aidl testAidl;

private ServiceConnection sc = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        testAidl = test_aidl.Stub.asInterface(service);
    }

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

之後就能直接透過這個物件呼叫 Service 中的方法了:

int count = testAidl.getCount();

五、重點整理與實務提醒

兩種啟動方式的選擇:如果你只是要「叫它做事,做完就好」,用 startService;如果需要「跟它保持連線、隨時呼叫它的方法」,用 bindService。兩者也可以混用——先 bind 再 start,Service 會持續存活直到兩者都解除。

AIDL 的本質:AIDL 產生的 Stub/Proxy 是一套 IPC 樣板。呼叫端拿到的 Proxy 會把方法呼叫序列化後送到 Service 進程,Service 端的 Stub 反序列化、執行、再把結果送回。這也解釋了為什麼跨進程傳遞的參數型別必須是 primitives 或實作 Parcelable/Serializable 的物件。

套件名稱必須一致。AIDL 檔在兩端的套件名稱與檔名都要相同,否則產生的 Java 介面不會匹配,編譯階段就會失敗。

呼叫端要處理例外。AIDL 方法都宣告丟出 RemoteException,因為遠程進程隨時可能崩潰或不存在。呼叫端必須 try-catch,並在 onServiceDisconnected 中把參照清空,避免後續呼叫落到失效的 Proxy 上。

版本演進:Service 需在背景長時間執行時,Android 8.0 之後必須改用 foreground service 並顯示常駐通知,否則會被系統限制;原本的 background service 限制也大幅收緊。本文的寫法反映的是早期 API 的行為,實際專案請對照目前版本的官方規範調整。

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