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

AIDL(Android Interface Define Language)是一種IPC通信方式震糖,也就是我們所說的進(jìn)程間通訊的一種方式魁瞪。進(jìn)程間通訊有很多種方法,比如通過文件讀取喷众,以及messenger奋救,還有ContentProviderontentProvider和Socket。在這里我就寫一些我對AIDL自己的理解结笨。
首先在我們的編譯器下面新建一個AIDL文件,系統(tǒng)會自動為我們新建一個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);
}

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

中傳遞了勉痴。
在這里我們還要新建一個Student的aidl文件

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

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

parcelable Student;
在這里如果沒有這個文件話赫模,就會報(bào)錯提示找不到類。

現(xiàn)在我們的AIDL文件中的東西已經(jīng)準(zhǔn)備好了蒸矛,現(xiàn)在我們就去實(shí)現(xiàn)AIDL如何進(jìn)行進(jìn)程間通訊瀑罗。
在這里新建一個Service類,把Service類當(dāng)成服務(wù)端雏掠。把Activity當(dāng)成我們的客戶端斩祭,來實(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()
    }
}
在上面我們寫了一個StudentManagerService 類繼承自Service類,并實(shí)現(xiàn)了它的onBind方法乡话,里面還有一個內(nèi)部類是一個Binder類摧玫,這個Binder繼承自IStudentManager.Stub并實(shí)現(xiàn)了它的內(nèi)部方法。這里我們使用了CopyOnWriteArrayList,nWriteArrayList,它支持并發(fā)的讀寫绑青,AIDL方法是在服務(wù)端Binder的線程池中執(zhí)行诬像,當(dāng)多個客戶端連接的時候,就會出現(xiàn)同時訪問的現(xiàn)象闸婴,所以我們要處理線程同步坏挠,這里使用CopyOnWriteArrayList直接自動進(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ù)邪乍,我們通過ServiceConnection中的onServiceConnected方法里面的

        var studentManager = IStudentManager.Stub.asInterface(service)

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


image.png

這樣我們就實(shí)現(xiàn)了進(jìn)程間的通訊了溺欧。
這里我們來看一下我們創(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)識一般用Binder當(dāng)前的雷明表示。
asInterface(android.os.IBinder obj)
用于將服務(wù)端的Binder對象轉(zhuǎn)化成AIDL接口類型對象姐刁,這種轉(zhuǎn)化是區(qū)分進(jìn)程的芥牌,在同一進(jìn)程中此方法就返回的是服務(wù)端Stub的本身,否則返回系統(tǒng)封裝的return new com.example.myapplication.adil.IStudentManager.Stub.Proxy(obj);
onTransact
這個方法個運(yùn)行在服務(wù)端的線程池中聂使,當(dāng)客戶端發(fā)起跨進(jìn)程請求時會通過系統(tǒng)底層封裝后交由此方法來處理壁拉。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末谬俄,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子弃理,更是在濱河造成了極大的恐慌溃论,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,270評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件痘昌,死亡現(xiàn)場離奇詭異钥勋,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)辆苔,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評論 3 395
  • 文/潘曉璐 我一進(jìn)店門算灸,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人驻啤,你說我怎么就攤上這事菲驴。” “怎么了骑冗?”我有些...
    開封第一講書人閱讀 165,630評論 0 356
  • 文/不壞的土叔 我叫張陵赊瞬,是天一觀的道長。 經(jīng)常有香客問我贼涩,道長巧涧,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,906評論 1 295
  • 正文 為了忘掉前任磁携,我火速辦了婚禮褒侧,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘谊迄。我一直安慰自己闷供,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,928評論 6 392
  • 文/花漫 我一把揭開白布统诺。 她就那樣靜靜地躺著歪脏,像睡著了一般。 火紅的嫁衣襯著肌膚如雪粮呢。 梳的紋絲不亂的頭發(fā)上婿失,一...
    開封第一講書人閱讀 51,718評論 1 305
  • 那天,我揣著相機(jī)與錄音啄寡,去河邊找鬼豪硅。 笑死,一個胖子當(dāng)著我的面吹牛挺物,可吹牛的內(nèi)容都是我干的懒浮。 我是一名探鬼主播,決...
    沈念sama閱讀 40,442評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼砚著!你這毒婦竟也來了次伶?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,345評論 0 276
  • 序言:老撾萬榮一對情侶失蹤稽穆,失蹤者是張志新(化名)和其女友劉穎冠王,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體舌镶,經(jīng)...
    沈念sama閱讀 45,802評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡柱彻,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,984評論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了餐胀。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片绒疗。...
    茶點(diǎn)故事閱讀 40,117評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖骂澄,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情惕虑,我是刑警寧澤坟冲,帶...
    沈念sama閱讀 35,810評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站溃蔫,受9級特大地震影響健提,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜伟叛,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,462評論 3 331
  • 文/蒙蒙 一私痹、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧统刮,春花似錦紊遵、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,011評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至鞭衩,卻和暖如春学搜,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背论衍。 一陣腳步聲響...
    開封第一講書人閱讀 33,139評論 1 272
  • 我被黑心中介騙來泰國打工瑞佩, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人坯台。 一個月前我還...
    沈念sama閱讀 48,377評論 3 373
  • 正文 我出身青樓炬丸,卻偏偏與公主長得像,于是被迫代替她去往敵國和親捂人。 傳聞我的和親對象是個殘疾皇子御雕,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,060評論 2 355