編輯:關於 Android 程式設計
AIDL 編程的基本步驟已在上一篇中介紹過(Android Studio 下的 AIDL 跨進程通信)。那篇只示範了如何傳遞 Java 基本型別與 Bitmap,但實務上經常需要傳遞一整個自訂物件。AIDL 做得到嗎?可以,網上也有不少資料。寫這篇的目的有兩個:一是當作自己的學習筆記,二是把踩過的坑分享出來。
AIDL 只支援 Java 基本型別,因此無法直接傳遞複雜型別的物件。Android 的解法是一套序列化機制:把物件序列化為位元組序列,傳到對端後再反序列化還原。
· 序列化:把 Java 物件轉換為位元組序列的過程。
· 反序列化:把位元組序列還原為 Java 物件的過程。
Java 本身有 Serializable 機制,Android 則另外提供了自己的 Parcelable。兩者的效能與使用情境差異請自行參考其他資料,這裡要記住的重點是:AIDL 傳的是序列化後的物件。
基本步驟與上一篇相同:在 main 目錄下建立 aidl 目錄,新增 IMyAidlInterface.aidl。假設要傳遞的物件是 Students,就在同一層建立 Students.java,並補上一個與它同名的 Students.aidl。目錄結構如下:

package com.example.xjp.aidla;
import android.os.Parcel;
import android.os.Parcelable;
public class Students implements Parcelable {
private int id;
private String name;
private String className;
private int age;
protected Students(Parcel in) {
id = in.readInt();
name = in.readString();
className = in.readString();
age = in.readInt();
}
public Students(int id, String name, String className, int age) {
this.id = id;
this.name = name;
this.className = className;
this.age = age;
}
public static final Creator<Students> CREATOR = new Creator<Students>() {
@Override
public Students createFromParcel(Parcel in) {
return new Students(in);
}
@Override
public Students[] newArray(int size) {
return new Students[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id); // 1
dest.writeString(name); // 2
dest.writeString(className);// 3
dest.writeInt(age); // 4
}
public void readFromParcel(Parcel source) {
id = source.readInt();
name = source.readString();
className = source.readString();
age = source.readInt();
}
// getter / setter 略
}
這裡最容易出錯:writeToParcel 的寫入順序與 readFromParcel 的讀取順序必須嚴格一致。寫入順序是 int → String → String → int,讀取順序也必須是 int → String → String → int,否則欄位會整個錯位,讀出來的資料一團亂。這種 bug 在編譯階段完全不會報錯,只能靠實際測試發現,所以要養成對照檢查的習慣。
package com.example.xjp.aidla; parcelable Students;
內容只有一行。注意 parcelable 的 p 是小寫,不是 Parcelable——這是語法規則,寫錯會編譯失敗。
package com.example.xjp.aidla;
import com.example.xjp.aidla.Students;
interface IMyAidlInterface {
int add(int arg1, int arg2);
String inStudentInfo(in Students student);
String outStudentInfo(out Students student);
String inOutStudentInfo(inout Students student);
}
三個方法的參數型別都是 Students,但前面各自帶了不同的方向修飾符,而這些修飾符是必須的,漏寫會直接編譯錯誤:
· in:參數由客戶端設定,也就是客戶端傳入、服務端接收。
· out:參數由服務端設定,相當於服務端的回傳值。
· inout:雙向都可以設定,可雙向溝通。
另外,介面中用到 Students 時一定要手動 import,即使兩者在同一個 package 下也一樣,否則會報找不到符號。
public class MyServer extends Service {
IMyAidlInterface.Stub mStub = new IMyAidlInterface.Stub() {
@Override
public int add(int arg1, int arg2) throws RemoteException {
return arg1 + arg2;
}
@Override
public String inStudentInfo(Students student) throws RemoteException {
return buildTable("table1", student);
}
@Override
public String outStudentInfo(Students student) throws RemoteException {
return buildTable("table2", student);
}
@Override
public String inOutStudentInfo(Students student) throws RemoteException {
// 這裡故意修改服務端的值,用來驗證 inout 的雙向性
student.setAge(22);
student.setClassName("090411");
return buildTable("table3", student);
}
private String buildTable(String title, Students s) {
return title + "\n"
+ "----------------------------------------------\n"
+ "| id | age | name | className |\n"
+ "----------------------------------------------\n"
+ "| " + s.getId() + " | " + s.getAge() + " | "
+ s.getName() + " | " + s.getClassName() + " |\n"
+ "----------------------------------------------";
}
};
@Override
public IBinder onBind(Intent intent) {
return mStub;
}
@Override
public void onCreate() {
super.onCreate();
Log.e("xjp", "the remote Process Name is ==>" + getCurProcessName(this));
}
@Override
public boolean onUnbind(Intent intent) {
Log.e("xjp", "the remote onUnbind......");
return super.onUnbind(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e("xjp", "the remote onDestroy......");
}
/** 取得當前進程名稱,用於驗證是否真的跑在另一個進程 */
private String getCurProcessName(Context context) {
int pid = android.os.Process.myPid();
ActivityManager mActivityManager =
(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningAppProcessInfo appProcess
: mActivityManager.getRunningAppProcesses()) {
if (appProcess.pid == pid) {
return appProcess.processName;
}
}
return null;
}
}
服務端的職責是依客戶端傳來的 Students 產生一張資訊表。在 AndroidManifest.xml 中註冊:
<service android:name="com.example.xjp.aidl.MyServer">
<intent-filter>
<action android:name="com.xjp.myService"></action>
</intent-filter>
</service>
可以加上 android:process 屬性指定獨立進程,也可以不加。不寫就是預設值,Service 會跑在當前應用的主進程;寫了則會覆蓋進程名,這也是驗證「跨進程」是否真的生效的直接方法。
準備好一切之後編譯,卻出現「找不到符號 類別 Students」。明明定義了、也 import 了,還是報錯——Android Studio 就會遇到這個問題。解法是在 build.gradle 中顯式把 aidl 目錄加入原始碼路徑:
sourceSets {
main {
java.srcDirs = ['src/main/java', 'src/main/aidl']
}
}
這行的意思是把 src/main/aidl 也當成 Java 原始碼目錄一起編譯。加上之後再 build 就正常了。
客戶端最省事:直接把服務端的整個 aidl 目錄複製過來即可,不需要重寫任何介面定義。客戶端同樣要加上面那行 sourceSets 配置。
public class MainActivity extends Activity {
private IMyAidlInterface mStub;
private TextView txt;
private boolean isBind;
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mStub = IMyAidlInterface.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
mStub = null;
}
};
public void bindService(View v) {
isBind = true;
Intent intent = new Intent();
intent.setAction("com.xjp.myService");
intent.setComponent(new ComponentName(
"com.example.xjp.aidl", "com.example.xjp.aidl.MyServer"));
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}
public void getTableInfo(View v) {
if (mStub == null) return;
try {
String info1 = mStub.inStudentInfo(new Students(1, "Jim", "090415", 18));
String info2 = mStub.outStudentInfo(new Students(2, "Lida", "090416", 17));
String info3 = mStub.inOutStudentInfo(new Students(3, "Tom", "090417", 16));
txt.setText(info1 + "\n===========line=========\n"
+ info2 + "\n===========line=========\n" + info3);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void unbindService(View v) {
if (isBind) {
isBind = false;
unbindService(serviceConnection);
}
}
@Override
protected void onDestroy() {
if (isBind) unbindService(serviceConnection);
super.onDestroy();
}
}

從三張表格的輸出可以驗證修飾符的行為:
· table1(in):表格內容完整顯示客戶端設定的值,證明 in 表示數值由客戶端傳入。
· table2(out):表格為空。客戶端雖然傳了 Students 進去,但內容不會被帶過去,證明 out 表示數值由服務端設定。
· table3(inout):id 與 name 保持客戶端傳入的值,而 age 從 16 變成 22、className 從 090417 變成 090411——這些都是服務端改的,證明 inout 允許雙向設定。
1. 方法參數前必須標明 in、out、inout 之一,否則編譯失敗。
2. 序列化物件的 writeToParcel 與 readFromParcel 讀寫順序必須完全一致,否則資料錯亂且不易察覺。
3. 凡是使用到 Students 的地方都要 import 完整套件路徑,同 package 也不例外。
4. 編譯前需在 build.gradle 加入 java.srcDirs = ['src/main/java', 'src/main/aidl']。
Android 接入騰訊開放平台實戰總結(一):QQ 登入與應用寶支付全流程
騰訊開放平台的接入,用過的人都懂:文檔分散、版本交叉、細節缺失。open.qq.com 上的資料又多又雜,社交類 API 更是琳瑯滿目。本文只聚焦最常見的兩塊——QQ 登
Android 源碼編譯環境搭建指南
編譯 Android 源碼通常需要 Linux 環境、足夠磁碟空間與完整依賴。Ubuntu 是常見選擇。安裝系統時應預留編譯空間,因為源碼、建置工具與輸出產物合計可能超過
取得 Android 設備已安裝應用清單:名稱、套件名與圖示
本文示範如何取得設備中已安裝的應用資訊,包含應用名稱、套件名稱、圖示等,並在清單中點選任一項時直接啟動對應的應用。 一、程式碼實作 package com.exampl
Android 動態生成課程表完整實作詳解
本文將示範如何依據提供的課程資訊,動態生成課程表。有別於網路上常見的課表形式,本方案的課程節數並非固定,每天可顯示不同數量的課程。 一、效果圖 每天共有 12 節課,但