編輯:關於 Android 程式設計
AIDL 是 Android Interface Definition Language 的縮寫,本質上是一份「跨進程接口的契約」。它解決的是一個很現實的問題:Android 上,一個進程無法直接存取另一個進程的記憶體空間,因此當你要讓 A 應用的客戶端呼叫 B 應用的服務時,必須先把物件拆解成作業系統能理解的原始型態,依序序列化後送過進程邊界,另一端再還原。這段繁瑣又冗長的搬運程式碼,AIDL 幫你自動生成。
先潑一盆冷水:大多數應用都不需要 AIDL。只有同時滿足兩個條件時它才是必要的——你需要讓不同應用的客戶端跨進程存取你的 Service,而且你的 Service 需要處理多執行緒。
不論走哪條路,都請先讀懂 Bound Service 再動手。
這是最容易被忽略、也最容易釀成 bug 的一點:呼叫 AIDL 接口就是一次普通的函式呼叫,你不能假設它跑在哪一條執行緒上。
AIDL 用 Java 語法撰寫,每個 .aidl 檔案只能定義一個接口,內容僅包含接口宣告與方法簽名。檔案要放在服務端與所有客戶端的 src 目錄下。編譯時,Android SDK 工具會依據它產生 IBinder 接口,存到專案的 gen 目錄。
AIDL 預設支援的型別:
String、CharSequenceList:元素必須是上述型別、其他 AIDL 生成的接口,或你自己定義的 Parcelable。可以使用泛型;接收端實際收到的通常是 ArrayList。Map:限制同上,不支援泛型 Map;接收端實際收到的通常是 HashMap。除此之外的型別,即使在同一個套件內也必須寫 import。
撰寫時的注意事項:
in(輸入)、out(輸出)、inout(雙向)。基本型別預設支援且不可標註。
// IRemoteService.aidl
package com.example.android;
/** Example service interface */
interface IRemoteService {
/** Request the process ID of this service, to do evil things with it. */
int getPid();
/** Demonstrates some basic types that you can use as parameters
* and return values in AIDL. */
void basicTypes(int anInt, long aLong, boolean aBoolean,
float aFloat, double aDouble, String aString);
}
存檔後 build 一次,SDK 工具會在 gen 目錄產生檔名相同、副檔名為 .java 的 IBinder 檔案(IRemoteService.aidl → IRemoteService.java)。Eclipse 幾乎是即時生成;用 Ant 的話則在下次 ant debug 或 ant release 時產生。
生成的檔案裡有一個名為 Stub 的抽象子類,它繼承 Binder 並宣告了 aidl 中所有方法。你要做的就是繼承 Stub 並實作这些方法。
Stub 還定義了一些輔助方法,最值得注意的是 asInterface():它接收一個 IBinder(通常是 onServiceConnected() 回呼傳來的參數),並回傳 Stub 介面的實例。
private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
public int getPid() {
return Process.myPid();
}
public void basicTypes(int anInt, long aLong, boolean aBoolean,
float aFloat, double aDouble, String aString) {
// Does nothing
}
};
實作時的三條鐵律:
繼承 Service,覆寫 onBind() 並回傳 Stub 實作即可。
public class RemoteService extends Service {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
return mBinder; // 把接口交出去
}
private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
public int getPid() {
return Process.myPid();
}
public void basicTypes(int anInt, long aLong, boolean aBoolean,
float aFloat, double aDouble, String aString) {
// Does nothing
}
};
}
客戶端呼叫 bindService() 之後,onServiceConnected() 回呼會收到 onBind() 回傳的那個 mBinder。客戶端必須取得介面類別,所以若雙方不在同一個應用,客戶端專案也要有一份 .aidl 副本放在 src 下。收到 IBinder 後,用 Stub.asInterface() 把它轉型:
IRemoteService mIRemoteService;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mIRemoteService = IRemoteService.Stub.asInterface(service);
}
public void onServiceDisconnected(ComponentName className) {
Log.e(TAG, "Service has unexpectedly disconnected");
mIRemoteService = null;
}
};
可以,但有兩個前提:對端也必須有這個類別的程式碼,而且該類別必須實作 Parcelable。Parcelable 的意義在於讓 Android 系統能把物件拆解為可跨進程傳輸的連續基本單位。
要建立一個支援 Parcelable 的類別:
writeToParcel(),把物件目前的狀態寫進 Parcel。CREATOR 的靜態欄位,實作 Parcelable.Creator。// Rect.aidl package android.graphics; // Declare Rect so AIDL can find it and knows that it implements // the parcelable protocol. parcelable Rect;
import android.os.Parcel;
import android.os.Parcelable;
public final class Rect implements Parcelable {
public int left;
public int top;
public int right;
public int bottom;
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Rect createFromParcel(Parcel in) {
return new Rect(in);
}
public Rect[] newArray(int size) {
return new Rect[size];
}
};
public Rect() { }
private Rect(Parcel in) {
readFromParcel(in);
}
public void writeToParcel(Parcel out) {
out.writeInt(left);
out.writeInt(top);
out.writeInt(right);
out.writeInt(bottom);
}
public void readFromParcel(Parcel in) {
left = in.readInt();
top = in.readInt();
right = in.readInt();
bottom = in.readInt();
}
}
安全性提醒:從其他進程收到的資料一律視為不可信。上面 Rect 從 Parcel 讀進 4 個整數,但你必須自行驗證這些值落在合理範圍內,而不論對方是否刻意構造了惡意內容。
以一個自訂介面為例:
package com.cao.android.demos.binder.aidl;
import com.cao.android.demos.binder.aidl.AIDLActivity;
interface AIDLService {
void registerTestCall(AIDLActivity cb);
void invokCallBack();
}

