Android多程式之手動編寫Binder類

xxq2dream發表於2018-08-18

Android多程式系列

分析系統生成的Binder類

package com.xxq2dream.aidl;

public interface IBookManager extends android.os.IInterface {
    /**
     * Local-side IPC implementation stub class.
     */
    public static abstract class Stub extends android.os.Binder implements com.xxq2dream.aidl.IBookManager {
        private static final java.lang.String DESCRIPTOR = "com.xxq2dream.aidl.IBookManager";

        /**
         * Construct the stub at attach it to the interface.
         */
        public Stub() {
            this.attachInterface(this, DESCRIPTOR);
        }

        /**
         * 用於將服務端的Binder物件轉換成客戶端所需要的AIDL介面型別的物件
         */
        public static com.xxq2dream.aidl.IBookManager asInterface(android.os.IBinder obj) {
            if ((obj == null)) {
                return null;
            }
            android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
            //這裡通過instanceof方法判斷是否是跨程式,如果客戶端和服務端位於同一程式,則返回的是服務端的Stub物件本身,不會呼叫跨程式的transact方法
            if (((iin != null) && (iin instanceof com.xxq2dream.aidl.IBookManager))) {
                return ((com.xxq2dream.aidl.IBookManager) iin);
            }
            //如果客戶端和服務端不在同一個程式中,那麼返回的是系統封裝好的Stub.Proxy代理物件,客戶端呼叫會走transact方法發起跨程式請求
            return new com.xxq2dream.aidl.IBookManager.Stub.Proxy(obj);
        }

        //返回當前Binder物件
        @Override
        public android.os.IBinder asBinder() {
            return this;
        }

        /**
         * 執行在服務端的Binder執行緒池中
         *
         * @param code 要執行的方法標識
         * @param data 客戶端傳遞過來的引數
         * @param reply 回傳給客戶端的資料
         * @param flags
         * @return true 表示執行成功;false,執行失敗,客戶端的請求失敗
         * @throws RemoteException
         */
        @Override
        public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException {
            switch (code) {
                case INTERFACE_TRANSACTION: {
                    reply.writeString(DESCRIPTOR);
                    return true;
                }
                case TRANSACTION_getBookList: {
                    data.enforceInterface(DESCRIPTOR);
                    java.util.List<com.xxq2dream.aidl.Book> _result = this.getBookList();
                    reply.writeNoException();
                    //將結果寫入reply返回
                    reply.writeTypedList(_result);
                    return true;
                }
                case TRANSACTION_addBook: {
                    data.enforceInterface(DESCRIPTOR);
                    com.xxq2dream.aidl.Book _arg0;
                    if ((0 != data.readInt())) {
                        _arg0 = com.xxq2dream.aidl.Book.CREATOR.createFromParcel(data);
                    } else {
                        _arg0 = null;
                    }
                    this.addBook(_arg0);
                    reply.writeNoException();
                    return true;
                }
            }
            return super.onTransact(code, data, reply, flags);
        }

        private static class Proxy implements com.xxq2dream.aidl.IBookManager {
            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;
            }

            /**
             * 執行在客戶端的Binder執行緒池中
             * 當客戶端和服務端不在同一個程式中時,通過上面的asInterface方法返回的就是這個Proxy物件
             * 呼叫服務端的方法就是呼叫這裡對應的方法,最終走的是transact方法發起遠端過程呼叫
             *
             * @return
             * @throws RemoteException
             */
            @Override
            public java.util.List<com.xxq2dream.aidl.Book> getBookList() throws android.os.RemoteException {
                //用於向服務端傳遞引數
                android.os.Parcel _data = android.os.Parcel.obtain();
                //用於接收服務端傳回來的結果
                android.os.Parcel _reply = android.os.Parcel.obtain();
                java.util.List<com.xxq2dream.aidl.Book> _result;
                try {
                    _data.writeInterfaceToken(DESCRIPTOR);
                    //發起遠端過程呼叫請求,同時當前執行緒掛起,服務端的onTransact方法會被呼叫
                    mRemote.transact(Stub.TRANSACTION_getBookList, _data, _reply, 0);
                    //上述呼叫過程返回後,當前執行緒繼續執行,從reply中取出結果返回
                    _reply.readException();
                    _result = _reply.createTypedArrayList(com.xxq2dream.aidl.Book.CREATOR);
                } finally {
                    _reply.recycle();
                    _data.recycle();
                }
                return _result;
            }

