編輯:關於 Android 程式設計
近期研究 Android 二次開發時,接觸到一種常見做法:透過 AIDL 對外暴露接口,讓其他應用可以呼叫。這也說明了 AIDL 的本質——兩個應用之間的跨進程通信。本文以兩個專案為例:ServerDemo 作為服務端提供加法計算,ClientDemo 作為客戶端呼叫該接口並顯示結果。
AIDL 是 Android Interface Definition Language 的縮寫,是 Android 內部進程通信(IPC, Inter-Process Communication)的接口描述語言。透過它我們可以定義進程間的通信契約,系統再依此自動生成必要的 Binder 樣板程式碼。




服務端介面幾乎是空的,重點是那個加法服務;客戶端則有兩個輸入框與一顆計算鈕。
只要使用 Eclipse 加 ADT 開發,AIDL 檔會像資源檔一樣被自動編譯成 Java 進入 gen 目錄,不需手動處理。
// IBoardADDInterface.aidl
package com.example.server;
interface IBoardADDInterface {
int add(int nValue1, int nValue2);
}
編譯後生成的 IBoardADDInterface.java 大致如下,可以順便理解 Binder 的運作方式:
public interface IBoardADDInterface extends android.os.IInterface {
public static abstract class Stub extends android.os.Binder
implements com.example.server.IBoardADDInterface {
private static final String DESCRIPTOR = "com.example.server.IBoardADDInterface";
public Stub() {
this.attachInterface(this, DESCRIPTOR);
}
// 把 IBinder 轉成接口,失敗則建立 Proxy
public static com.example.server.IBoardADDInterface asInterface(android.os.IBinder obj) {
if (obj == null) return null;
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (iin != null && iin instanceof com.example.server.IBoardADDInterface) {
return (com.example.server.IBoardADDInterface) iin;
}
return new com.example.server.IBoardADDInterface.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_add:
data.enforceInterface(DESCRIPTOR);
int arg0 = data.readInt();
int arg1 = data.readInt();
int result = this.add(arg0, arg1);
reply.writeNoException();
reply.writeInt(result);
return true;
}
return super.onTransact(code, data, reply, flags);
}
private static class Proxy implements com.example.server.IBoardADDInterface {
private final android.os.IBinder mRemote;
Proxy(android.os.IBinder remote) { mRemote = remote; }
@Override
public int add(int nValue1, int nValue2) throws android.os.RemoteException {
android.os.Parcel data = android.os.Parcel.obtain();
android.os.Parcel reply = android.os.Parcel.obtain();
int result;
try {
data.writeInterfaceToken(DESCRIPTOR);
data.writeInt(nValue1);
data.writeInt(nValue2);
mRemote.transact(Stub.TRANSACTION_add, data, reply, 0);
reply.readException();
result = reply.readInt();
} finally {
reply.recycle();
data.recycle();
}
return result;
}
}
static final int TRANSACTION_add =
(android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
}
int add(int nValue1, int nValue2) throws android.os.RemoteException;
}
讀完這份自動生成的程式碼,AIDL 的原理就透明了:參數透過 Parcel 序列化寫入,呼叫走 transact,結果再從 reply 讀回。所謂「跨進程呼叫」,就是這套 Parcel 打包與 Binder 轉發的過程。
public class CaculateAddService extends Service {
private static final String CACULATE_ADD = "COM.CACULATE.ADD";
@Override
public IBinder onBind(Intent intent) {
if (CACULATE_ADD.equals(intent.getAction())) {
return mBinder;
}
return null;
}
// AIDL 接口的實作,業務邏輯寫在這裡
private final IBinder mBinder = new IBoardADDInterface.Stub() {
@Override
public int add(int nValue1, int nValue2) throws RemoteException {
Log.i("Show", nValue1 + " ,,, " + nValue2);
return nValue1 + nValue2;
}
};
}
用 action 字串來辨識服務,是為了讓同一個 App 能提供多種服務時可以分流;action 名稱由開發者自訂。
<service android:name="com.example.server.CaculateAddService">
<intent-filter>
<action android:name="COM.CACULATE.ADD" />
</intent-filter>
</service>
服務端到此完成。Activity 幾乎沒寫什麼,因為整個重點就是 Service 與 AIDL。
把服務端的 IBoardADDInterface.aidl 原封不動複製到客戶端,套件名稱必須保持一致,否則 DESCRIPTOR 對不上,asInterface 會永遠回傳 Proxy 而無法命中本地實作。
package com.example.server;
interface IBoardADDInterface {
int add(int nValue1, int nValue2);
}
public class CaculateManager {
private static final String CACULATE_ADD = "COM.CACULATE.ADD";
private IBoardADDInterface mService = null;
private Context mContext = null;
public void bindService(Context context) {
mContext = context;
context.bindService(new Intent(CACULATE_ADD),
serviceConnection, Context.BIND_AUTO_CREATE);
}
public void unbindService() {
if (mContext != null) {
mContext.unbindService(serviceConnection);
}
}
public int caculateAdd(int nValue1, int nValue2) {
if (mService == null) return 0;
try {
return mService.add(nValue1, nValue2);
} catch (Exception e) {
return 0;
}
}
private final ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// 關鍵:把 IBinder 轉成 AIDL 接口
mService = IBoardADDInterface.Stub.asInterface(service);
}
};
}
這個類封裝了綁定、解綁與接口呼叫三件事。注意 mService 必須在 onServiceConnected 之後才不為 null,所以呼叫時機要放在綁定成功之後。
public class MainActivity extends Activity {
private final CaculateManager caculateManager = new CaculateManager();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
caculateManager.bindService(this);
findViewById(R.id.button1).setOnClickListener(v -> {
EditText et1 = findViewById(R.id.editText1);
EditText et2 = findViewById(R.id.editText2);
int v1 = Integer.parseInt(et1.getText().toString().trim());
int v2 = Integer.parseInt(et2.getText().toString().trim());
int result = caculateManager.caculateAdd(v1, v2);
((TextView) findViewById(R.id.textView1))
.setText("計算結果:" + result);
});
}
@Override
protected void onDestroy() {
caculateManager.unbindService();
super.onDestroy();
}
}
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="使用 AIDL 服務調用其他程序計算,返回結果" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal" />
<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal" />
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="加法計算" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="計算結果:" />
</LinearLayout>
Android 向上推送式菜單實作
在百度地圖等需要保留手勢操作的應用中,側滑菜單可能與地圖手勢衝突。此時可改用向上推拉的菜單,透過按鈕觸發顯示與隱藏。 實作思路 版面配置可包含兩個主要區域:主視圖與菜
Android Studio 模板用法與自定義模板完全攻略
本文 gif 圖較多,可能導致頁面加載緩慢,請耐心等待。 今天我們來學習 Android Studio 這款工具的一些「黑科技」——Template(模板)。所謂模板
Android 特效專輯(八):實現心型氣泡飛舞特效,讓你的 APP 瞬間暖心
Android 特效專輯(八)——實現心型氣泡飛舞特效 臨近年假,家裡估計會斷網,更新完這篇可能要等到年後了。不過在此期間我會把更新內容保存在
小米手機軟體打不開/閃退?小米手機使用常見問題彙整
小米手機躋身全球前一大手機品牌,MIUI 用戶超過數千萬。以下彙整在使用小米手機過程中經常遇到的問題與解法。 1、軟體閃退、無法打開 打開「設定」→「應用程式」→ 找到