AIDL的底層是通過Binder進行通信的,通過追蹤.aidl編譯后自動生成的文件我們知道,文件中的Stub類用于服務端,Proxy類用于客戶端調用,那么可否直接通過繼承Binder類實現多進程通信呢?下面就來試一試。
效果圖:

服務端代碼,BinderService.java:
首先繼承Binder 類,實現onTransact()供客戶端調用,同樣通過onBind()返回Binder實例:
private static final java.lang.String DEscriptOR = "org.ninetripods.mq.multiprocess_sever.IAidlCallBack";private static final int KEY_FLAG = 0x110;private class MyBinder extends Binder { /** * @param code 唯一標識,客戶端傳遞標識執行服務端代碼 * @param data 客戶端傳遞過來的參數 * @param reply 服務器返回回去的值 * @param flags 是否有返回值 0:有 1:沒有 * @return * @throws RemoteException 異常 */ @Override protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException { switch (code) { case KEY_FLAG: //標識服務器名稱 data.enforceInterface(DEscriptOR); Apple apple = new Apple("紅星蘋果", 15f, getString(R.string.response_binder_info)); reply.writeNoException(); reply.writeInt(1); apple.writeToParcel(reply, android/216528.html">android/176373.html">android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE); return true; } return super.onTransact(code, data, reply, flags); } } @Override public IBinder onBind(Intent intent) { return new MyBinder(); }在AndroidManifest.xml中聲明一下:
<service android:name=".BinderService" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="android.mq.binder.service" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter></service>
客戶端代碼:BinderActivity.java:
首先編寫ServiceConnection 類來獲得Binder實例,來發送和接收數據:
private ServiceConnection binderConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { isBound = true; mService = service; if (mService != null) { //聲明兩個Parcel類型數據(_data和_reply) 一個用于傳輸數據 一個用于接收數據 android.os.Parcel _data = android.os.Parcel.obtain(); android.os.Parcel _reply = android.os.Parcel.obtain(); Apple apple; try { //與服務器端的enforceInterface(DEscriptOR)對應 _data.writeInterfaceToken(DEscriptOR); //調用服務端的transact()傳輸數據 mService.transact(KEY_FLAG, _data, _reply, 0); _reply.readException(); if (0 != _reply.readInt()) { //接收服務端響應數據 apple = Apple.CREATOR.createFromParcel(_reply); } else { apple = null; } showMessage(apple != null ? ("/n" + apple.getNoticeInfo() + "/n名稱:" + apple.getName() + "/n價格:" + apple.getPrice() + " 元") : "未獲得服務器信息", R.color.red_f); } catch (Exception e) { e.printStackTrace(); } finally { _data.recycle(); _reply.recycle(); } } } @Override public void onServiceDisconnected(ComponentName name) { isBound = false; mService = null; } };然后就是綁定服務了:
Intent intent = new Intent(); intent.setAction("android.mq.binder.service"); intent.setPackage("org.ninetripods.mq.multiprocess_sever"); bindService(intent, binderConnection, BIND_AUTO_CREATE);代碼也挺簡單,里面用到的Apple類已經實現了Pacelable接口序列化,進程間傳輸數據就是一個數據序列化和反序列化的過程~
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答