            @Override
            public void addBook(com.xxq2dream.aidl.Book book) 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 ((book != null)) {
                        _data.writeInt(1);
                        book.writeToParcel(_data, 0);
                    } else {
                        _data.writeInt(0);
                    }
                    mRemote.transact(Stub.TRANSACTION_addBook, _data, _reply, 0);
                    _reply.readException();
                } finally {
                    _reply.recycle();
                    _data.recycle();
                }
            }
        }

        //介面的標識
        static final int TRANSACTION_getBookList = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
        static final int TRANSACTION_addBook = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
    }
    
    //提供的介面
    public java.util.List<com.xxq2dream.aidl.Book> getBookList() throws android.os.RemoteException;

    public void addBook(com.xxq2dream.aidl.Book book) throws android.os.RemoteException;

}

複製程式碼

動手編寫Binder類

  • 從上面的分析可以看出Binder類主要可以分為2個部分,一個是Stub類,也就是真正的Binder類;另一個就是AIDL介面
抽取出AIDL介面
public interface IBookManager extends IInterface {

    static final String DESCRIPTOR = "com.xxq2dream.manualbinder.IBookManager";

    static final int TRANSACTION_getBookList = IBinder.FIRST_CALL_TRANSACTION + 0;
    static final int TRANSACTION_addBook = IBinder.FIRST_CALL_TRANSACTION + 1;
    <!--註釋1-->
    <!--static final int TRANSACTION_registerListener= IBinder.FIRST_CALL_TRANSACTION + 2;-->
    <!--static final int TRANSACTION_unRegisterListener= IBinder.FIRST_CALL_TRANSACTION + 3;-->

    public List<Book> getBookList() throws RemoteException;
    public void addBook(Book book) throws RemoteException;
    <!--註釋2-->
    <!--void registerListener(IOnNewBookArrivedListener listener) throws RemoteException;-->
    <!--void unRegisterListener(IOnNewBookArrivedListener listener) throws RemoteException;-->
}
複製程式碼
實現Stub類和Stub類的代理類
  • 這個和上面自動生成的程式碼大部分都是一樣的
public class BookManagerImpl extends Binder implements IBookManager {
    private static final String TAG = "BookManagerImpl";

    public BookManagerImpl() {
        Log.e(TAG, "attachInterface-->"+ System.currentTimeMillis());
        this.attachInterface(this,DESCRIPTOR);
    }

    /**
     * Cast an IBinder object into an com.xxq2dream.IBookManager interface,
     * generating a proxy if needed.
     */
    public static IBookManager asInterface(IBinder obj) {
        if ((obj == null)) {
            return null;
        }
        android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
        if (((iin != null) && (iin instanceof IBookManager))) {
            Log.e(TAG, "asInterface");
            return ((IBookManager) iin);
        }
        Log.e(TAG, "asInterface Proxy-->"+ System.currentTimeMillis());
        return new BookManagerImpl.Proxy(obj);
    }

    /**
     * 執行在服務端的Binder執行緒池中
     *
     * @param code 要執行的方法標識
     * @param data 客戶端傳遞過來的引數
     * @param reply 回傳給客戶端的資料
     * @param flags
     * @return true 表示執行成功;false,執行失敗,客戶端的請求失敗
     * @throws RemoteException
     */
    @Override
    public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
        Log.e(TAG, "onTransact-->"+System.currentTimeMillis());

