Binder 機制研究,demo + 解析

github demo 地址:
https://github.com/jjbheda/aidl_demo

#1. 基本定義
##1.1 IPC
IPC (Inter Process Communication,進程間通信。指至少兩個進程或線程間傳送數據或信號的一些技術或方法。

##1.2 AIDL
AIDL (Android Interface Definition Language)Android 接口定義語言。與您可能使用過的其他接口語言 (IDL) 類似。
您可以利用它定義客戶端與服務均認可的編程接口,以便二者使用進程間通信 (IPC) 進行相互通信。
在 Android 中,一個進程通常無法訪問另一個進程的內存。進程通信操作的代碼較爲繁瑣,因此 Android 使用 AIDL 簡化處理該問題。

2. 不同IPC 比較

image.png

#3. 基本原理
image.png

image.png

image.png

#4 大體流程
image.png

  • 總體
    Client 端,主要通過 Proxy ,調用接口。
    Service端,Stub 接收後,主要通過自身的接口實現(通常是自己實現的Service),來處理客戶端的接口請求。 然後通過binder機制返回數據給客戶端。

  • 服務端
    主要是生成Binder 併發送給客戶端,內部調用asBinder()

public class PwdService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }
    private IBinder binder = new IPwdInterface.Stub() {
        @Override
        public boolean verifyPwd(User user) throws RemoteException {
           if (user == null || user.name == null
                   || user.pwd == null) {
               return false;
           }
           if (user.name.equals( "abc") && user.pwd.equals("123")) {
               return true;
           }
            return false;
        }
    };
}
  • 客戶端
    拿到服務端的Binder(調用bindService),並轉換成自身可以使用的接口,直接使用,調用asInterface()
 private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.w(TAG, "onServiceConnected: success ");
            pwdInterface = IPwdInterface.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.w(TAG, "onServiceDisConnected! ");
            unbindService(serviceConnection);
        }
    };
 if (pwdInterface != null) {
                try {
                    boolean verify = pwdInterface.verifyPwd(new User(name, pwd));
                    if (verify) {
                        Toast.makeText(this, "驗證成功!!!", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(this, "驗證失敗!!!", Toast.LENGTH_LONG).show();
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

5. 存在意義

  1. Android四大組件通信方式。
  2. Binder 從整體上來說是一種 IPC 機制,Android 是Binder 消息驅動。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章