Android AIDL 一探究竟

AIDL ---(Android Interface Definition Language)Android接口定义语言

  简述:

1、什么时候使用?

通信方式 使用场景
AIDL IPC 、多个应用程序、多线程
Binder IPC 、多个应用程序
Messenger IPC
注:  IPC --- (Inter-Process communication)进程间通信/跨进程通信

 

 

 

     

 

2、如何实现 AIDL 通信?

   下面是项目目录结构图:客户端与服务端代码要保证 aidl 文件夹下内容的一致

    步骤①:创建一个AIDL文件. (在服务端)

 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 接口文件(在服务端)

  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 文件中注册服务:

  <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() 中,第一个参数是:服务端的 项目包名;第二个参数是:要绑定的服务 包名 + 类名

     

 

原文地址:https://www.cnblogs.com/jesonjason/p/5958407.html