资源描述:
《activity中使用aidl让service与activity通信》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、简易计算器,默认执行1+1的计算,点击go按钮执行计算,先看效果图,如下首先建立一个ICallback.aidl文件,作为Activity中的回调方法Java代码//MyAIDLfile,namedSomeClass.aidlpackagecom.zhang.test.service;//Seethelistaboveforwhichclassesneed//importstatements(hint--mostofthem)//Declaretheinterface.interfaceICallback{//Meth
2、odscantake0ormoreparameters,and//returnavalueorvoid.//MethodscaneventakeotherAIDL-definedparameters.//BankAccountcreateAccount(inStringname,intstartingDeposit,inIAtmServiceatmService);//Allnon-Javaprimitiveparameters(e.g.,int,bool,etc)require//adirectionaltagind
3、icatingwhichwaythedatawillgo.Available//valuesarein,out,inout.(Primitivesareinbydefault,andcannotbeotherwise).//Limitthedirectiontowhatistrulyneeded,becausemarshallingparameters//isexpensive.voidshowResult(intresult);}复制代码然后再建立一个IService.aidl用来在Activity中接收Servic
4、e回调,以及在Service中onBind时返回的Binder注意:aidl中import不能写com.xxx.*,要写全类的路径Java代码packagecom.zhang.test.service;importcom.zhang.test.service.ICallback;interfaceIService{voidregisterCallback(ICallbackcb);voidunregisterCallback(ICallbackcb);}复制代码接下来是service,CalculateService.
5、javaJava代码packagecom.zhang.test.service;importandroid.app.Service;importandroid.content.BroadcastReceiver;importandroid.content.Context;importandroid.content.Intent;importandroid.content.IntentFilter;importandroid.os.Handler;importandroid.os.IBinder;importandroi
6、d.os.Message;importandroid.os.RemoteCallbackList;importandroid.os.RemoteException;importandroid.util.Log;publicclassCalculateServiceextendsService{privatestaticfinalStringTAG="MainService";publicstaticfinalStringACTION_CALCUlATE="action_calculate";privateRemoteC
7、allbackListmCallbacks=newRemoteCallbackList();privateIService.StubmBinder=newIService.Stub(){@OverridepublicvoidunregisterCallback(ICallbackcb){if(cb!=null){mCallbacks.unregister(cb);}}@OverridepublicvoidregisterCallback(ICallbackcb){if(cb!=null){mCallbacks.regi
8、ster(cb);}}};//这里的BroadcastReceiver实现了Activity主动与Service通信privateBroadcastReceiverreceiver=newBroadcastReceiver(){@OverridepublicvoidonReceive(Contextcontext,Intentin