1. 程式人生 > >《Android 開發藝術探索》讀書筆記六 IPC機制之Binder

《Android 開發藝術探索》讀書筆記六 IPC機制之Binder

一、Binder簡介

Binder是Android中的一個類,它實現於IBinder介面:
(1)從IPC角度來說,Binder是一種跨程序通訊的方式;
(2)從Android Framework角度來講,Binder是ServiceManager連線各種Manager(ActicityManager、WindowManager等等)和相應ManagerService的橋樑;
(3)從Android應用層來說,Binder是客戶端與服務端通訊的媒介,通過bindService,服務端會返回一個包含了服務端業務呼叫的Binder物件,通過這個Binder物件,客戶端就可以獲取服務端提供的服務或者資料。這裡的服務包括普通服務及基於AIDL的服務。

在Android開發中,Binder主要應用在Service中,包括AIDL和Messenger,其中普通Service中的Binder不涉及程序間通訊,而Messenger的底層其實是AIDL。

二、Binder的工作機制

以下通過AIDL的方式來分析Binder的工作機制:
首先建立三個檔案Book.java、Book.aidl、IBookManager.aidl

Book.java:

public class Book implements Parcelable{

    public int bookId;
    public int bookName;

    public
Book(int bookId, int bookName) { this.bookId = bookId; this.bookName = bookName; } protected Book(Parcel in) { bookId = in.readInt(); bookName = in.readInt(); } public static final Creator<Book> CREATOR = new Creator<Book>() { @Override
public Book createFromParcel(Parcel in) { return new Book(in); } @Override public Book[] newArray(int size) { return new Book[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(bookId); dest.writeInt(bookName); } }

Book.aidl:

package com.example.ipcdemo1binder.aidl;

parcelable Book;

IBookManager.aidl:

package com.example.ipcdemo1binder.aidl;

import com.example.ipcdemo1binder.aidl.Book;
interface IBookManager {

    List<Book> getBookList();
    void addBook(in Book book);
} 

在上面三個檔案中,Book.java表示一個圖書資訊的類,它實現了Parceleable介面,Book.aidl是Book類在AIDL中的宣告,IBookManager.aidl裡面有兩個方法:getBookList和addBook。

在gen目錄下,系統自動為我們生成了IBookManager.java類,程式碼如下:

/*
 * This file is auto-generated.  DO NOT MODIFY.
 * Original file: C:\\THHWork\\Developer\\EclipseWorkspace\\Temp1\\IPCDemo1Binder\\src\\com\\example\\ipcdemo1binder\\aidl\\IBookManager.aidl
 */
package com.example.ipcdemo1binder.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.example.ipcdemo1binder.aidl.IBookManager {
        private static final java.lang.String DESCRIPTOR = "com.example.ipcdemo1binder.aidl.IBookManager";

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

        /**
         * Cast an IBinder object into an
         * com.example.ipcdemo1binder.aidl.IBookManager interface, generating a
         * proxy if needed.
         */
        public static com.example.ipcdemo1binder.aidl.IBookManager asInterface(
                android.os.IBinder obj) {
            if ((obj == null)) {
                return null;
            }
            android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
            if (((iin != null) && (iin instanceof com.example.ipcdemo1binder.aidl.IBookManager))) {
                return ((com.example.ipcdemo1binder.aidl.IBookManager) iin);
            }
            return new com.example.ipcdemo1binder.aidl.IBookManager.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 {
            switch (code) {
            case INTERFACE_TRANSACTION: {
                reply.writeString(DESCRIPTOR);
                return true;
            }
            case TRANSACTION_getBookList: {
                data.enforceInterface(DESCRIPTOR);
                java.util.List<com.example.ipcdemo1binder.aidl.Book> _result = this
                        .getBookList();
                reply.writeNoException();
                reply.writeTypedList(_result);
                return true;
            }
            case TRANSACTION_addBook: {
                data.enforceInterface(DESCRIPTOR);
                com.example.ipcdemo1binder.aidl.Book _arg0;
                if ((0 != data.readInt())) {
                    _arg0 = com.example.ipcdemo1binder.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.example.ipcdemo1binder.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;
            }

            @Override
            public java.util.List<com.example.ipcdemo1binder.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.example.ipcdemo1binder.aidl.Book> _result;
                try {
                    _data.writeInterfaceToken(DESCRIPTOR);
                    mRemote.transact(Stub.TRANSACTION_getBookList, _data,
                            _reply, 0);
                    _reply.readException();
                    _result = _reply
                            .createTypedArrayList(com.example.ipcdemo1binder.aidl.Book.CREATOR);
                } finally {
                    _reply.recycle();
                    _data.recycle();
                }
                return _result;
            }

            @Override
            public void addBook(com.example.ipcdemo1binder.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.example.ipcdemo1binder.aidl.Book> getBookList()
            throws android.os.RemoteException;

    public void addBook(com.example.ipcdemo1binder.aidl.Book book)
            throws android.os.RemoteException;
}

IBookManager介面繼承於IInterface介面,宣告兩個方法getBookList和addBook。接著,它聲明瞭一個內部類Stub,這個Stub就是一個Binder類,當客戶端與服務端在同一個程序時,方法呼叫不會走跨程序transact過程,而當兩者位於同一程序時,方法呼叫需要走transact過程,這個邏輯由Stub的內部代理類Proxy完成。

DESCRIPTOR
Binder的唯一標識,一般用當前Binder的類名錶示。

asInterface
用於將服務端的Binder物件轉換成客戶端所需的AIDL介面型別物件。這種轉換是區分程序的,如果是同一程序,那麼返回的就是伺服器的Stub物件本身,如果不是同一程序,返回的是系統封裝後的Stub.proxy物件。

asBinder
返回Binder物件

onTransact
如果是跨程序請求時,會呼叫此方法。引數code可以確定客戶端請求的目標方法是什麼,接著從data中取出目標方法所需的引數,然後執行目標方法。當執行完畢後,就向reply中寫入返回值。需要注意的是:如果此方法返回false,那麼客戶端請求會失敗。可利用此特性做許可權驗證,我們也不希望隨便一個程序都能遠端呼叫我們的服務。

Proxy#getBookList
這個方法執行在客戶端,當客戶端呼叫此方法時,它的內部實現是這樣的,首先建立該方法所需要的輸入型Parcel物件_data、輸出型Parcel物件_reply和返回值物件List;然後把該方法的引數資訊寫入_data(如果有引數的話),接著通過RPC(遠端過程呼叫)請求,同時當前執行緒掛起,然後服務端的onTransact方法會被呼叫,直到RPC過程返回後,當前執行緒繼續執行,並從_reply中取出RPC過程的返回結果,最後返回_reply中的資料。

Proxy#addBook
此方法的執行過程與getBookList相同。

注意:當客戶端發起遠端請求時,由於當前執行緒會被掛起直到服務端程序返回資料,所以如果一個遠端方法是耗時的,那麼不能在UI執行緒中發起此遠端請求;其次,由於服務端的Binder方法執行在Binder執行緒池中,所以Binder方法不管是否耗時都應該採用同步的方式去實現,因為它已經執行在一個執行緒中了。

我們也可以自定義一個Binder類,與系統自動生成的類大致一樣,只是在結構上有些調整。

Binder中有兩個比較重要的方法linkToDeath和unlinkToDeath。

private IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
        @Override
        public void binderDied() {
            if (bookManager == null)
                return;
            bookManager.asBinder().unlinkToDeath(mDeathRecipient, 0);
            bookManager = null;
            //重新繫結Service
            bindService();
        }
    };
public void onServiceConnected(ComponentName name, IBinder service) {
                bookManager = BookManagerImpl.asInterface(service);
                try {
                    service.linkToDeath(mDeathRecipient, 0);
                    List<Book> bookList = bookManager.getBookList();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }

如果伺服器程序由於某種原因異常終止,這個時候我們到服務端Binder的連線斷裂,會導致我們的遠端呼叫失敗。更為重要的是,我們並不知道Binder的連線斷裂,那麼客戶端的功能就會受到影響。我們可以通過linkToDeath給Binder設定一個死亡代理,當Binder死亡時,我們就會收到通過,從而重新發起連線請求。