Android AIDL详解(代码用Kotlin完成)

AIDL(Android Interface Define Language)是一种IPC通信方式,也就是我们所说的进程间通讯的一种方式。进程间通讯有很多种方法,比如通过文件读取,以及messenger,还有ContentProviderontentProvider和Socket。在这里我就写一些我对AIDL自己的理解。
首先在我们的编译器下面新建一个AIDL文件,系统会自动为我们新建一个aidl包将我们的文件放进去。
// IStudentManager.aidl
package com.example.myapplication.adil;

// Declare any non-default types here with import statements
import com.example.myapplication.adil.Student;
import com.example.myapplication.adil.INewStudentListener;
interface IStudentManager {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
            double aDouble, String aString);

     List getList();
     void addStudent(in Student student);
}

我们在新建一个Student类。

package com.example.myapplication;

import android.os.Parcel;
import android.os.Parcelable;

public class Student implements Parcelable {


    public int stdId;
    public String stdName;

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

    @Override
    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(stdId);
        out.writeString(stdName);
    }

    public static  final Parcelable.Creator CREATOR = new Parcelable.Creator(){

        @Override
        public Student createFromParcel(Parcel source) {
            return new Student(source);
        }

        @Override
        public Student[] newArray(int size) {
            return new Student[size];
        }
    };
    public  Student(int studentId,String bookName){
        this.stdId = studentId;
        this.stdName = bookName;
    }
    private Student(Parcel in){
        stdId = in.readInt();
        stdName = in.readString();
    }
}
由于在AIDL中能够传递的对象必须实现Parcelable接口,所以在这里我们的Student实现了改接口之后就可以在AIDL

中传递了。
在这里我们还要新建一个Student的aidl文件

// Student.aidl
package com.example.myapplication;

// Declare any non-default types here with import statements

parcelable Student;
在这里如果没有这个文件话,就会报错提示找不到类。

现在我们的AIDL文件中的东西已经准备好了,现在我们就去实现AIDL如何进行进程间通讯。
在这里新建一个Service类,把Service类当成服务端。把Activity当成我们的客户端,来实现进程间通讯

package com.example.myapplication

import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.util.Log
import com.example.myapplication.adil.IStudentManager

import java.util.concurrent.CopyOnWriteArrayList


class StudentManagerService :Service() {
    companion object{
        val TAG:String = "StudentManagerService "
    }

    private var mStudentList = CopyOnWriteArrayList();
    internal inner class MyBinder :IStudentManager.Stub(){


        override fun basicTypes(
            anInt: Int,
            aLong: Long,
            aBoolean: Boolean,
            aFloat: Float,
            aDouble: Double,
            aString: String?
        ) {

        }
      
        override fun getList(): MutableList {
            return mStudentList
        }

        override fun addStudent(student: Student?) {
            mStudentList.add(student)
        }

    }

    override fun onCreate() {
        super.onCreate()
        mStudentList.add(Student(1,"王子"))
        mStudentList.add(Student(2,"栗子"))
 
    }

    override fun onBind(intent: Intent?): IBinder? {
        return MyBinder()
    }
}
在上面我们写了一个StudentManagerService 类继承自Service类,并实现了它的onBind方法,里面还有一个内部类是一个Binder类,这个Binder继承自IStudentManager.Stub并实现了它的内部方法。这里我们使用了CopyOnWriteArrayList,nWriteArrayList,它支持并发的读写,AIDL方法是在服务端Binder的线程池中执行,当多个客户端连接的时候,就会出现同时访问的现象,所以我们要处理线程同步,这里使用CopyOnWriteArrayList直接自动进行线程同步。

在src/main/AndroidManifest.xml中

    
下面是Activity的代码

class MainActivity : AppCompatActivity() {

    private  var IRemoteStudentManager:IStudentManager? = null
    private lateinit var myListener:MyListener
    private lateinit var myConnection: MyConnection
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        myListener = MyListener()
        myConnection = MyConnection()
        var intent = Intent(this@MainActivity,StudentManagerService::class.java)
        bindService(intent,myConnection, Context.BIND_AUTO_CREATE)
    }
    internal inner class MyConnection: ServiceConnection{
        override fun onServiceDisconnected(name: ComponentName?) {
     
        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
           var studentManager = IStudentManager.Stub.asInterface(service)

            var list = studentManager.list
            Log.e("MainActivity", "list"+list.javaClass.canonicalName)
            Log.e("MainActivity", "list"+list.toString())
 
        }

    }

  

    override fun onDestroy() {
        super.onDestroy()

        unbindService(myConnection)
    }

}

