AIDL (Android Interface Definition Language) 定義跨進程通訊介面。編譯器自動生成實現 IBinder 的 Stub 類,處理序列化/反序列化 (marshalling),讓客戶端像呼叫本地方法一樣呼叫遠端 Service 方法。
.aidl,置於 src/main/aidl/ (Gradle 自動識別)。public/private,預設公開。String、CharSequence、List、Map (元素需為支援類型)、Parcelable 實現類、其他 AIDL 介面。in (預設)、out、inout,指定資料流向優化序列化。src/main/aidl/com/example/aidlservicedemo/domain/IDog.aidl
package com.example.aidlservicedemo.domain;
interface IDog {
String getName();
int getAge();
}
public class BaseTypeService extends Service {
private static final String TAG = "AIDLService";
private final IDog.Stub binder = new IDog.Stub() {
private final String[] names = {"小白", "旺財", "小黑"};
private final int[] ages = {1, 2, 3};
private final Random random = new Random();
@Override public String getName() throws RemoteException {
return names[random.nextInt(names.length)];
}
@Override public int getAge() throws RemoteException {
return ages[random.nextInt(ages.length)];
}
};
@Override public void onCreate() {
super.onCreate();
Log.i(TAG, "Service Created");
}
@Override public IBinder onBind(Intent intent) {
Log.i(TAG, "Client Bound");
return binder;
}
}
<service
android:name=".BaseTypeService"
android:exported="true"
android:process=":remote"> <!-- 獨立進程模擬跨進程 -->
<intent-filter>
<action android:name="com.example.aidlservicedemo.BaseTypeService" />
</intent-filter>
</service>
public class BaseTypeActivity extends AppCompatActivity {
private IDog dogService;
private final ServiceConnection conn = new ServiceConnection() {
@Override public void onServiceConnected(ComponentName name, IBinder binder) {
dogService = IDog.Stub.asInterface(binder); // 關鍵:轉為介面代理
Toast.makeText(BaseTypeActivity.this, "服務連線成功", Toast.LENGTH_SHORT).show();
}
@Override public void onServiceDisconnected(ComponentName name) {
dogService = null;
}
};
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service);
findViewById(R.id.btn_bind).setOnClickListener(v -> {
Intent intent = new Intent("com.example.aidlservicedemo.BaseTypeService");
intent.setPackage("com.example.aidlservicedemo"); // 顯式 Intent
bindService(intent, conn, Context.BIND_AUTO_CREATE);
});
findViewById(R.id.btn_unbind).setOnClickListener(v -> {
if (dogService != null) {
unbindService(conn);
dogService = null;
}
});
findViewById(R.id.btn_get).setOnClickListener(v -> {
if (dogService == null) {
Toast.makeText(this, "請先綁定服務", Toast.LENGTH_SHORT).show();
return;
}
try {
String name = dogService.getName();
int age = dogService.getAge();
Toast.makeText(this, "Name: " + name + ", Age: " + age, Toast.LENGTH_SHORT).show();
} catch (RemoteException e) {
Log.e("Client", "遠端呼叫失敗", e);
Toast.makeText(this, "呼叫失敗:" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
@Override protected void onDestroy() {
super.onDestroy();
if (dogService != null) unbindService(conn);
}
}
IBinder 轉為介面代理,內部實現 transact() 跨進程通訊。void 且標註 oneway,呼叫端不阻塞,系統佇列處理 (僅適用 Service 同進程或特定場景)。編譯後 gen/.../IDog.java 包含:
IDog (原定義)Stub extends Binder implements IDog:實現 onTransact() 解析 Parcel、分發呼叫、回寫結果。Proxy implements IDog:客戶端持有,將呼叫封裝為 Parcel 發送。簡單單向訊息可用 Messenger (內部封裝 Handler),無需編寫 AIDL。複雜高效能場景可直接繼承 Binder 實現自訂協議。