³õ̽AndroidÖеÄbinder»úÖÆ ÏÂÔØ±¾ÎÄ

* ±ØÐëµ÷Óø¸ÀàonTransact´¦ÀíÆäËûcode

*/

returnsuper.onTransact(code, data, reply, flags);

}

}

ʵÏÖbinder´úÀí¶Ë

Ç°Ãæ½éÉÜÁË£¬binder´úÀí¶ÔÏóÀà»áÄÚ¾ÛÒ»¸öbinderÒýÓöÔÏó,¸ÃÒýÓöÔÏóͨ¹ý¹¹Ôì·½·¨´«Èë¼´¿É:

publicclassBinderServiceProxyimplementsIBinderService{

/**

* ÄÚ¾ÛµÄbinderÒýÓöÔÏó

*/

private IBinder remote;

publicBinderServiceProxy(IBinder binder){

if(binder.queryLocalInterface(DESCRIPITON) == null )

remote = binder;

else

thrownew RuntimeException(\this is not a BpBinder.\);

}

@Override

public String getMessage() {

Parcel data = Parcel.obtain();

Parcel reply = Parcel.obtain();

data.writeInterfaceToken(DESCRIPITON);

try {

remote.transact(GET_MESSAGE,data,reply,0);

} catch (RemoteException e) {

e.printStackTrace();

}

reply.readException();

String msg = reply.readString();

data.recycle();

data.recycle();

return msg;

}

@Override

public IBinder asBinder() {

returnnull;

}

}

ÕâÀïÒªÌØ±ð×¢ÒâµÄÊÇ£¬ÒòΪbinder´úÀí¶ÔÏóÀàÄÚ¾ÛµÄÊÇÒ»¸öbinderÒýÓöÔÏó£¬ËùÒÔÒª¶Ô¹¹Ôì·½·¨Öд«ÈëµÄIbinder¶ÔÏó½øÐмì²é£¬±£Ö¤ÆäÊÇbinderÒýÓöÔÏó¡£

È»ºó¾ÍÊÇʵÏÖ·þÎñ½Ó¿Ú·½·¨£¬ÕâÀïºÜ¼òµ¥ÁË£¬¾ÍÊÇ×é×°ParcelÊý¾Ý£¬È»ºóÀûÓÃÒýÓÃbinder¶ÔÏ󷢯ðRPCµ÷Óá£

4. »ñÈ¡binderÒýÓöÔÏó

Õâ¾ÍÒª½èÖúAndroidÖеÄservice×é¼þÁË£¬²¢ÇÒÒÔbindService()·½·¨Æô¶¯¸Ãservice¡£

Ê×Ïȶ¨Òåservice×é¼þ£º

publicclassMyBinderServiceextendsService{

@Nullable

@Override

public IBinder onBind(Intent intent) {

returnnew BinderServiceStub();

}

}

È»ºóÔÚÇåµ¥ÎļþÖУ¬ÉùÃ÷¸Ãservice×é¼þ£¬²¢ÇÒÉèÖÃprocessÊôÐÔ£¬±£Ö¤¸ÃserviceÔËÐÐÔÚÁíÍâÒ»¸ö½ø³ÌÖУº

android:process=\/>

×îºóÒÔbindService()·½Ê½°ó¶¨¸Ãservice£º

Intent intent = new Intent();

intent.setClass(this,MyBinderService.class);

bindService(intent, new ServiceConnection() {

@Override

publicvoidonServiceConnected(ComponentName name, IBinder service) {

if(service.queryLocalInterface(IBinderService.DESCRIPITON)==null){

// µÃµ½binder´úÀí¶ÔÏó

BinderServiceProxy proxy = new BinderServiceProxy(service);

// ¿ªÊ¼Ö´Ðз½·¨

Log.i(\,\\+proxy.getMessage());

}

}

@Override

publicvoidonServiceDisconnected(ComponentName name) {

}