Android Framework層Binder機制

Framework層Binder相關(guān)接口:


IInterface接口:

public interface IInterface
{
    /**
     * 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.
     */
    public IBinder asBinder();
}

IBinder接口:

public interface IBinder {
  
    public String getInterfaceDescriptor() throws RemoteException;

    public boolean pingBinder();

    public boolean isBinderAlive();
    
    public IInterface queryLocalInterface(String descriptor);

    public void shellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
            String[] args, ShellCallback shellCallback, ResultReceiver resultReceiver) throws RemoteException;

    public interface DeathRecipient {
        public void binderDied();
    }

    public void linkToDeath(DeathRecipient recipient, int flags)
            throws RemoteException;

    public boolean unlinkToDeath(DeathRecipient recipient, int flags);
}

AIDL簡易示例:


aidl-example-structure.png

IMainInterface.aidl代碼:

package com.afollestad.aidlexample;
import com.afollestad.aidlexample.MainObject;

interface IMainService {
    MainObject[] listFiles(String path);

    void exit();
}

MainObject.aidl代碼:

package com.afollestad.aidlexample;
parcelable MainObject;

MainObject.java代碼:

public class MainObject implements Parcelable {

    private String mPath;

    public MainObject(Parcel source) {
        mPath = source.readString();
    }

    public MainObject(String path) {
        mPath = path;
    }

    public String getPath() {
        return mPath;
    }

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(mPath);
    }

    public static final Parcelable.Creator<MainObject> CREATOR = new Parcelable.Creator<MainObject>() {
        @Override
        public MainObject[] newArray(int size) {
            return new MainObject[size];
        }

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

MainService.java代碼:

public class MainService extends Service {

   // 省略...

    private final IMainService.Stub mBinder = new IMainService.Stub() {
        @Override
        public MainObject[] listFiles(String path) throws RemoteException {
            log("Received list command for: " + path);
            List<MainObject> toSend = new ArrayList<>();
            // Generates a list of 1000 objects that aren't sent back to the binding Activity
            for (int i = 0; i < 1000; i++) {
                toSend.add(new MainObject("/example/item" + (i + 1)));
            }
            return toSend.toArray(new MainObject[toSend.size()]);
        }

        @Override
        public void exit() throws RemoteException {
            log("Received exit command.");
            stopSelf();
        }
    };
}

編譯之后叹哭,產(chǎn)生的aidl接口文件路徑:


IMainService-build-path.png

其代碼結(jié)構(gòu):


AIDL-build.png

IMainInterface.java詳細代碼:

/*
 * This file is auto-generated.  DO NOT MODIFY.
 * Original file: /home/bianjp/repos/android/hotfix/aidl-example/receiver/src/main/aidl/com/afollestad/aidlexample/IMainService.aidl
 */
package com.afollestad.aidlexample;

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

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

        /**
         * Cast an IBinder object into an com.afollestad.aidlexample.IMainService interface,
         * generating a proxy if needed.
         */
        public static com.afollestad.aidlexample.IMainService asInterface(android.os.IBinder obj) {
            if ((obj == null)) {
                return null;
            }
            android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
            if (((iin != null) && (iin instanceof com.afollestad.aidlexample.IMainService))) {
                return ((com.afollestad.aidlexample.IMainService) iin);
            }
            return new com.afollestad.aidlexample.IMainService.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_listFiles: {
                    data.enforceInterface(DESCRIPTOR);
                    java.lang.String _arg0;
                    _arg0 = data.readString();
                    com.afollestad.aidlexample.MainObject[] _result = this.listFiles(_arg0);
                    reply.writeNoException();
                    reply.writeTypedArray(_result, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
                    return true;
                }
                case TRANSACTION_exit: {
                    data.enforceInterface(DESCRIPTOR);
                    this.exit();
                    reply.writeNoException();
                    return true;
                }
            }
            return super.onTransact(code, data, reply, flags);
        }

        private static class Proxy implements com.afollestad.aidlexample.IMainService {
            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 com.afollestad.aidlexample.MainObject[] listFiles(java.lang.String path) throws android.os.RemoteException {
                android.os.Parcel _data = android.os.Parcel.obtain();
                android.os.Parcel _reply = android.os.Parcel.obtain();
                com.afollestad.aidlexample.MainObject[] _result;
                try {
                    _data.writeInterfaceToken(DESCRIPTOR);
                    _data.writeString(path);
                    mRemote.transact(Stub.TRANSACTION_listFiles, _data, _reply, 0);
                    _reply.readException();
                    _result = _reply.createTypedArray(com.afollestad.aidlexample.MainObject.CREATOR);
                } finally {
                    _reply.recycle();
                    _data.recycle();
                }
                return _result;
            }

            @Override
            public void exit() throws android.os.RemoteException {
                android.os.Parcel _data = android.os.Parcel.obtain();
                android.os.Parcel _reply = android.os.Parcel.obtain();
                try {
                    _data.writeInterfaceToken(DESCRIPTOR);
                    mRemote.transact(Stub.TRANSACTION_exit, _data, _reply, 0);
                    _reply.readException();
                } finally {
                    _reply.recycle();
                    _data.recycle();
                }
            }
        }

        static final int TRANSACTION_listFiles = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
        static final int TRANSACTION_exit = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
    }

    public com.afollestad.aidlexample.MainObject[] listFiles(java.lang.String path) throws android.os.RemoteException;

    public void exit() throws android.os.RemoteException;
}

