Aidl進程間通訊詳細介紹

目錄介紹

  • 1.問題答疑
  • 2.Aidl相關屬性介紹php

    • 2.1 AIDL所支持的數據類型
    • 2.2 服務端和客戶端
    • 2.3 AIDL的基本概念
  • 3.實際開發中案例操做java

    • 3.1 aidl通訊業務需求
    • 3.2 操做步驟僞代碼
    • 3.3 服務端操做步驟
    • 3.4 客戶端操做步驟
    • 3.5 測試
  • 4.可能出現的問題android

    • 4.1 客戶端在子線程中發起通訊訪問問題
    • 4.2 什麼狀況下會致使遠程調用失敗
    • 4.3 設置aidl的權限,須要經過權限才能調用
  • 5.部分源碼解析git

    • 5.1 服務端aidl編譯生成的java文件
    • 5.2 客戶端綁定服務端service原理

關於aidl應用案例

關於連接

1.問題答疑

  • 1.1.0 AIDL所支持的數據類型有哪些?
  • 1.1.1 提供給客戶端鏈接的service何時運行?
  • 1.1.2 Stub類是幹什麼用的呢?
  • 1.1.3 如何解決遠程調用失敗的問題?

2.Aidl相關屬性介紹

2.1 AIDL所支持的數據類型

  • 在AIDL中,並不是支持全部數據類型,他支持的數據類型以下所示:github

    • 基本數據類型(int、long、char、boolean、double、float、byte、short)
    • String和CharSequence
    • List:只支持ArrayList,而且裏面的每一個元素必須被AIDL支持
    • Map: 只支持HashMap, 一樣的,裏面的元素都必須被AIDL支持,包括key和value
    • Parcelable:全部實現了Parcelable接口的對象
    • AIDL: 全部的AIDL接口自己也能夠在AIDL 文件中使用

2.2 服務端和客戶端

  • 2.2.1 服務端segmentfault

    • 注意:服務端就是你要鏈接的進程。服務端給客戶端一個Service,在這個Service中監聽客戶端的鏈接請求,而後建立一個AIDL接口文件,裏面是將要實現的方法,注意這個方法是暴露給客戶端的的。在Service中實現這個AIDL接口便可
  • 2.2.2 客戶端服務器

    • 客戶端首先須要綁定服務端的Service,綁定成功後,將服務端返回的Binder對象轉換成AIDL接口所屬的類型,最後調用AIDL的方法就能夠了。

2.3 AIDL的基本概念

  • AIDL:Android Interface Definition Language,即Android接口定義語言;用於讓某個Service與多個應用程序組件之間進行跨進程通訊,從而能夠實現多個應用程序共享同一個Service的功能。

3.實際開發中案例操做

3.1 aidl通訊業務需求

  • aidl多進程通訊應用——服務端:某app;客戶端:app調試工具。注意:aidl多進程通訊是指兩個獨立app之間的通訊……
  • 打開app調試工具,能夠經過綁定服務端某app的service,獲取到公司app的信息,好比渠道,版本號,簽名,打包時間,token等屬性
  • 經過app調試工具,能夠經過aidl接口中的方法設置屬性,設置成功後,查看某app是否設置屬性成功

3.2 操做步驟僞代碼

  • 3.2.1 服務端app

    • 步驟1:新建定義AIDL文件,並聲明該服務須要向客戶端提供的接口
    • 補充,若是aidl中有對象,則須要建立對象,而且實現Parcelable
    • 步驟2:在Service子類中實現AIDL中定義的接口方法,並定義生命週期的方法(onCreat、onBind()、blabla)
    • 步驟3:在AndroidMainfest.xml中註冊服務 & 聲明爲遠程服務
  • 3.2.2 客戶端ide

    • 步驟1:拷貝服務端的AIDL文件到目錄下
    • 步驟2:使用Stub.asInterface接口獲取服務器的Binder,根據須要調用服務提供的接口方法
    • 步驟3:經過Intent指定服務端的服務名稱和所在包,綁定遠程Service

3.3 服務端操做步驟

  • 3.3.1 建立一個aidl文件【注意:在main路徑下建立】工具

    • 能夠看到裏面有一個AppInfo,注意這個類須要本身建立,而且手動導包進來。不然編譯時找不到……
// ICheckAppInfoManager.aidl
package cn.ycbjie.ycaudioplayer;
import cn.ycbjie.ycaudioplayer.AppInfo;
// Declare any non-default types here with import statements

