使用AIDL双向通信

来源:互联网 发布:不调用淘宝客api 编辑:程序博客网 时间:2024/06/06 00:47
之前实现了一个功能,要求能和另一个进程的Service双向通信,除了远程Service中要实现


IInterface.Stub(),客户进程(调用远程Service的应用)也要实现一个ICallBack.Stub(),而该ICallBack也是通过AIDL定义。例子如下:


IService .aidl

interface IService {   void init(ICallback callBack);  }


ICallback.aidl

interface ICallback {   void onResult(String result);void onError(String errorMsg, int errorCode);}

远程Service中的一个内部类:

private final IService.Stub mBinder = new IService.Stub() {public ICallback mCallBack;@Overridepublic void init(ICallback callBack)throws RemoteException {mCallBack = callBack;}}


在Android group中也有一个类似的话题:


https://groups.google.com/forum/#!topic/android-developers/X3SCuioxpYE

其中一个回答建议参考android api example的Remote Service. 

https://android.googlesource.com/platform/development/+/master/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.java 

   final RemoteCallbackList<IRemoteServiceCallback> mCallbacks            = new RemoteCallbackList<IRemoteServiceCallback>();
一下是RemoteCallbackList的文档:

To use this class, simply create a single instance along with your service, and call itsregister(E) andunregister(E) methods as client register and unregister with your service. To call back on to the registered clients, use beginBroadcast(),getBroadcastItem(int), andfinishBroadcast().

If a registered callback's process goes away, this class will take care of automatically removing it from the list. If you want to do additional work in this situation, you can create a subclass that implements theonCallbackDied(E) method.

可见用RemoteCallbackList来管理这些远程回调接口更为方便。

0 0
原创粉丝点击