Android AIDL 一探究竟

AIDL ---(Android Interface Definition Language)Android接口定義語言android

  簡述:多線程

一、何時使用?ide

通訊方式 使用場景
AIDL IPC 、多個應用程序、多線程
Binder IPC 、多個應用程序
Messenger IPC
注:  IPC --- (Inter-Process communication)進程間通訊/跨進程通訊

 

 

 

     

 

二、如何實現 AIDL 通訊?spa

   下面是項目目錄結構圖:客戶端與服務端代碼要保證 aidl 文件夾下內容的一致線程

    步驟①:建立一個AIDL文件. (在服務端)3d

 1 // IMyAidlInterface.aidl
 2 package com.anglus.aidl;
 3 
 4 // Declare any non-default types here with import statements
 5 
 6 interface IMyAidlInterface {
 7     /**
 8      * Demonstrates some basic types that you can use as parameters
 9      * and return values in AIDL.
10      */
11 //    計算兩個數的和
12     int add(int num1, int num2);
13 }

    步驟②:實現自定義的AIDL 接口文件(在服務端)code

  public class IRemoteService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return mIBinder;
    }

    private IBinder mIBinder = new IMyAidlInterface.Stub() {
        @Override
        public int add(int num1, int num2) throws RemoteException {
            Log.i("IRemoteService", "收到遠程的請求,傳入的參數是:" + num1 + "和" + num2);
            return num1 + num2;
        }
    };
}

       必定不要忘了在 AndroidManifest.xml 文件中註冊服務:xml

  <service
            android:name=".IRemoteService"
            android:enabled="true"
            android:exported="true"/>

     步驟③: 綁定服務,獲得遠程服務對象,便可在客戶端進行使用。對象

 1   private void bindService() {
 2         // 綁定到服務
 3         Intent intent = new Intent();
 4         intent.setComponent(new ComponentName("com.anglus.aidl",
 5                 "com.anglus.aidl.IRemoteService"));
 6         bindService(intent, conn, Context.BIND_AUTO_CREATE);
 7     }
 8 
 9     private ServiceConnection conn = new ServiceConnection() {
10         @Override
11         public void onServiceConnected(ComponentName name, IBinder service) {
12             // 拿到遠程服務
13             iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
14         }
15 
16         @Override
17         public void onServiceDisconnected(ComponentName name) {
18             // 回收資源
19             iMyAidlInterface = null;
20         }
21     };

       注意:在 new ComponetName() 中,第一個參數是:服務端的 項目包名;第二個參數是:要綁定的服務 包名 + 類名blog

相關文章
相關標籤/搜索