        switch (code) {
            case INTERFACE_TRANSACTION: {
                Log.e(TAG, "INTERFACE_TRANSACTION-->"+ System.currentTimeMillis());
                reply.writeString(DESCRIPTOR);
                return true;
            }
            case TRANSACTION_getBookList: {
                Log.e(TAG, "TRANSACTION_getBookList-->"+ System.currentTimeMillis());

                data.enforceInterface(DESCRIPTOR);
                List<Book> result = this.getBookList();
                reply.writeNoException();
                reply.writeTypedList(result);
                return true;
            }
            case TRANSACTION_addBook: {
                Log.e(TAG, "TRANSACTION_addBook-->"+ System.currentTimeMillis());

                data.enforceInterface(DESCRIPTOR);
                Book arg0;
                if (0 != data.readInt()) {
                    arg0 = Book.CREATOR.createFromParcel(data);
                }else {
                    arg0 = null;
                }
                this.addBook(arg0);
                reply.writeNoException();
                return true;
            }
            <!--註釋6-->
            <!--case TRANSACTION_registerListener: {-->
            <!--    Log.e(TAG, "TRANSACTION_registerListener-->" +System.currentTimeMillis());-->
            <!--    data.enforceInterface(DESCRIPTOR);-->
            <!--    IOnNewBookArrivedListener arg0;-->
            <!--    arg0 = OnNewBookArrivedListenerImpl.asInterface(data.readStrongBinder());-->
            <!--    this.registerListener(arg0);-->
            <!--    reply.writeNoException();-->
            <!--    return true;-->
            <!--}-->
            <!--case TRANSACTION_unRegisterListener: {-->
            <!--    Log.e(TAG, "TRANSACTION_unRegisterListener-->" +System.currentTimeMillis());-->
            <!--    data.enforceInterface(DESCRIPTOR);-->
            <!--    IOnNewBookArrivedListener arg0;-->
            <!--    arg0 = OnNewBookArrivedListenerImpl.asInterface(data.readStrongBinder());-->
            <!--    this.unRegisterListener(arg0);-->
            <!--    reply.writeNoException();-->
            <!--    return true;-->
            <!--}-->
        }
        return super.onTransact(code, data, reply, flags);
    }

    @Override
    public List<Book> getBookList() throws RemoteException {
        return null;
    }

    @Override
    public void addBook(Book book) throws RemoteException {

    }

    <!--註釋5-->
    <!--@Override-->
    <!--public void registerListener(IOnNewBookArrivedListener listener) {-->

    <!--}-->

    <!--@Override-->
    <!--public void unRegisterListener(IOnNewBookArrivedListener listener) {-->

    <!--}-->

    /**
     * Retrieve the Binder object associated with this interface.
     * You must use this instead of a plain cast, so that proxy objects
     * can return the correct result.
     */
    @Override
    public IBinder asBinder() {
        Log.e(TAG, "asBinder-->"+ System.currentTimeMillis());
        return this;
    }

    private static class Proxy implements IBookManager {

        private IBinder mRemote;

        Proxy(IBinder remote) {
            mRemote = remote;
        }

        public String getInterfaceDescriptor() {
            return DESCRIPTOR;
        }

        /**
         * 執行在客戶端的Binder執行緒池中
         *
         * @return
         * @throws RemoteException
         */
        @Override
        public List<Book> getBookList() throws RemoteException {
            Log.e(TAG, "Proxy-->getBookList-->"+ System.currentTimeMillis());

            //用於向服務端傳遞引數
            Parcel data = Parcel.obtain();
            //用於接收服務端傳回來的結果
            Parcel reply = Parcel.obtain();
            List<Book> result;
            try {
                data.writeInterfaceToken(DESCRIPTOR);
                //發起遠端過程呼叫請求,同時當前執行緒掛起,服務端的onTransact方法會被呼叫
                mRemote.transact(TRANSACTION_getBookList, data, reply, 0);
                //上述呼叫過程返回後,當前執行緒繼續執行,從reply中取出結果返回
                reply.readException();
                result = reply.createTypedArrayList(Book.CREATOR);
            } finally {
                reply.recycle();
                data.recycle();
            }
            return result;
        }

        @Override
        public void addBook(Book book) throws RemoteException {
            Log.e(TAG, "Proxy-->addBook-->"+ System.currentTimeMillis());

            //用於向服務端傳遞引數
            Parcel data = Parcel.obtain();
            //用於接收服務端傳回來的結果
            Parcel reply = Parcel.obtain();
            try {
                data.writeInterfaceToken(DESCRIPTOR);
                if (book != null) {
                    data.writeInt(1);
                    book.writeToParcel(data,0);
                }else {
                    data.writeInt(0);
                }
                mRemote.transact(TRANSACTION_addBook, data, reply, 0);
                reply.readException();
            }finally {
                reply.recycle();
                data.recycle();
            }
        }
        
        <!--註釋3-->
        <!--@Override-->
        <!--public void registerListener(IOnNewBookArrivedListener listener) throws RemoteException{-->
        <!--    Log.e(TAG, "Proxy-->registerListener-->"+ System.currentTimeMillis());-->

        <!--    //用於向服務端傳遞引數-->
        <!--    Parcel data = Parcel.obtain();-->
        <!--    //用於接收服務端傳回來的結果-->
        <!--    Parcel reply = Parcel.obtain();-->
        <!--    try {-->
        <!--        data.writeInterfaceToken(DESCRIPTOR);-->
        <!--        data.writeStrongBinder((listener != null)?(listener.asBinder()) : (null));-->
        <!--        mRemote.transact(TRANSACTION_registerListener, data, reply, 0);-->
        <!--        reply.readException();-->
        <!--    }finally {-->
        <!--        reply.recycle();-->
        <!--        data.recycle();-->
        <!--    }-->

        <!--}-->
        
        <!--註釋4-->
        <!--@Override-->
        <!--public void unRegisterListener(IOnNewBookArrivedListener listener) throws RemoteException{-->
        <!--    Log.e(TAG, "Proxy-->unRegisterListener-->"+ System.currentTimeMillis());-->

        <!--    //用於向服務端傳遞引數-->
        <!--    Parcel data = Parcel.obtain();-->
        <!--    //用於接收服務端傳回來的結果-->
        <!--    Parcel reply = Parcel.obtain();-->
        <!--    try {-->
        <!--        data.writeInterfaceToken(DESCRIPTOR);-->
        <!--        data.writeStrongBinder((listener != null)?(listener.asBinder()) : (null));-->
        <!--        mRemote.transact(TRANSACTION_unRegisterListener, data, reply, 0);-->
        <!--        reply.readException();-->
        <!--    }finally {-->
        <!--        reply.recycle();-->
        <!--        data.recycle();-->
        <!--    }-->
        <!--}-->

        /**
         * Retrieve the Binder object associated with this interface.
         * You must use this instead of a plain cast, so that proxy objects
         * can return the correct result.
         */
        @Override
        public IBinder asBinder() {
            Log.e(TAG, "Proxy-->asBinder-->"+ System.currentTimeMillis());
            return mRemote;
        }
    }
}
複製程式碼
  • 以上就是我們自己動手寫的Binder類,沒有使用系統的方法,也不用編寫AIDL檔案
