How to use AIDL for cross-process communication

The steps for cross-process communication using AIDL (Android Interface Definition Language) are as follows:

  1. Create AIDL file:

    1. Create an AIDL file in your Android project with an extension of .aidleg IMyService.aidl.
    2. Define interfaces and methods in AIDL files that will be used for cross-process communication
      // IMyService.aidl
      interface IMyService {
          void sendData(int data);
          String getData();
      }
      

  2. Implement the AIDL interface:

    Create a Service in the server process and implement the AIDL interface just defined.
    public class MyService extends Service {
        private final IMyService.Stub binder = new IMyService.Stub() {
            @Override
            public void sendData(int data) {
                // 处理客户端发送的数据
            }
    
            @Override
            public String getData() {
                // 返回需要传递给客户端的数据
                return "Hello, client!";
            }
        };
    
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return binder;
        }
    }
    
  3. Connect to server process:
    1. In the client process, use the code generated by AIDL to create a ServiceConnection object, which is used to connect to the Service of the server process and communicate across processes.
      private ServiceConnection serviceConnection = new ServiceConnection() {
          @Override
          public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
              // 连接到服务端进程的Service成功
              // 将IBinder对象转换为AIDL接口对象
              IMyService myService = IMyService.Stub.asInterface(iBinder);
      
              try {
                  // 调用服务端的方法进行跨进程通信
                  myService.sendData(123);
                  String result = myService.getData();
                  // 处理返回的数据
              } catch (RemoteException e) {
                  e.printStackTrace();
              }
          }
      
          @Override
          public void onServiceDisconnected(ComponentName componentName) {
              // 与服务端进程的Service断开连接
          }
      };
      
      // 绑定到服务端进程的Service
      Intent intent = new Intent();
      intent.setComponent(new ComponentName("服务端进程的包名", "服务端进程的Service类名"));
      bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
      

      Through the above steps, you can use AIDL for cross-process communication. It should be noted that you need to set the package name and Service class name of the server process to correct values ​​so as to correctly connect to the Service of the server process. At the same time, AIDL also supports the definition of callback methods in the interface to achieve two-way communication. Detailed usage and examples can be found in the Android development documentation.

Guess you like

Origin blog.csdn.net/lzq520210/article/details/131682571