在Activity中我们绑定了远程服务,我们通过ServiceConnection中的onServiceConnected方法里面的

        var studentManager = IStudentManager.Stub.asInterface(service)

拿到了Binder对象转换成的AIDL接口,然后我们就可以通过这个接口去掉服务端的方法了,就能看到我们的打印日志了


image.png

这样我们就实现了进程间的通讯了。
这里我们来看一下我们创建AIDL文件之后,系统给我们生成的java文件

/*
 * This file is auto-generated.  DO NOT MODIFY.
 */
package com.example.myapplication.adil;
public interface IStudentManager extends android.os.IInterface
{
  /** Default implementation for IStudentManager. */
  public static class Default implements com.example.myapplication.adil.IStudentManager
  {
    /**
         * Demonstrates some basic types that you can use as parameters
         * and return values in AIDL.
         */
    @Override public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, java.lang.String aString) throws android.os.RemoteException
    {
    }
    @Override public java.util.List getList() throws android.os.RemoteException
    {
      return null;
    }
    @Override public void addStudent(com.example.myapplication.Student student) throws android.os.RemoteException
    {
    }
    @Override
    public android.os.IBinder asBinder() {
      return null;
    }
  }
  /** Local-side IPC implementation stub class. */
  public static abstract class Stub extends android.os.Binder implements com.example.myapplication.adil.IStudentManager
  {
    private static final java.lang.String DESCRIPTOR = "com.example.myapplication.adil.IStudentManager";
    /** Construct the stub at attach it to the interface. */
    public Stub()
    {
      this.attachInterface(this, DESCRIPTOR);
    }
    /**
     * Cast an IBinder object into an com.example.myapplication.adil.IStudentManager interface,
     * generating a proxy if needed.
     */
    public static com.example.myapplication.adil.IStudentManager asInterface(android.os.IBinder obj)
    {
      if ((obj==null)) {
        return null;
      }
      android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
      if (((iin!=null)&&(iin instanceof com.example.myapplication.adil.IStudentManager))) {
        return ((com.example.myapplication.adil.IStudentManager)iin);
      }
      return new com.example.myapplication.adil.IStudentManager.Stub.Proxy(obj);
    }
    @Override public android.os.IBinder asBinder()
    {
      return this;
    }
    @Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException
    {
      java.lang.String descriptor = DESCRIPTOR;
      switch (code)
      {
        case INTERFACE_TRANSACTION:
        {
          reply.writeString(descriptor);
          return true;
        }
        case TRANSACTION_basicTypes:
        {
          data.enforceInterface(descriptor);
          int _arg0;
          _arg0 = data.readInt();
          long _arg1;
          _arg1 = data.readLong();
          boolean _arg2;
          _arg2 = (0!=data.readInt());
          float _arg3;
          _arg3 = data.readFloat();
          double _arg4;
          _arg4 = data.readDouble();
          java.lang.String _arg5;
          _arg5 = data.readString();
          this.basicTypes(_arg0, _arg1, _arg2, _arg3, _arg4, _arg5);
          reply.writeNoException();
          return true;
        }
        case TRANSACTION_getList:
        {
          data.enforceInterface(descriptor);
          java.util.List _result = this.getList();
          reply.writeNoException();
          reply.writeTypedList(_result);
          return true;
        }
        case TRANSACTION_addStudent:
        {
          data.enforceInterface(descriptor);
          com.example.myapplication.Student _arg0;
          if ((0!=data.readInt())) {
            _arg0 = com.example.myapplication.Student.CREATOR.createFromParcel(data);
          }
          else {
            _arg0 = null;
          }
          this.addStudent(_arg0);
          reply.writeNoException();
          return true;
        }
       
        default:
        {
          return super.onTransact(code, data, reply, flags);
        }
      }
    }
    private static class Proxy implements com.example.myapplication.adil.IStudentManager
    {
      private android.os.IBinder mRemote;
      Proxy(android.os.IBinder remote)
      {
        mRemote = remote;
      }
      @Override public android.os.IBinder asBinder()
      {
        return mRemote;
      }
      public java.lang.String getInterfaceDescriptor()
      {
        return DESCRIPTOR;
      }
      /**
           * Demonstrates some basic types that you can use as parameters
           * and return values in AIDL.
           */
      @Override public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, java.lang.String aString) throws android.os.RemoteException
      {
        android.os.Parcel _data = android.os.Parcel.obtain();
        android.os.Parcel _reply = android.os.Parcel.obtain();
        try {
          _data.writeInterfaceToken(DESCRIPTOR);
          _data.writeInt(anInt);
          _data.writeLong(aLong);
          _data.writeInt(((aBoolean)?(1):(0)));
          _data.writeFloat(aFloat);
          _data.writeDouble(aDouble);
          _data.writeString(aString);
          boolean _status = mRemote.transact(Stub.TRANSACTION_basicTypes, _data, _reply, 0);
          if (!_status && getDefaultImpl() != null) {
            getDefaultImpl().basicTypes(anInt, aLong, aBoolean, aFloat, aDouble, aString);
            return;
          }
          _reply.readException();
        }
        finally {
          _reply.recycle();
          _data.recycle();
        }
      }
      @Override public java.util.List getList() throws android.os.RemoteException
      {
        android.os.Parcel _data = android.os.Parcel.obtain();
        android.os.Parcel _reply = android.os.Parcel.obtain();
        java.util.List _result;
        try {
          _data.writeInterfaceToken(DESCRIPTOR);
          boolean _status = mRemote.transact(Stub.TRANSACTION_getList, _data, _reply, 0);
          if (!_status && getDefaultImpl() != null) {
            return getDefaultImpl().getList();
          }
          _reply.readException();
          _result = _reply.createTypedArrayList(com.example.myapplication.Student.CREATOR);
        }
        finally {
          _reply.recycle();
          _data.recycle();
        }
        return _result;
      }
      @Override public void addStudent(com.example.myapplication.Student student) throws android.os.RemoteException
      {
        android.os.Parcel _data = android.os.Parcel.obtain();
        android.os.Parcel _reply = android.os.Parcel.obtain();
        try {
          _data.writeInterfaceToken(DESCRIPTOR);
          if ((student!=null)) {
            _data.writeInt(1);
            student.writeToParcel(_data, 0);
          }
          else {
            _data.writeInt(0);
          }
          boolean _status = mRemote.transact(Stub.TRANSACTION_addStudent, _data, _reply, 0);
          if (!_status && getDefaultImpl() != null) {
            getDefaultImpl().addStudent(student);
            return;
          }
          _reply.readException();
        }
        finally {
          _reply.recycle();
          _data.recycle();
        }
      }
      
      public static com.example.myapplication.adil.IStudentManager sDefaultImpl;
    }
    static final int TRANSACTION_basicTypes = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
    static final int TRANSACTION_getList = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
    static final int TRANSACTION_addStudent = (android.os.IBinder.FIRST_CALL_TRANSACTION + 2);
    public static boolean setDefaultImpl(com.example.myapplication.adil.IStudentManager impl) {
      if (Stub.Proxy.sDefaultImpl == null && impl != null) {
        Stub.Proxy.sDefaultImpl = impl;
        return true;
      }
      return false;
    }
    public static com.example.myapplication.adil.IStudentManager getDefaultImpl() {
      return Stub.Proxy.sDefaultImpl;
    }
  }
  /**
       * Demonstrates some basic types that you can use as parameters
       * and return values in AIDL.
       */
  public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, java.lang.String aString) throws android.os.RemoteException;
  public java.util.List getList() throws android.os.RemoteException;
  public void addStudent(com.example.myapplication.Student student) throws android.os.RemoteException;

}

这里生成的DESCRIPTOR是Binder的唯一标识一般用Binder当前的雷明表示。
asInterface(android.os.IBinder obj)
用于将服务端的Binder对象转化成AIDL接口类型对象,这种转化是区分进程的,在同一进程中此方法就返回的是服务端Stub的本身,否则返回系统封装的return new com.example.myapplication.adil.IStudentManager.Stub.Proxy(obj);
onTransact
这个方法个运行在服务端的线程池中,当客户端发起跨进程请求时会通过系统底层封装后交由此方法来处理。

你可能感兴趣的:(Android AIDL详解(代码用Kotlin完成))