附上一張Framework層Binder通信模型圖:圖片來源

app_binder_demo.jpg

手寫B(tài)inder示例


binder-framework-demo.png

IMyService.java代碼:

/**
 * 作為接口
 */
public interface IMyService extends IInterface {
    static final java.lang.String DESCRIPTOR = "com.yuanhh.frameworkBinder.MyServer";
    public void sayHello(String str) throws RemoteException ;
    static final int TRANSACTION_say = android.os.IBinder.FIRST_CALL_TRANSACTION;
}

MyServicce.java代碼:

import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;

public class MyService extends Binder implements IMyService{ 
    

    public MyService() {
        this.attachInterface(this, DESCRIPTOR);
    }

    @Override
    public IBinder asBinder() {
        return this;
    }

    /** 將MyService轉(zhuǎn)換為IMyService接口 **/
    public static com.yuanhh.frameworkBinder.IMyService asInterface(
            android.os.IBinder obj) {
        if ((obj == null)) {
            return null;
        }
        android.os.IInterface iInterface = obj.queryLocalInterface(DESCRIPTOR);
        if (((iInterface != null) && (iInterface instanceof com.yuanhh.frameworkBinder.IMyService))) {
            return ((com.yuanhh.frameworkBinder.IMyService) iInterface);
        }
        return null;
    }

    /**  服務(wù)端蠢护,接收遠程消息擂啥,處理onTransact方法  **/
    @Override
    protected boolean onTransact(int code, Parcel data, Parcel reply, int flags)
            throws RemoteException {
        switch (code) {
        case INTERFACE_TRANSACTION: {
            reply.writeString(DESCRIPTOR);
            return true;
        }
        case TRANSACTION_say: {
            data.enforceInterface(DESCRIPTOR);
            String str = data.readString();
            sayHello(str);
            reply.writeNoException();
            return true;
        }
        }
        return super.onTransact(code, data, reply, flags);
    }

    /** 自定義sayHello()方法   **/
    @Override
    public void sayHello(String str) {
        System.out.println("MyService:: Hello, " + str);
    }
}

ServiceProxy.java代碼:

import android.os.IBinder;
import android.os.RemoteException;

public class MyServiceProxy implements IMyService {
    private android.os.IBinder mRemote;  //′ú±íBpBinder

    public MyServiceProxy(android.os.IBinder remote) {
        mRemote = remote;
    }

    public java.lang.String getInterfaceDescriptor() {
        return DESCRIPTOR;
    }

    @Override
    public void sayHello(String str) throws RemoteException {
        android.os.Parcel _data = android.os.Parcel.obtain();
        android.os.Parcel _reply = android.os.Parcel.obtain();
        try {
            _data.writeInterfaceToken(DESCRIPTOR);
            _data.writeString(str);
            mRemote.transact(TRANSACTION_say, _data, _reply, 0);
            _reply.readException();
        } finally {
            _reply.recycle();
            _data.recycle();
        }
    }