interface ICheckAppInfoManager {

    //獲取app信息,好比token,版本號,簽名,渠道等信息
    List<AppInfo> getAppInfo(String sign);
    
    boolean setToken(String sign,String token);

    boolean setChannel(String sign,String channel);

    boolean setAppAuthorName(String sign,String name);

}
  • 3.3.2 建立一個AppInfo類,實現Parcelable接口

    • 這個類就是須要用的實體類,由於是跨進程,因此實現了Parcelable接口,這個是Android官方提供的,它裏面主要是靠Parcel來傳遞數據,Parcel內部包裝了可序列化的數據,可以在Binder中自由傳輸數據。
    • 注意:若是用到了自定義Parcelable對象,就須要建立一個同名的AIDL文件,包名要和實體類包名一致。我以前這個地方沒加,致使出現錯誤!
    • 如圖所示:
  • image
import android.os.Parcel;
import android.os.Parcelable;

public class AppInfo  implements Parcelable {

    private String key;
    private String value;

    public AppInfo(String key, String value) {
        this.key = key;
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.key);
        dest.writeString(this.value);
    }

    public AppInfo() {
    }

    protected AppInfo(Parcel in) {
        this.key = in.readString();
        this.value = in.readString();
    }

    public static final Creator<AppInfo> CREATOR = new Creator<AppInfo>() {
        @Override
        public AppInfo createFromParcel(Parcel source) {
            return new AppInfo(source);
        }

        @Override
        public AppInfo[] newArray(int size) {
            return new AppInfo[size];
        }
    };

    @Override
    public String toString() {
        return "AppInfo{" +
                "key='" + key + '\'' +
                ", value='" + value + '\'' +
                '}';
    }
}
  • 3.3.3 在Service子類中實現AIDL中定義的接口方法,並定義生命週期的方法(onCreat、onBind()等)

    • 重寫的onBinde()方法中返回Binder對象,這個Binder對象指向IAdvertManager.Stub(),這個Stub類並不是咱們本身建立的,而是AIDL自動生成的。系統會爲每一個AIDL接口在build/source/aidl下生成一個文件夾,它的名稱跟你命名的AIDL文件夾同樣,裏面的類也同樣。
    • 建立binder對象,在這個getAppInfo方法中,能夠設置app基本信息,方便後期多進程通訊測試
/**
 * <pre>
 *     @author yangchong
 *     blog  :
 *     time  : 2018/05/30
 *     desc  : 用於aidl多進程通訊服務service
 *     revise:
 * </pre>
 */
public class AppInfoService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        LogUtils.i("AppInfoService--IBinder:");
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        LogUtils.i("AppInfoService--onCreate:");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtils.i("AppInfoService--onDestroy:");
    }

    /**
     * 1.核心,Stub裏面的方法運行的binder池中。
     * 2.Stub類並不是咱們本身建立的,而是AIDL自動生成的。
     *   系統會爲每一個AIDL接口在build/generated/source/aidl下生成一個文件夾,它的名稱跟你命名的AIDL文件夾同樣
     * 3.Stub類,是一個內部類,他本質上是一個Binder類。當服務端和客戶端位於同一個進程時,方法調用不會走跨進程的transact過程,
     *   當二者處於不一樣晉城市,方法調用走transact過程,這個邏輯由Stub的內部代理類Proxy完成。
     */
    private final IBinder binder = new ICheckAppInfoManager.Stub() {
        @Override
        public List<AppInfo> getAppInfo(String sign) throws RemoteException {
            List<AppInfo> list=new ArrayList<>();
            String aidlCheckAppInfoSign = AppToolUtils.getAidlCheckAppInfoSign();
            LogUtils.e("AppInfoService--AppInfoService",aidlCheckAppInfoSign+"-------------"+sign);
            if(!aidlCheckAppInfoSign.equals(sign)){
                return list;
            }
            list.add(new AppInfo("app版本號(versionName)", BuildConfig.VERSION_NAME));
            list.add(new AppInfo("app版本名稱(versionCode)", BuildConfig.VERSION_CODE+""));
            list.add(new AppInfo("打包時間", BuildConfig.BUILD_TIME));
            list.add(new AppInfo("app包名", getPackageName()));
            list.add(new AppInfo("app做者", SPUtils.getInstance(Constant.SP_NAME).getString("name","楊充")));
            list.add(new AppInfo("app渠道", SPUtils.getInstance(Constant.SP_NAME).getString("channel")));
            list.add(new AppInfo("token", SPUtils.getInstance(Constant.SP_NAME).getString("token")));
            list.add(new AppInfo("App簽名", AppToolUtils.getSingInfo(getApplicationContext(), getPackageName(), AppToolUtils.SHA1)));
            return list;
        }


        @Override
        public boolean setToken(String sign, String token) throws RemoteException {
            if(!AppToolUtils.getAidlCheckAppInfoSign().equals(sign)){
                return false;
            }
            SPUtils.getInstance(Constant.SP_NAME).put("token",token);
            LogUtils.i("AppInfoService--setToken:"+ token);
            return true;
        }

        @Override
        public boolean setChannel(String sign, String channel) throws RemoteException {
            if(!AppToolUtils.getAidlCheckAppInfoSign().equals(sign)){
                return false;
            }
            SPUtils.getInstance(Constant.SP_NAME).put("channel",channel);
            LogUtils.i("AppInfoService--setChannel:"+ channel);
            return true;
        }

        @Override
        public boolean setAppAuthorName(String sign, String name) throws RemoteException {
            if(!AppToolUtils.getAidlCheckAppInfoSign().equals(sign)){
                return false;
            }
            SPUtils.getInstance(Constant.SP_NAME).put("name",name);
            LogUtils.i("AppInfoService--setAppAuthorName:"+ name);
            return true;
        }
    };
}
  • 3.3.4 在AndroidMainfest.xml中註冊服務 & 聲明爲遠程服務

    • 在清單文件註冊便可,須要設置action。這個在客戶端中綁定服務service須要用到!
