In Android, if we need to communicate between different processes, we need to use aidl technology to do it.
Aidl (Android Interface definition Language) is an interface definition language, and the compiler generates Java code that conforms to the communication protocol through the description information of the *.aidl file, so we don't have to write this complicated code ourselves. Only need to call when needed, in this way we can complete the process of communication between the work. About the writing rules of Aidl I do not introduce more here, readers can go online to find the relevant information.
Next, I'll show you the most basic process for manipulating aidl.
First, we need to build a service-side project, so:
In Iperson.aidl we define a "greeting" method, the code is as follows:
Package Com.scott.aidl; Interface IPerson { string greet (String someone);}
With the help of the Eclipse plugin, the compiler will automatically generate the corresponding Iperson.java file in the Gen directory, with the following formatted code:
Package Com.scott.aidl; Public InterfaceIPerson extends Android.os.IInterface {/** Local-side IPC implementation stub class.*/ Public Static Abstract classStub extends Android.os.Binder implements Com.scott.aidl.IPerson {Private StaticFinal Java.lang.String descriptor ="Com.scott.aidl.IPerson"; /** Construct The stub at attach it to the interface.*/ PublicStub () { This. Attachinterface ( This, descriptor); } /** * Cast an IBinder object to an Com.scott.aidl.IPerson interface, * Generating a proxy if needed. */ Public StaticCom.scott.aidl.IPerson asinterface (Android.os.IBinder obj) {if(obj = =NULL)) { return NULL; } android.os.IInterface iin=(android.os.IInterface) obj.querylocalinterface (descriptor); if(((Iin! =NULL) &&(iin instanceof Com.scott.aidl.IPerson))) { return((Com.scott.aidl.IPerson) iin); } return Newcom.scott.aidl.IPerson.Stub.Proxy (obj); } PublicAndroid.os.IBinder Asbinder () {return This; } @Override PublicBoolean Ontransact (intCode, Android.os.Parcel data, android.os.Parcel reply,intflags) throws Android.os.RemoteException {Switch(code) { Caseinterface_transaction: {reply.writestring (descriptor); return true; } CaseTransaction_greet: {data.enforceinterface (descriptor); Java.lang.String _arg0; _arg0=data.readstring (); Java.lang.String _result= This. Greet (_ARG0); Reply.writenoexception (); Reply.writestring (_result); return true; } } returnsuper.ontransact (Code, data, reply, flags); } Private Static classProxy implements Com.scott.aidl.IPerson {PrivateAndroid.os.IBinder Mremote; Proxy (Android.os.IBinder remote) {mremote=remote; } PublicAndroid.os.IBinder Asbinder () {returnMremote; } Publicjava.lang.String Getinterfacedescriptor () {returndescriptor; } Publicjava.lang.String greet (java.lang.String someone) throws Android.os.RemoteException {Android.os.Parcel _data=Android.os.Parcel.obtain (); Android.os.Parcel _reply=Android.os.Parcel.obtain (); Java.lang.String _result; Try{_data.writeinterfacetoken (descriptor); _data.writestring (someone); Mremote.transact (Stub.transaction_greet, _data, _reply,0); _reply.readexception (); _result=_reply.readstring (); } finally{_reply.recycle (); _data.recycle (); } return_result; } } StaticFinalintTransaction_greet = (Android.os.IBinder.FIRST_CALL_TRANSACTION +0); } Publicjava.lang.String greet (java.lang.String someone) throws android.os.RemoteException;}
The outline view of the file is as follows:
The abstract inner class stub in the IPerson interface inherits the Android.os.Binder class and implements the IPerson interface, and the more important method is the Asinterface (IBinder) method, This method converts an object of type IBinder to a IPerson type, and when necessary generates a proxy object to return the result.
The next step is our service:
Package Com.scott.server;import android.app.service;import android.content.intent;import android.os.IBinder; Import Android.os.remoteexception;import android.util.log;import Com.scott.aidl.IPerson; Public classAidlservice extends Service {Private StaticFinal String TAG ="Aidlservice"; Iperson.stub Stub=Newiperson.stub () {@Override Publicstring Greet (String someone) throws RemoteException {log.i (TAG,"greet () called"); return "Hello,"+someone; } }; @Override Publicibinder onbind (Intent Intent) {log.i (TAG,"Onbind () called"); returnstub; } @Override Publicboolean onunbind (Intent Intent) {log.i (TAG,"Onunbind () called"); return true; } @Override Public voidOnDestroy () {Super.ondestroy (); LOG.I (TAG,"OnDestroy () called"); }}
We implement the Greet method of iperson.stub this abstract class, and then return our stub instance in the Onbind (Intent) method, The iperson.stub that the caller gets is our example, and the Greet method executes as we expect.
Of course, in order for the service to take effect, we also need to do some configuration work in Androidmanifest.xml:
The server is finished, and then we have to finish the client work. I've built a client project,
We just need to copy the Iperson.aidl file to the appropriate directory, the compiler will also generate a corresponding Iperson.java file, which is no different from the server. In this way, the server and the client are unified on the communication protocol. Our main work is done in mainactivity.
The mainactivity code is as follows:
Package Com.scott.client;import Android.app.activity;import android.content.componentname;import Android.content.context;import Android.content.intent;import Android.content.serviceconnection;import Android.os.bundle;import Android.os.ibinder;import Android.os.remoteexception;import Android.util.Log;import Android.view.view;import android.widget.button;import android.widget.toast;import Com.scott.aidl.IPerson; Public classMainactivity extends Activity {PrivateButton bindbtn; PrivateButton greetbtn; PrivateButton unbindbtn; PrivateIPerson person; PrivateServiceconnection conn =Newserviceconnection () {@Override Public voidonserviceconnected (componentname name, IBinder service) {LOG.I ("serviceconnection","onserviceconnected () called"); person=IPerson.Stub.asInterface (service); } @Override Public voidonservicedisconnected (componentname name) {//This was called when the connection with the service had been unexpectedly disconnected,//that's, its process crashed. Because It is running in our same process and we should never see this happen.LOG.I ("serviceconnection","onservicedisconnected () called"); } }; @Override Public voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); BINDBTN=(Button) Findviewbyid (R.ID.BINDBTN); Bindbtn.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {Intent Intent=NewIntent ("Android.intent.action.AIDLService"); Bindservice (Intent, Conn, context.bind_auto_create); Bindbtn.setenabled (false); Greetbtn.setenabled (true); Unbindbtn.setenabled (true); } }); GREETBTN=(Button) Findviewbyid (R.ID.GREETBTN); Greetbtn.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {Try{String RetVal= Person.greet ("Scott"); Toast.maketext (mainactivity. This, RetVal, Toast.length_short). Show (); } Catch(RemoteException e) {toast.maketext (mainactivity. This,"Error", Toast.length_short). Show (); } } }); UNBINDBTN=(Button) Findviewbyid (R.ID.UNBINDBTN); Unbindbtn.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {unbindservice (conn); Bindbtn.setenabled (true); Greetbtn.setenabled (false); Unbindbtn.setenabled (false); } }); }}
As you can see from the code, we're going to rewrite the onserviceconnected method in Serviceconnection to convert the IBinder type to our IPerson type. Now we have the last step, and this link is also the most critical, is to bind the services we need. We bind their services through the "Android.intent.action.AIDLService" identifier defined by the service-side services, so that the client and the server implement the communication connection, and we can invoke the "greeting" method in IPerson.
Finally, several client presentation process diagrams are posted.
According to the order is: initial interface, click Bindservice after the interface, click Greet after the interface, click the Unbindservice after the interface.
The logs during the operation are as follows:
Android uses Aidl for inter-process communication