擴充套件我們的Binder類
  • 比如我們要實現當服務端有新書時就通知客戶端,也就是觀察者模式。我們需要在客戶端繫結服務端後繫結監聽的介面,還要提供解綁的介面,上面的程式碼中標記的註釋1-6就是擴充套件Binder類的步驟
  • 當然,由於AIDL中不支援普通的介面,只支援AIDL介面,我們要增加服務端的AIDL介面服務,像上面的程式碼裡那樣傳遞的介面肯定就是AIDL實現的介面,也就是
  • 所以我們還得增加AIDL介面,同樣的我們可以通過編寫AIDL檔案然後由系統自動生成,也可以手動編寫。這裡我們還是以手動的方式編寫
  • AIDL介面IOnNewBookArrivedListener
public interface IOnNewBookArrivedListener extends IInterface {
    static final String DESCRIPTOR = "com.xxq2dream.aidl.IOnNewBookArrivedListener";

    static final int TRANSACTION_onNewBookArrived = IBinder.FIRST_CALL_TRANSACTION + 0;

    void onNewBookArrived(Book book) throws RemoteException;
}
複製程式碼
  • 對應的Binder類
public class OnNewBookArrivedListenerImpl extends Binder implements IOnNewBookArrivedListener {
    private static final String TAG = "NewBookArrivedListener";

    public OnNewBookArrivedListenerImpl() {
        Log.e(TAG, "attachInterface-->"+ System.currentTimeMillis());
        this.attachInterface(this,DESCRIPTOR);
    }