<service android:name=".service.AppInfoService"
    android:process=":remote"
    android:exported="true">
    <intent-filter>
        <action android:name="cn.ycbjie.ycaudioplayer.service.aidl.AppInfoService"/>
        <category android:name="android.intent.category.DEFAULT"/>
    </intent-filter>
</service>

3.4 客戶端操做步驟

  • 3.4.1 拷貝服務端的AIDL文件到目錄下

    • 注意:複製時不要改動任何東西!
    • 如圖所示:

image

  • 3.4.2 經過Intent指定服務端的服務名稱和所在包,綁定遠程Service

    • 經過Intent指定服務端的服務名稱和所在包,進行Service綁定;
    • 建立ServiceConnection對象
    /**
     * 跨進程綁定服務
     */
    private void attemptToBindService() {
        Intent intent = new Intent();
        //經過Intent指定服務端的服務名稱和所在包,與遠程Service進行綁定
        //參數與服務器端的action要一致,即"服務器包名.aidl接口文件名"
        intent.setAction("cn.ycbjie.ycaudioplayer.service.aidl.AppInfoService");
        //Android5.0後沒法只經過隱式Intent綁定遠程Service
        //須要經過setPackage()方法指定包名
        intent.setPackage(packName);
        //綁定服務,傳入intent和ServiceConnection對象
        bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }
    
    
    /**
     * 建立ServiceConnection的匿名類
     */
    private ServiceConnection connection = new ServiceConnection() {
        //重寫onServiceConnected()方法和onServiceDisconnected()方法
        // 在Activity與Service創建關聯和解除關聯的時候調用
        @Override public void onServiceDisconnected(ComponentName name) {
            Log.e(getLocalClassName(), "沒法綁定aidlServer的AIDLService服務");
            mBound = false;
        }
    
        //在Activity與Service創建關聯時調用
        @Override public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e(getLocalClassName(), "完成綁定aidlServer的AIDLService服務");
            //使用IAppInfoManager.Stub.asInterface()方法獲取服務器端返回的IBinder對象
            //將IBinder對象傳換成了mAIDL_Service接口對象
            messageCenter = ICheckAppInfoManager.Stub.asInterface(service);
            mBound = true;
            if (messageCenter != null) {
                try {
                    //連接成功
                    Toast.makeText(MainActivity.this,"連接成功",Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };
  • 3.4.3 使用Stub.asInterface接口獲取服務器的Binder,根據須要調用服務提供的接口方法

    • 經過步驟3.4.2完成了跨進程綁定服務,接下來經過調用方法獲取到數據。這裏能夠調用getAppInfo方法獲取到服務端[app]的數據
    private void getAppInfo() {
        //若是與服務端的鏈接處於未鏈接狀態,則嘗試鏈接
        if (!mBound) {
            attemptToBindService();
            Toast.makeText(this, "當前與服務端處於未鏈接狀態,正在嘗試重連,請稍後再試",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        if (messageCenter == null) {
            return;
        }
        try {
            List<AppInfo> info = messageCenter.getAppInfo(Utils.getSign(packName));
            if(info==null || (info.size()==0)){
                Toast.makeText(this, "沒法獲取數據,多是簽名錯誤!", Toast.LENGTH_SHORT).show();
            }else {
                mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
                FirstAdapter adapter = new FirstAdapter(info, this);
                mRecyclerView.setAdapter(adapter);
                adapter.setOnItemClickListener(new FirstAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
    
                    }
                });
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

3.5 測試

  • 最後看看經過測試工具[客戶端]跨進程獲取服務端app信息截圖

image

4.可能出現的問題

4.1 客戶端在子線程中發起通訊訪問問題

  • 當客戶端發起遠程請求時,客戶端會掛起,一直等到服務端處理完並返回數據,因此遠程通訊是很耗時的,因此不能在子線程發起訪問。因爲服務端的Binder方法運行在Binder線程池中,因此應採起同步的方式去實現,由於它已經運行在一個線程中呢。

4.2 什麼狀況下會致使遠程調用失敗

  • Binder是會意外死亡的。若是服務端的進程因爲某種緣由異常終止,會致使遠程調用失敗,若是咱們不知道Binder鏈接已經斷裂, 那麼客戶端就會受到影響。不用擔憂,Android貼心的爲咱們提供了連個配對的方法linkToDeath和unlinkToDeath,經過linkToDeath咱們能夠給Binder設置一個死亡代理,當Binder死亡時,咱們就會收到通知。
// 在建立ServiceConnection的匿名類中的onServiceConnected方法中
// 設置死亡代理
messageCenter.asBinder().linkToDeath(deathRecipient, 0);


/**
 * 給binder設置死亡代理
 */
private IBinder.DeathRecipient deathRecipient = new IBinder.DeathRecipient() {

    @Override
    public void binderDied() {
        if(messageCenter == null){
            return;
        }
        messageCenter.asBinder().unlinkToDeath(deathRecipient, 0);
        messageCenter = null;
        //這裏從新綁定服務
        attemptToBindService();
    }
};

4.3 設置aidl的權限,須要經過權限才能調用

<!--給aidl多進程通訊,服務加入權限驗證功能-->
<permission android:name="aidl.AppInfoService"
    android:protectionLevel="normal"/>
    

//在AppInfoService服務中驗證權限
@Nullable
@Override
public IBinder onBind(Intent intent) {
    LogUtils.i("AppInfoService--IBinder:");
    int check = checkCallingOrSelfPermission("aidl.AppInfoService");
    if(check == PackageManager.PERMISSION_DENIED){
        return null;
    }
    return binder;
}

5.部分源碼解析

5.1 服務端aidl編譯生成的java文件

  • 5.1.1 首先找到aidl編譯生成的Java文件

image

  • 5.1.2 分析生成的java文件

    • 這個ICheckAppInfoManager.java就是系統爲咱們生成的相應java文件,簡單說下這個類。它聲明瞭三個方法getAppInfo,setToken和setChannel,分明就是咱們AIDL接口中的三個方法。同時他聲明瞭3個id用來標識這幾個方法,id用於標識在transact過程當中客戶端請求的究竟是哪一個方法。接着就是咱們的Stub,能夠看到它是一個內部類,他本質上是一個Binder類。當服務端和客戶端位於同一個進程時,方法調用不會走跨進程的transact過程,當二者處於不一樣晉城市,方法調用走transact過程,這個邏輯由Stub的內部代理類Proxy完成。
    • 這個Stub對象之因此裏面有咱們AIDL的接口,正是由於官方替咱們作好了,咱們只要在這裏具體實現就行了。

5.2 客戶端綁定服務端service原理

  • 客戶端也很是簡單,首先咱們鏈接到服務端Service,在鏈接成功時,也就是onServiceConnected方法裏,經過asInterface(service)方法能夠將服務端的Binder對象轉換成客戶端所需的AIDL的接口的對象。這種轉換是區分進程的,若是是同一進程,那麼此方法返回的就是Stub自己,不然返回的就是系統Stub.proxy對象。拿到接口對象以後,咱們就可以調用相應方法進行本身的處理

參考文章

關於個人博客
相關文章
相關標籤/搜索