編輯:關於 Android 程式設計
前言:在做一件事之前,千萬別先覺得它很難。還沒開始就先在內心產生恐懼,只會阻礙你的進步——往往真的動手做完,才發現沒那麼複雜。
AIDL 全名是 Android Interface Definition Language(Android 介面定義語言),用來定義「用戶端與伺服器通訊介面」的標準與規範。
回顧四大元件:Activity、Broadcast、ContentProvider、Service。前三者我們都見過跨進程的例子——一個應用可以明示意圖啟動另一個應用的 Activity、可以送出廣播被其他應用接收、可以對外提供 ContentProvider 讓其他應用用 ContentResolver 取資料。Service 同樣能實現跨進程通訊,這就是本文的主題。
官方文件對使用時機有很明確的提示:
Using AIDL is necessary only if you allow clients from different applications to access your service for IPC and want to handle multithreading in your service. If you do not need to perform concurrent IPC across different applications, you should create your interface by implementing a Binder or, if you want to perform IPC, but do not need to handle multithreading, implement your interface using a Messenger. Regardless, be sure that you understand Bound Services before implementing an AIDL.
白話是:只有當你允許不同應用的用戶端透過 Service 進行跨進程通訊、且需要在 Service 中處理多執行緒時,才需要 AIDL。若不需要跨應用的即時通訊,用 Binder 實作介面即可;若要跨進程但不需要多執行緒,用 Messenger 更簡單。無論如何,先理解 Bound Service 再來碰 AIDL。
結論:AIDL 就是讓兩個不同應用透過 Service 通訊(IPC),且遠端 Service 能處理多執行緒,本質上是 C/S 模式。
實作步驟:
onBind() 回傳 Stub 實例,把介面暴露給用戶端先建立一個 Module 作為服務端應用。Android Studio 雖然能直接新增 AIDL 檔並自動產生 aidl 資料夾,但產生的套件名稱就是應用套件名,改起來有點麻煩——而用戶端與服務端的 AIDL 檔(含套件名)必須完全一致,所以這裡改用手動方式:在 main 下建立 aidl 資料夾,再在其中建一個套件(名稱自訂,但兩端要一致),然後建立 IRemoteService.aidl。
AIDL 的語法規則:
寫法與 Java 介面幾乎相同,差別是不要 public 修飾符:
// IRemoteService.aidl
package com.lt.aidl;
interface IRemoteService {
/** 展示可用的基本型別 */
void basicTypes(int anInt, long aLong, boolean aBoolean,
float aFloat, double aDouble, String aString);
/** 取得本服務的 process ID */
int getPid();
/** 依 id 取得名稱 */
String getName(int id);
}
存檔後編譯器會自動產生 IRemoteService.java(在 Packages 檢視中可見)。這個檔案不需要我們閱讀或修改。

