編輯:關於 Android 程式設計
從本篇開始,我們來探討Binder的調用過程與運行機制。本文不深入Binder驅動及底層實現,而是以AIDL的使用為切入點,理清Java層面上Binder的實現與跨進程通信過程。按照慣例,先總結AIDL的使用步驟,再依據源碼梳理其調用邏輯。
AIDL通常用於Service與其他組件(如Activity)之間的通信。之所以要用它,是因為它能幫助我們快速實現跨進程通信:當Service與Activity分處不同進程又需要互相通信時,AIDL正是理想的解決方案。
(1)編寫AIDL文件。需注意的是,AIDL文件只支持基本類型數據的遠程傳輸,自定義的實體對象則必須實現Parcelable接口。
(2)在Service中繼承Stub類,重寫aidl文件中定義的方法以實現具體業務。由於Stub是一個抽象類,aidl中的方法在Stub裡仍是待實現的空方法,編譯器會提示你需要實現哪些方法。以下是根據AIDL自動生成的類:
package com.example.appa; import android.os.IInterface; import android.util.Log; public interface CustomBinder extends android.os.IInterface { final String TAG = "Binder"; public static abstract class Stub extends android.os.Binder implements com.example.appa.CustomBinder { private static final java.lang.String DESCRIPTOR = "com.example.appa.Test"; public Stub() { this.attachInterface((IInterface) this, DESCRIPTOR); Log.e(TAG, "CustomBinder.Stub-->" + "Stub()構造器執行"); } public static com.example.appa.CustomBinder asInterface( android.os.IBinder obj) { if ((obj == null)) { return null; } android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR); if (((iin != null) && (iin instanceof com.example.appa.Test))) { return ((com.example.appa.CustomBinder) iin); } Log.e(TAG, "CustomBinder.Stub-->" + "asInterface()執行:" + iin); return new com.example.appa.CustomBinder.Stub.Proxy(obj); } @Override public android.os.IBinder asBinder() { Log.e(TAG, "CustomBinder.Stub-->" + "asBinder()"); return this; } @Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException { Log.e(TAG, "CustomBinder.Stub-->" + "onTransact()執行"); switch (code) { case INTERFACE_TRANSACTION: { reply.writeString(DESCRIPTOR); return true; } case TRANSACTION_hello: { Log.e(TAG, "CustomBinder.Stub-->" + "TRANSACTION_hello執行:服務端執行本地hello方法"); data.enforceInterface(DESCRIPTOR); java.lang.String _arg0; _arg0 = data.readString(); java.lang.String _result = this.hello(_arg0); reply.writeNoException(); reply.writeString(_result); return true; } } return super.onTransact(code, data, reply, flags); } private static class Proxy implements com.example.appa.CustomBinder { private android.os.IBinder mRemote; Proxy(android.os.IBinder remote) { mRemote = remote; } @Override public android.os.IBinder asBinder() { Log.e(TAG, "CustomBinder.Stub.Proxy-->" + "asBinder()執行"); return mRemote; } public java.lang.String getInterfaceDescriptor() { Log.e(TAG, "CustomBinder.Stub.Proxy-->" + "getInterfaceDescriptor()執行"); return DESCRIPTOR; } @Override public java.lang.String hello(java.lang.String content) throws android.os.RemoteException { Log.e(TAG, "CustomBinder.Stub.Proxy-->" + "hello()執行"); android.os.Parcel _data = android.os.Parcel.obtain(); android.os.Parcel _reply = android.os.Parcel.obtain(); java.lang.String _result; try { _data.writeInterfaceToken(DESCRIPTOR); _data.writeString(content); mRemote.transact(Stub.TRANSACTION_hello, _data, _reply, 0); _reply.readException(); _result = _reply.readString(); } finally { _reply.recycle(); _data.recycle(); } return _result; } } static final int TRANSACTION_hello = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0); } public java.lang.String hello(java.lang.String content) throws android.os.RemoteException; }
完成上述兩步,實際上就構建了一個Server端,接下來便是Client的使用。
(3)在Service中繼承Stub定義自己的Binder。
private class MyBinder extends CustomBinder.Stub { @Override public String hello(String content) throws RemoteException { String con = "這是從Service發出來的內容..." + content; Log.e(TAG, "TestService.MyBinder-->"+"hello()執行"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } return con; } }
(4)在Activity中實現ServiceConnection接口並創建實例。
private class MyServiceConnection implements ServiceConnection { @Override public void onServiceConnected(ComponentName name, IBinder service) { showToast("服務已連接"); mBinderConnection = CustomBinder.Stub.asInterface(service); try { String str = mBinderConnection.hello("來自Activity的問候"); Log.e(TAG, "MainActivity.MyServiceConnection-->" + "onServiceConnected()執行,此時Service已經連接上,Server和Client可以通信了"); } catch (RemoteException e) { e.printStackTrace(); } } @Override public void onServiceDisconnected(ComponentName name) { mBinderConnection = null; } }
(5)調用bindService()即可。
當Server端(TestService)與Client端(MainActivity)都準備就緒後,客戶端發起調用(例如調用hello()方法)時,其內部順序如下:
第一步:執行Stub的構造器。因為調用bindService()時,Service的onCreate中new了CustomBinder.Stub對象,從而觸發構造器。
第二步:執行Stub的asInterface(),在onServiceConnected()中獲取Binder驅動發送過來的Stub實例。
第三步:調用Stub.Proxy的hello()。由於TestService與當前Activity不在同一進程,會使用Proxy實例的hello(),它通過BinderProxy調用Stub的onTransact(),進入第四步。
第四步:調用Stub的onTransact(),它負責調用服務端本地的hello(),也就是TestService中繼承Stub重寫的那個方法(即TestService.MyBinder.hello())。
正如ServiceConnection的onServiceConnected()所示,客戶端通過Stub的asInterface()獲取遠程具體對象:
public void onServiceConnected(ComponentName name, IBinder service) { showToast("服務已連接"); mBinderConnection = CustomBinder.Stub.asInterface(service);
這裡要特別注意:若服務端(TestService)與客戶端(MainActivity)在同一進程,則service參數是我們在TestService中定義的MyBinder實例,對程序員而言是一個本地Binder;若不在同一進程,則service參數是一個android.os.Binder.BinderProxy實例。asInterface()的實現如下:
public static com.example.appa.CustomBinder asInterface( android.os.IBinder obj) { if ((obj == null)) { return null; } android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR); if (((iin != null) && (iin instanceof com.example.appa.Test))) { return ((com.example.appa.CustomBinder) iin); } Log.e(TAG, "CustomBinder.Stub-->" + "asInterface()執行:" + iin); return new com.example.appa.CustomBinder.Stub.Proxy(obj); }
正如註釋所言:若Server與Client在同一進程,就直接返回Binder實例,此時方法調用即本地調用;若不在同一進程,則返回一個Stub.Proxy實例,需要借助代理通過BinderProxy進行遠程調用。兩者區別顯著。
(1)服務端與客戶端在同一進程:若未指定TestService與Activity的process屬性,則調用hello()時會直接調用Stub的hello()(即MyBinder重寫的方法),無需走Stub.Proxy流程。
(2)服務端與客戶端不在同一進程:為TestService的process指定別名,讓它運行在另一進程。此時調用hello()實際走的是Stub.Proxy的hello():
@Override public java.lang.String hello(java.lang.String content) throws android.os.RemoteException { Log.e(TAG, "CustomBinder.Stub.Proxy-->" + "hello()執行"); android.os.Parcel _data = android.os.Parcel.obtain(); android.os.Parcel _reply = android.os.Parcel.obtain(); java.lang.String _result; try { _data.writeInterfaceToken(DESCRIPTOR); _data.writeString(content); mRemote.transact(Stub.TRANSACTION_hello, _data, _reply, 0); _reply.readException(); _result = _reply.readString(); } finally { _reply.recycle(); _data.recycle(); } return _result; }
其實Stub.Proxy的hello()什麼也沒「親自做」,它只是把必要數據寫入、讀出Parcel,再通過mRemote調用transact(),告知Binder驅動去通知服務端執行真正的hello()。由於此時mRemote是一個Binder.BinderProxy實例,transact()便是它的native方法,用於通知Binder驅動去調用服務端的onTransact()。當通過mRemote調用transact()時,客戶端線程會被掛起,直到服務端返回結果(確切地說,是等到Stub的onTransact()返回)。
(若服務端與客戶端在同一進程,則無此步。)上一節中,客戶端的請求經由Stub.Proxy交給了Binder驅動,驅動完成一系列操作後,通知服務端調用onTransact()來響應請求:
@Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException { Log.e(TAG, "CustomBinder.Stub-->" + "onTransact()執行"); switch (code) { case INTERFACE_TRANSACTION: { reply.writeString(DESCRIPTOR); return true; } case TRANSACTION_hello: { Log.e(TAG, "CustomBinder.Stub-->" + "TRANSACTION_hello執行:服務端執行本地hello方法"); data.enforceInterface(DESCRIPTOR); java.lang.String _arg0; _arg0 = data.readString(); java.lang.String _result = this.hello(_arg0); reply.writeNoException(); reply.writeString(_result); return true; } } return super.onTransact(code, data, reply, flags); }
關鍵這一行:java.lang.String _result = this.hello(),它調用了服務端自己的hello()(即TestService.MyBinder的hello()),拿到結果後寫回reply(也就是寫回Binder驅動)。隨後驅動喚醒仍處掛起狀態的客戶端線程並返回結果。至此,一次跨進程通信便圓滿完成。
若Server與Client在同一進程,Server會直接調用Service中的相關方法;若不在同一進程,則通過跨進程通信遠程調用:先是Stub的代理類使用BinderProxy執行其transact()(一個native方法,內部進行一系列函數調用),最終交由Binder驅動完成。通信過程中,Client進程陷入內核態,調用hello方法的線程掛起等待返回;驅動完成操作後喚醒Server進程,調用Server本地對象(Stub)的onTransact(由Server端線程池完成)。onTransact再調用服務端的hello()並把結果寫回驅動,驅動隨即喚醒掛起的Client線程返回結果。一次跨進程遠程調用就此落幕。
(1)IBinder:它是一個接口,代表一種跨進程傳輸的能力。只要實現了這個接口,對象就能被跨進程傳遞——這是驅動底層支持的。在跨進程數據流經驅動時,驅動會識別IBinder類型的數據,自動完成不同進程間Binder本地對象與代理對象的轉換。
(2)Binder:代表Binder本地對象。BinderProxy是Binder的內部類,代表遠程進程Binder對象的本地代理。這兩個類都繼承自IBinder,因而都具備跨進程傳輸能力;實際上,跨進程時Binder驅動會自動完成它們之間的轉換。
理清Server端與Client端的跨進程通信過程後,我們不難發現,這一切都建立在客戶端能獲取到服務端對象的基礎上——也就是Activity實現ServiceConnection接口,其onServiceConnected()為我們返回遠程服務端對象。那麼,這個方法究竟何時被調用、何時返回遠程對象呢?這正是bindService()所處理的問題,我們將在下一篇揭開bindService()之謎。
Android 記憶體洩漏檢測:LeakCanary 使用與實作
在 Android 開發中,記憶體洩漏是常見但不容易察覺的問題。LeakCanary 是一個專門用來偵測 Activity、Fragment 等物件是否被意外持有的工具。
深入理解了 Android 的任務(Task)與返回棧(Back Stack)
原文譯自官方文檔:https://developer.android.com/guide/components/tasks-and-back-stack.html 一個應
Android 經典面試題知識點總結(未完待續)
本文整理了 Android 面試中常見的一批核心知識點,涵蓋生命周期、四大組件、Handler 機制、性能優化與數據存儲等,適合複習鞏固。 1. Fragment 生命
移植 u-boot 2012.04.1 到 Mini2440(二):NorFlash 的識別與匹配
上一篇文章裡,我們完成了新建單板、時鐘與 SDRAM 的初始化,串口已經能正常印出啟動資訊,但畫面上還掛著一行錯誤提示。 這一篇就來把它解決掉。 一、從哪裡查起 直接搜