    @Override
    public IBinder asBinder() {
        return mRemote;
    }

}

ServerDemo.java:

import android.os.Looper;
import android.os.ServiceManager;

public class ServerDemo {

    public static void main(String[] args) {
        System.out.println("MyService Start");
        Looper.prepareMainLooper(); //開啟循環(huán)執(zhí)行
        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_FOREGROUND); //設(shè)置為前臺優(yōu)先級
        ServiceManager.addService("MyService", new MyService());//注冊服務(wù)
        Looper.loop();
    }

}

ClientDemo.java代碼:

import android.os.IBinder;
import android.os.RemoteException;
import android.os.ServiceManager;

public class ClientDemo {
 
    public static void main(String[] args) throws RemoteException {
        System.out.println("Client start");
        IBinder binder = ServiceManager.getService("MyService"); //獲取名為"MyService"的服務(wù)
        IMyService myService = new MyServiceProxy(binder); //創(chuàng)建MyServiceProxy對象
        myService.sayHello("binder"); //通過MyServiceProxy對象調(diào)用接口的方法
        System.out.println("Client end");
    }
}

一個介紹binder機制的系列文章

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市一忱,隨后出現(xiàn)的幾起案子界阁,更是在濱河造成了極大的恐慌,老刑警劉巖嫡良,帶你破解...
    沈念sama閱讀 222,252評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件次舌,死亡現(xiàn)場離奇詭異,居然都是意外死亡约素,警方通過查閱死者的電腦和手機书释,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,886評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來硅急,“玉大人,你說我怎么就攤上這事佳遂∮啵” “怎么了?”我有些...
    開封第一講書人閱讀 168,814評論 0 361
  • 文/不壞的土叔 我叫張陵丑罪,是天一觀的道長荚板。 經(jīng)常有香客問我凤壁,道長,這世上最難降的妖魔是什么跪另? 我笑而不...
    開封第一講書人閱讀 59,869評論 1 299
  • 正文 為了忘掉前任拧抖,我火速辦了婚禮,結(jié)果婚禮上免绿,老公的妹妹穿的比我還像新娘唧席。我一直安慰自己,他們只是感情好嘲驾,可當(dāng)我...
    茶點故事閱讀 68,888評論 6 398
  • 文/花漫 我一把揭開白布淌哟。 她就那樣靜靜地躺著,像睡著了一般辽故。 火紅的嫁衣襯著肌膚如雪徒仓。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,475評論 1 312
  • 那天誊垢,我揣著相機與錄音掉弛,去河邊找鬼。 笑死喂走,一個胖子當(dāng)著我的面吹牛狰晚,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播缴啡,決...
    沈念sama閱讀 41,010評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼壁晒,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了业栅?” 一聲冷哼從身側(cè)響起秒咐,我...
    開封第一講書人閱讀 39,924評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎碘裕,沒想到半個月后携取,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,469評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡帮孔,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,552評論 3 342
  • 正文 我和宋清朗相戀三年雷滋,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片文兢。...
    茶點故事閱讀 40,680評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡晤斩,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出姆坚,到底是詐尸還是另有隱情澳泵,我是刑警寧澤,帶...
    沈念sama閱讀 36,362評論 5 351
  • 正文 年R本政府宣布兼呵,位于F島的核電站兔辅,受9級特大地震影響腊敲,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜维苔,卻給世界環(huán)境...
    茶點故事閱讀 42,037評論 3 335
  • 文/蒙蒙 一碰辅、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧介时,春花似錦乎赴、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,519評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至勉失,卻和暖如春羹蚣,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背乱凿。 一陣腳步聲響...
    開封第一講書人閱讀 33,621評論 1 274
  • 我被黑心中介騙來泰國打工顽素, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人徒蟆。 一個月前我還...
    沈念sama閱讀 49,099評論 3 378
  • 正文 我出身青樓胁出,卻偏偏與公主長得像,于是被迫代替她去往敵國和親段审。 傳聞我的和親對象是個殘疾皇子全蝶,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,691評論 2 361

推薦閱讀更多精彩內(nèi)容