打開自動產生的介面,會看到一個內部靜態抽象類 Stub,它繼承 Binder 並實作了該介面。因此我們可以直接用 Stub 完成遠端服務:
package com.lt.remoteservice.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import com.lt.aidl.IRemoteService;
public class RemoteService extends Service {
private String[] names = {"呂布", "關羽", "趙子龍", "張飛"};
/** 回傳代理物件 IBinder 給用戶端 */
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
@Override
public void basicTypes(int anInt, long aLong, boolean aBoolean,
float aFloat, double aDouble, String aString)
throws RemoteException {
System.out.println("Thread: " + Thread.currentThread().getName());
System.out.println("basicTypes aDouble: " + aDouble + " anInt: " + anInt
+ " aBoolean " + aBoolean + " aString " + aString);
}
@Override
public int getPid() throws RemoteException {
System.out.println("Thread: " + Thread.currentThread().getName());
return android.os.Process.myPid();
}
@Override
public String getName(int id) throws RemoteException {
return names[id];
}
};
}
別忘了在清單檔註冊 Service,並提供一個帶 action 的 intent-filter(用戶端通常用隱式意圖啟動),action 值可自訂:
<service android:name=".service.RemoteService">
<intent-filter>
<action android:name="lt.test.aidl" />
</intent-filter>
</service>
建立另一個 Module,同樣建立 aidl 資料夾並把服務端的 aidl 檔原封不動複製過來(套件名務必一致)。
版面配置:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="輸入查詢 ID" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="search"
android:text="查詢" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="結果:" />
<TextView
android:id="@+id/tv_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
重點來了——建立 ServiceConnection:
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// service 是代理物件,必須轉型成 AIDL 介面物件
mRemoteService = IRemoteService.Stub.asInterface(service);
try {
int pid = mRemoteService.getPid();
int currentPid = android.os.Process.myPid();
System.out.println("currentPID: " + currentPid + " remotePID: " + pid);
mRemoteService.basicTypes(12, 1223L, true, 12.2f, 12.3, "有夢就要去追,加油!");
} catch (RemoteException e) {
e.printStackTrace();
}
System.out.println("bind success! " + mRemoteService.toString());
}
@Override
public void onServiceDisconnected(ComponentName name) {
mRemoteService = null;
}
};
要點:連線成功後回傳的 IBinder 必須透過 IRemoteService.Stub.asInterface(service) 轉成 AIDL 物件,它才是遠端服務的代理。
用隱式意圖綁定:
Intent intent = new Intent();
intent.setAction("lt.test.aidl"); // 對應服務端清單檔的 action
intent.setPackage("com.lt.remoteservice"); // 服務所在應用的套件名
boolean isConnSuccess = bindService(intent, conn, Context.BIND_AUTO_CREATE);
注意:
互動邏輯:
public void search(View view) {
if (!isConnSuccess) {
System.out.println("連接失敗!");
return;
}
int id = Integer.valueOf(mEditText.getText().toString());
try {
String name = mRemoteService.getName(id);
mTv_result.setText(name);
} catch (RemoteException ex) {
ex.printStackTrace();
}
}
完整 Activity:
package com.lt.remoteclient;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.lt.aidl.IRemoteService;
public class MainActivity extends Activity {
private IRemoteService mRemoteService;
private TextView mTv_result;
private EditText mEditText;
private boolean isConnSuccess;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditText = (EditText) findViewById(R.id.editText);
mTv_result = (TextView) findViewById(R.id.tv_result);
Intent intent = new Intent();
intent.setAction("lt.test.aidl");
intent.setPackage("com.lt.remoteservice");
isConnSuccess = bindService(intent, conn, Context.BIND_AUTO_CREATE);
}
public void search(View view) {
if (!isConnSuccess) {
System.out.println("連接失敗!");
return;
}
int id = Integer.valueOf(mEditText.getText().toString());
try {
mTv_result.setText(mRemoteService.getName(id));
} catch (RemoteException ex) {
ex.printStackTrace();
}
}
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mRemoteService = IRemoteService.Stub.asInterface(service);
try {
System.out.println("currentPID: " + android.os.Process.myPid()
+ " remotePID: " + mRemoteService.getPid());
mRemoteService.basicTypes(12, 1223L, true, 12.2f, 12.3, "有夢就要去追,加油!");
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
mRemoteService = null;
}
};
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(conn); // 一定要反綁定
}
}
先執行服務端、再執行用戶端,可以看到雙方 PID 明顯不同:

後台日誌:

