Android AIDL詳解(代碼用Kotlin完成)

AIDL(Android Interface Define Language)是一種IPC通信方式,也就是我們所說(shuō)的進(jìn)程間通訊的一種方式。進(jìn)程間通訊有很多種方法,比如通過(guò)文件讀取,以及messenger,還有ContentProviderontentProvider和Socket。在這里我就寫(xiě)一些我對(duì)AIDL自己的理解。
首先在我們的編譯器下面新建一個(gè)AIDL文件,系統(tǒng)會(huì)自動(dòng)為我們新建一個(gè)aidl包將我們的文件放進(jìn)去。
// 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<Student> getList();
     void addStudent(in Student student);
}

我們?cè)谛陆ㄒ粋€(gè)Student類(lèi)。

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<Student> CREATOR = new Parcelable.Creator<Student>(){

        @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中能夠傳遞的對(duì)象必須實(shí)現(xiàn)Parcelable接口,所以在這里我們的Student實(shí)現(xiàn)了改接口之后就可以在AIDL

中傳遞了。
在這里我們還要新建一個(gè)Student的aidl文件

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

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

parcelable Student;
在這里如果沒(méi)有這個(gè)文件話,就會(huì)報(bào)錯(cuò)提示找不到類(lèi)。

現(xiàn)在我們的AIDL文件中的東西已經(jīng)準(zhǔn)備好了,現(xiàn)在我們就去實(shí)現(xiàn)AIDL如何進(jìn)行進(jìn)程間通訊。
在這里新建一個(gè)Service類(lèi),把Service類(lèi)當(dāng)成服務(wù)端。把Activity當(dāng)成我們的客戶端,來(lái)實(shí)現(xiàn)進(jìn)程間通訊

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<Student>();
    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<Student> {
            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()
    }
}
在上面我們寫(xiě)了一個(gè)StudentManagerService 類(lèi)繼承自Service類(lèi),并實(shí)現(xiàn)了它的onBind方法,里面還有一個(gè)內(nèi)部類(lèi)是一個(gè)Binder類(lèi),這個(gè)Binder繼承自IStudentManager.Stub并實(shí)現(xiàn)了它的內(nèi)部方法。這里我們使用了CopyOnWriteArrayList,nWriteArrayList,它支持并發(fā)的讀寫(xiě),AIDL方法是在服務(wù)端Binder的線程池中執(zhí)行,當(dāng)多個(gè)客戶端連接的時(shí)候,就會(huì)出現(xiàn)同時(shí)訪問(wèn)的現(xiàn)象,所以我們要處理線程同步,這里使用CopyOnWriteArrayList直接自動(dòng)進(jìn)行線程同步。

在src/main/AndroidManifest.xml中

    <service android:name=".StudentManagerService"
            android:process=":remote"
            ></service>
下面是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中我們綁定了遠(yuǎn)程服務(wù),我們通過(guò)ServiceConnection中的onServiceConnected方法里面的

        var studentManager = IStudentManager.Stub.asInterface(service)

拿到了Binder對(duì)象轉(zhuǎn)換成的AIDL接口,然后我們就可以通過(guò)這個(gè)接口去掉服務(wù)端的方法了,就能看到我們的打印日志了


image.png

這樣我們就實(shí)現(xiàn)了進(jìn)程間的通訊了。
這里我們來(lái)看一下我們創(chuàng)建AIDL文件之后,系統(tǒng)給我們生成的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<com.example.myapplication.Student> 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<com.example.myapplication.Student> _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<com.example.myapplication.Student> getList() throws android.os.RemoteException
      {
        android.os.Parcel _data = android.os.Parcel.obtain();
        android.os.Parcel _reply = android.os.Parcel.obtain();
        java.util.List<com.example.myapplication.Student> _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<com.example.myapplication.Student> getList() throws android.os.RemoteException;
  public void addStudent(com.example.myapplication.Student student) throws android.os.RemoteException;

}

這里生成的DESCRIPTOR是Binder的唯一標(biāo)識(shí)一般用Binder當(dāng)前的雷明表示。
asInterface(android.os.IBinder obj)
用于將服務(wù)端的Binder對(duì)象轉(zhuǎn)化成AIDL接口類(lèi)型對(duì)象,這種轉(zhuǎn)化是區(qū)分進(jìn)程的,在同一進(jìn)程中此方法就返回的是服務(wù)端Stub的本身,否則返回系統(tǒng)封裝的return new com.example.myapplication.adil.IStudentManager.Stub.Proxy(obj);
onTransact
這個(gè)方法個(gè)運(yùn)行在服務(wù)端的線程池中,當(dāng)客戶端發(fā)起跨進(jìn)程請(qǐng)求時(shí)會(huì)通過(guò)系統(tǒng)底層封裝后交由此方法來(lái)處理。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容