    public static IOnNewBookArrivedListener asInterface (IBinder obj) {
        if ((obj == null)) {
            return null;
        }
        android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
        if (((iin != null) && (iin instanceof IOnNewBookArrivedListener))) {
            Log.e(TAG, "asInterface");
            return ((IOnNewBookArrivedListener) iin);
        }
        Log.e(TAG, "asInterface Proxy-->"+ System.currentTimeMillis());
        return new OnNewBookArrivedListenerImpl.Proxy(obj);
    }

    /**
     * 執行在服務端的Binder執行緒池中
     *
     * @param code 要執行的方法標識
     * @param data 客戶端傳遞過來的引數
     * @param reply 回傳給客戶端的資料
     * @param flags
     * @return true 表示執行成功;false,執行失敗,客戶端的請求失敗
     * @throws RemoteException
     */
    @Override
    public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
        Log.e(TAG, "onTransact-->"+System.currentTimeMillis());

        switch (code) {
            case INTERFACE_TRANSACTION: {
                Log.e(TAG, "INTERFACE_TRANSACTION-->"+ System.currentTimeMillis());
                reply.writeString(DESCRIPTOR);
                return true;
            }
            case TRANSACTION_onNewBookArrived: {
                Log.e(TAG, "TRANSACTION_onNewBookArrived-->"+ System.currentTimeMillis());

                data.enforceInterface(DESCRIPTOR);
                Book _arg0;
                if ((0 != data.readInt())) {
                    _arg0 = Book.CREATOR.createFromParcel(data);
                } else {
                    _arg0 = null;
                }
                this.onNewBookArrived(_arg0);
                reply.writeNoException();
                return true;
            }
        }
        return super.onTransact(code, data, reply, flags);
    }

    @Override
    public void onNewBookArrived(Book book) {

    }

    /**
     * Retrieve the Binder object associated with this interface.
     * You must use this instead of a plain cast, so that proxy objects
     * can return the correct result.
     */
    @Override
    public IBinder asBinder() {
        return this;
    }

    private static class Proxy implements IOnNewBookArrivedListener {

        private IBinder mRemote;

        Proxy(IBinder remote) {
            mRemote = remote;
        }

        public String getInterfaceDescriptor() {
            return DESCRIPTOR;
        }

        /**
         * Retrieve the Binder object associated with this interface.
         * You must use this instead of a plain cast, so that proxy objects
         * can return the correct result.
         */
        @Override
        public IBinder asBinder() {
            Log.e(TAG, "Proxy-->asBinder-->"+ System.currentTimeMillis());
            return mRemote;
        }

        @Override
        public void onNewBookArrived(Book newBook) throws RemoteException{
            Log.e(TAG, "onNewBookArrived-->" + System.currentTimeMillis());
            android.os.Parcel _data = android.os.Parcel.obtain();
            android.os.Parcel _reply = android.os.Parcel.obtain();
            try {
                _data.writeInterfaceToken(DESCRIPTOR);
                if ((newBook != null)) {
                    _data.writeInt(1);
                    newBook.writeToParcel(_data, 0);
                } else {
                    _data.writeInt(0);
                }
                mRemote.transact(TRANSACTION_onNewBookArrived, _data, _reply, 0);
                _reply.readException();
            } finally {
                _reply.recycle();
                _data.recycle();
            }
        }
    }
}
複製程式碼
Binder傳遞AIDL介面
  • 通過上面的程式碼我們可以看到,和傳遞普通的Parcelable序列化物件不同的是,在Proxy類中要通過writeStrongBinder方法將AIDL介面加入到引數中去
  • 在服務端的onTransact方法中要通過對應的Binder類的asInterface方法獲得傳遞過來的介面引數
IOnNewBookArrivedListener arg0;
arg0 = OnNewBookArrivedListenerImpl.asInterface(data.readStrongBinder());
複製程式碼
結語
  • 通過手動編寫Binder類,可以讓我們更好地理解Binder的工作機制
  • 擴充套件了Binder類以後,下一步我們還需要相應的改造客戶端和服務端,以便增加註冊監聽的功能

                歡迎關注我的微信公眾號,和我一起學習一起成長!
複製程式碼

AntDream

相關文章