編輯:關於 Android 程式設計
上一篇講了 Android 中「一個進程 = 一個 VM + 一個主線程 + 一個 Looper + 一個 MessageQueue」,這篇用一個小 Demo 把 IBinder 跨進程通信說清楚。
場景設計很簡單:進程 A 放一個 MainActivity,上面幾個按鈕;進程 B 跑一個 Service,專職播放音樂。點 A 的按鈕去控制 B 放歌,順便把 IPC 到底是怎麼回事講明白。
public class MainActivity extends AppCompatActivity {
private IBinder ib = null;
private Button bt_1, bt_2, bt_3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_1 = (Button) findViewById(R.id.bt_1);
bt_2 = (Button) findViewById(R.id.bt_2);
bt_3 = (Button) findViewById(R.id.bt_3);
bt_1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Parcel parcel = Parcel.obtain();
Parcel parcelReply = Parcel.obtain();
parcel.writeString("play");
try {
ib.transact(1, parcel, parcelReply, 0); // code = 1 表示播放
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
bt_2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Parcel parcel = Parcel.obtain();
Parcel parcelReply = Parcel.obtain();
parcel.writeString("stop");
try {
ib.transact(2, parcel, parcelReply, 0); // code = 2 表示停止
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
bt_3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { finish(); }
});
startService(new Intent(this, myService.class));
bindService(new Intent(this, myService.class), conn, BIND_AUTO_CREATE);
}
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
ib = service; // 拿到通信工具
}
@Override
public void onServiceDisconnected(ComponentName name) { }
};
}
回顧一下應用啟動的過程:點擊圖標後,zygote 孵化出一個新進程,裡面有主線程、VM、Looper、MessageQueue;主線程在 while 循環裡轉圈,框架 new 出 MainActivity 並發消息讓它執行 onCreate()。
而開發者自己是不能 new Service 的,只能在 Manifest 裡聲明,再由框架根據聲明去創建:
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.gray_dog3.ibindertest">
<application>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".myService"
android:process=":remote" />
</application>
</manifest>
關鍵就在 android:process=":remote":它告訴框架,這個 Service 要放在一個獨立進程裡。於是框架孵化新進程、new 出 myService 放進去,這個進程的主線程同樣在自己的 while 循環裡待命,收到 Message 後執行 onCreate()。
public class myService extends Service {
private IBinder iBinder = null;
private static ContrlSong contrlSong;
@Override
public void onCreate() {
iBinder = new myBinder();
contrlSong = new MySongContrler(getApplicationContext());
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return iBinder;
}
public static void play() { contrlSong.play(); }
public static void stop() { contrlSong.stop(); }
}
現在兩個進程都有了:MA(MainActivity)在自己的進程裡轉圈,MS(myService)在另一個進程裡轉圈。如果兩者在同一進程,MA 直接 myService.play() 就完事了;但事實是它們不在一個進程。
原因很直接:每個進程擁有獨立的內存空間,彼此隔離。MA 拿不到 MS 的方法地址,就像一個 Facebook 用戶沒法直接加 QQ 好友。要交流,必須借助一個雙方都認的「中介」——Android 提供的這個中介就是 IBinder。
bindService(new Intent(this, myService.class), conn, BIND_AUTO_CREATE);
第一個參數 Intent 表明這件事要交給框架去做;第二個 conn 是個 ServiceConnection,性質和 OnClickListener 一樣,是「綁定完成後的觸發器」,它在類加載時就已經存在。
MA 主線程發出 bind 請求後就繼續轉圈了。框架把 bind 做完,再發一條 Message 回來,Message 裡帶著一個 IBinder 對象;MA 主線程被喚醒後執行 conn.onServiceConnected(),其中 ib = service; 就是把這個通信工具的引用存下來。
MS 這邊對應的邏輯是:
@Override
public void onCreate() {
iBinder = new myBinder();
contrlSong = new MySongContrler(getApplicationContext());
}
@Override
public IBinder onBind(Intent intent) {
return iBinder; // 框架在 MA 發起 bindService 後調用此方法
}
MS 把 iBinder 交給框架,框架轉交給 MA,於是雙方看似拿到了「同一個」對象。之所以要加引號,是因為它們其實不是同一個:MS 持有的是 Binder,MA 持有的是 BinderProxy,後者是前者的「分身」。真正的數據傳輸由框架和底層 Linux 完成,框架負責保證本尊與分身同步,對上層完全透明。
IBinder 接口及其兩個實現 Binder、BinderProxy 都由框架提供。名字不重要,本質就是:MA 和 MS 同時持有一個對象,這個對象有寫方法和讀方法,一個寫一個讀就能通信。代碼裡 MA 的 ib 是 BinderProxy 類型,MS 的 iBinder 是 Binder 類型,但對開發者而言可以視為同一個對象。
MA 中的 ib.transact(1, parcel, parcelReply, 0) 就是「寫」;MS 中的 iBinder.onTransact() 就是「讀」。MA 寫完,框架通知 MS 來讀:
public class myBinder extends Binder {
@Override
protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
if (code == 1) myService.play();
if (code == 2) myService.stop();
return true;
}
}
那 Parcel 是什麼?它是 Android 的序列化容器。序列化就是把要傳的數據轉成一種雙方約定的格式——反正底層都是二進制,只要規定好 String 怎麼表示、對象怎麼表示,出發前打包、到達後解包即可。
為什麼非要這一步?因為真正的 IPC 並不在 Java 層,底層代碼用什麼語言、什麼數據結構實現,上層無從得知;直接把 Java 對象的內存布局扔過去,對方看到的是一堆亂碼。何況對象本身佔空間大,不利於高速讀寫。約定格式才是跨邊界傳遞的可行解。
public interface ContrlSong {
void play();
void stop();
}
public class MySongContrler implements ContrlSong {
private MediaPlayer mediaPlayer = null;
private Context context;
MySongContrler(Context context) {
this.context = context;
}
@Override
public void play() {
if (mediaPlayer != null) return;
mediaPlayer = MediaPlayer.create(context, R.raw.song);
mediaPlayer.start();
}
@Override
public void stop() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
}
1. 框架為兩個進程各分配一個主線程,各自在自己的消息循環裡待命;
2. MA 調用 startService + bindService,框架創建並啟動 MS;
3. MS 在 onCreate 中準備好 Binder,並在 onBind 時把它交給框架;
4. 框架為 MA 生成 BinderProxy,通過 onServiceConnected 回傳;
5. MA 調用 transact 寫數據,框架通知 MS 的 onTransact 讀數據;
6. 雙方通過約定的 code 與 Parcel 內容完成一次「方法調用」。
這就是 IBinder 最直觀的用法。真實系統中的 Binder 還要處理線程池、死亡通知、權限校驗、引用計數等問題,AIDL 工具也正是把這套模板自動生成出來,讓開發者只需關注接口定義。
自製 Android 圖表庫 XCL-Charts 效果展示
我一直相信,靈感來了就要抓住,有了興趣就要深入研究。所以即使最近很忙,我仍然沒有放下 Android 圖表實作的研究。如今,我的圖表庫基礎架構已經頗具雛形,不再只是小打小
自定義 Android 窗口標題欄樣式的實現
Android 默認的窗口標題欄(Window Title)在很多時候不合用:高度不夠、配色與界面不協調、或者只是想換個視覺風格。當需求僅停留在樣式層面時,不必寫自定義
Android ListView 加入 CheckBox 的實作原理與完整程式碼
在 ListView 裡放入 CheckBox,看似簡單,實則暗藏不少細節,特別是效能優化與事件處理。本文透過一個可全選、可取消的範例,帶你理解它的運作原理與實作重點。
Android 自定義手勢密碼簡易版實作
簡易九宮格手勢若要快速實作手勢密碼,可先建立一個自訂 View,在畫布上畫出九個圓點。每個圓點需要記錄編號、座標與是否被選中,當手指滑過時,就將符合範圍的圓點加入連線。初