編譯後會得到三個東西:
android.os.IInterface,與 aidl 中定義的接口一一對應。android.os.Binder,在 onTransact() 中接收通信資料,依 code 分派到對應的介面方法,並回寫結果。由服務端實作。這個結構與 axis 依 WSDL 產生 client/server 骨架的思路是一致的:Stub 與 Proxy 把進程通信的細節完全封裝起來,使用者眼中就只是一次普通的介面呼叫。
1. 服務端實作 Stub,並在 onBind 回傳:
@Override
public IBinder onBind(Intent intent) {
return mBinder; // mBinder 為 AIDLService.Stub 的實作
}
2. 客戶端在 onServiceConnected 取得 IBinder:
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mService = AIDLService.Stub.asInterface(service);
try {
mService.registerTestCall(mCallback);
} catch (RemoteException e) {
e.printStackTrace();
}
}
};
// 別忘了把它傳進去
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
3. asInterface() 的關鍵分支:
public static AIDLService asInterface(android.os.IBinder obj) {
if (obj == null) {
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
// 若綁定的是同進程 Service,直接回傳 Stub 本身,根本不進程通信
if (iin != null && iin instanceof AIDLService) {
return (AIDLService) iin;
}
// 否則回傳 Proxy 包裝 BinderProxy
return new AIDLService.Stub.Proxy(obj);
}
這段程式說明了一件很重要的事:AIDL 在跨進程時才真的走 IPC,同進程時會自動退化成本地直接呼叫。
4. Proxy 方法的實作:
public void invokCallBack() throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
// DESCRIPTOR 描述要呼叫哪個 Stub 物件
_data.writeInterfaceToken(DESCRIPTOR);
// TRANSACTION_invokCallBack 標識要呼叫 Stub 中的哪個方法
// mRemote 即 BinderProxy,負責跨進程搬運資料
mRemote.transact(Stub.TRANSACTION_invokCallBack, _data, _reply, 0);
_reply.readException();
} finally {
_reply.recycle();
_data.recycle();
}
}
5. 進入 native 層:
public native boolean transact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException;
// 對應 JNI:/frameworks/base/core/jni/android_util_Binder.cpp
// → static jboolean android_os_BinderProxy_transact(...)
6. 服務端接收,呼叫堆疊:
AIDLService.Stub.onTransact AIDLService.Stub(Binder).execTransact NativeStart.run
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_registerTestCall:
data.enforceInterface(DESCRIPTOR);
AIDLActivity _arg0 = AIDLActivity.Stub.asInterface(data.readStrongBinder());
this.registerTestCall(_arg0);
reply.writeNoException();
return true;
case TRANSACTION_invokCallBack:
data.enforceInterface(DESCRIPTOR);
this.invokCallBack(); // 由服務端的 Stub 子類實作
reply.writeNoException();
return true;
}
return super.onTransact(code, data, reply, flags);
}
Context.bindService(),傳入 ServiceConnection。onServiceConnected() 中取得 IBinder。YourInterface.Stub.asInterface(service) 完成轉型。DeadObjectException——這是遠程方法唯一會拋出的異常。Context.unbindService() 解除連線。另外記得:跨進程傳遞的物件是引用計數的,而你可以把匿名物件當作方法參數傳過去。
AIDL 的表層是「寫一個介面描述檔,工具幫你生成 Java 骨架」,底層則是 Binder 驅動 + JNI + native 的 Parcel 搬運。理解 Stub / Proxy 的分工、asInterface 的同進程捷徑、以及 onTransact 的 code 分派,就足以應付九成的Framework 閱讀需求;再往下的 C++ 層如何完成實際的進程通信,則是另一個主題了。
Android CheckBox 複選框的用法與監聽處理
CheckBox 是介面開發中最常見的多選控制項。Android 的實作方式很直接:每個 CheckBox 各自掛一個 CompoundButton.OnCheckedC
掌握 Android 視窗顯示狀態:requestWindowFeature() 的實際應用
在日常開發中,我們經常會遇到諸如「讓程式全屏顯示」、「自訂標題列(例如在標題上放入按鈕等控制項)」之類的需求。今天這一篇,就來談談如何靈
Android 開發之 ToggleButton 開關控件用法
ToggleButton 可以理解為一個兩態開關:每點擊一次,就在「開」與「關」之間切換,同時可以分別顯示不同的文案與背景圖,常用於功能啟停、狀態切換等交互。 常用方法
Android 中的訊息通知:NotificationManager 與 Notification 用法整理
來談談 Notification。它最常見的場景是電話、簡訊、郵件、鬧鐘——手機狀態條上會浮現一個小圖示提示使用者處理,從上方滑下狀態條就能展開並處理這則快訊。Andro