確實處在兩個不同進程中,用戶端既能傳基本型別給服務端,也能取回查詢結果——跨進程通訊完成。
上面只傳了基本型別。要傳自訂物件,該物件必須實作 Parcelable 介面(系統會把它拆解成基本型別再在進程間傳遞)。
步驟:
writeToParcel(Parcel dest, int flags),把物件狀態寫入 ParcelCREATOR,型別為 Parcelable.Creator<T>步驟 1~3:建立 Person 類別
package com.lt.aidl;
import android.os.Parcel;
import android.os.Parcelable;
public class Person implements Parcelable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
private Person(Parcel in) {
readFromParcel(in);
}
private void readFromParcel(Parcel in) {
this.name = in.readString();
this.age = in.readInt();
}
/**
* 要序列化傳遞的實體類別內部一定要宣告這個常量,
* 名稱只能是 CREATOR,型別必須是 Parcelable.Creator<T>
*/
public static final Creator<Person> CREATOR = new Creator<Person>() {
/** 依 Parcel 反序列化回原物件,讀取順序必須與 writeToParcel 的寫入順序相同 */
@Override
public Person createFromParcel(Parcel in) {
return new Person(in.readString(), in.readInt());
}
@Override
public Person[] newArray(int size) {
return new Person[size];
}
};
@Override
public int describeContents() {
return 0;
}
/**
* 把物件寫入 Parcel(序列化)
* 注意:寫入順序必須與 createFromParcel 的讀取順序完全一致
*/
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(age);
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}
步驟 4:在 Person 所在的套件建立同名 aidl 檔 Person.aidl:
package com.lt.aidl; parcelable Person;
此時專案結構:

把 Person.java 與 Person.aidl 複製到用戶端的相同位置,然後重新建置。
直接這樣建置,Android Studio 會報找不到自訂型別的錯誤(這個問題折騰了我幾個小時)。解法是在 gradle 檔中把 aidl 也加入 sourceSets:
sourceSets {
main {
manifest.srcFile 'src/main/AndroidManifest.xml'
java.srcDirs = ['src/main/java', 'src/main/aidl']
resources.srcDirs = ['src/main/java', 'src/main/aidl']
aidl.srcDirs = ['src/main/aidl']
res.srcDirs = ['src/main/res']
assets.srcDirs = ['src/main/assets']
}
}
完整的 gradle 檔:
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
applicationId "com.lt.remoteclient"
minSdkVersion 11
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
sourceSets {
main {
manifest.srcFile 'src/main/AndroidManifest.xml'
java.srcDirs = ['src/main/java', 'src/main/aidl']
resources.srcDirs = ['src/main/java', 'src/main/aidl']
aidl.srcDirs = ['src/main/aidl']
res.srcDirs = ['src/main/res']
assets.srcDirs = ['src/main/assets']
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.0.1'
}
重新建置後問題就解決了。分別執行兩個應用,測試結果如下:

AIDL 作為介面定義語言有自己的語法,寫法近似 Java 介面,因此也有人直接建立介面後把副檔名改成 .aidl。要記住:AIDL 只在「不同應用需要即時通訊」且「需要處理多執行緒」時才必要,其他情況用 Messenger 或普通 Binder 就好。它預設支援大多數型別,但要傳遞物件,就必須實作 Parcelable 並補上同名 aidl 檔。
writeToParcel 中讀寫順序必須嚴格一致;傳大物件會觸發 Binder 緩衝區限制(約 1MB,還要扣除其他程序用量),大資料請改用 URI 或檔案路徑傳遞。compile 寫法與 support 套件已停舊,新專案請改用 implementation 與 AndroidX。
Android 開發踩坑:Fragment 使用動畫引發 Unknown animation name: objectAnimator 異常
為 Fragment 製作切換動畫時,啟動後遇到了一個異常: Caused by: java.lang.RuntimeException: Unknown animat
Chromium 如何為 video 標籤渲染影片畫面
前言在 Chromium 中,video 標籤的畫面並不是簡單地把播放器視窗塞進網頁,而是透過一套跨進程、跨線程的渲染鏈路完成。核心思路是讓播放器把解碼結果寫入 GPU
Android 速覽:一張圖看懂 View 生命週期
Android 自助餐之 View 生命週期學習自訂 View 時,掌握它的生命週期是必修的一課。View 從被建立、測量、佈局到繪製,有著一套清晰的流程,而各個回呼方法
用 SpannableString 讓 TextView 顯示效果更豐富:SpannableUtils 工具類實作
做 TextView 時常會遇到這樣的需求:一整段文字裡,只有中間幾個字要加粗、換色、加上標或做成超連結。用好幾個 TextView 硬湊當然做得到,但只要特殊處理的片段