The previous period of time studied a lot of Android two development, one of the methods is through aidl communication, leaving the interface to provide outside two times development. It can also be seen from here that aidl communication is a process communication between two applications. In this blog, the main write two applications, one is Serverdemo, can be called the server, is also an application to provide interfaces, in this case I wrote an addition calculation. The second is the client: Clientdemo, in this program called the addition calculation interface, the value is passed to Serverdemo for addition calculation, return the result, to display.
1, the definition of Aidl
Aidl is Android Interface Definition language abbreviation, it is an Android internal process communication Interface Description Language, through which we can define the communication interface between processes;icp:interprocess Communication: Internal process communication.
2, two project structure and realization effect
As you can see from the image above, there is nothing on the server side layout, but there is an addition calculation service. While the client has two input boxes to enter two values, click Calculate.
3. Server service side3.1. Create a new aidl file
Save your Aidl file, as long as it is developed in Eclipse, your ADT plugin will compile the Aidl file like a resource file into Java code generated in the Gen folder, without having to compile it manually: Compile and generate Aidlservice.java code like my example.
Iboardaddinterface.aidl
Package Com.example.server;import android.os.bundle;/*** * System private API for talking with the Caculate service. * {@hide} */interface iboardaddinterface{ int Add (int nvalue1,int nValue2);}
automatically putaidl files are compiled into Java code to generate Iboardaddinterface interface code under the Gen folder
/* * This file is auto-generated. Do not MODIFY. * Original file:c:\\users\\southgnssliyc\\desktop\\android aidl\\serverdemo\\src\\com\\example\\server\\ Iboardaddinterface.aidl */package com.example.server;/*** * System private API for talking with the Caculate service. * * {@hide} */public interface Iboardaddinterface extends android.os.iinterface{/** local-side IPC implementation stub CLA SS. */public static abstract class Stub extends Android.os.Binder implements com.example.server.iboardaddinterface{ Private static final Java.lang.String descriptor = "Com.example.server.IBoardADDInterface";/** Construct the stub at Atta CH it to the interface. */public Stub () {this.attachinterface (this, descriptor);} /** * Cast an IBinder object to an Com.example.server.IBoardADDInterface interface, * Generating a proxy if needed. */public static Com.example.server.IBoardADDInterface asinterface (Android.os.IBinder obj) {if ((Obj==null)) {return null;} Android.os.IInterface iin = Obj.querylocalinterfacE (descriptor), if (((iin!=null) && (iin instanceof Com.example.server.IBoardADDInterface)) {return ( Com.example.server.IBoardADDInterface) iin);} return new Com.example.server.IBoardADDInterface.Stub.Proxy (obj); @Override public Android.os.IBinder Asbinder () {return this;} @Override public boolean ontransact (int code, ANDROID.OS.PARCEL data, android.os.Parcel reply, int flags) throws ANDROID.O S.remoteexception{switch (code) {case interface_transaction:{reply.writestring (descriptor); return true;} Case Transaction_add:{data.enforceinterface (descriptor); int _arg0;_arg0 = Data.readint (); int _arg1;_arg1 = Data.readint (); int _result = This.add (_arg0, _ARG1); Reply.writenoexception (); Reply.writeint (_result); return true;}} Return Super.ontransact (Code, data, reply, flags);} private static class Proxy implements Com.example.server.iboardaddinterface{private Android.os.IBinder Mremote; Proxy (Android.os.IBinder remote) {mremote = remote;} @Override public Android.os.IBinder Asbinder () {return mremote;}Public java.lang.String Getinterfacedescriptor () {return descriptor;} @Override public int Add (int nValue1, int nValue2) throws Android.os.remoteexception{android.os.parcel _data = Android.os . Parcel.obtain (); Android.os.Parcel _reply = Android.os.Parcel.obtain (); int _result;try {_data.writeinterfacetoken ( descriptor); _data.writeint (nValue1); _data.writeint (nValue2); Mremote.transact (Stub.transaction_add, _data, _reply , 0); _reply.readexception (); _result = _reply.readint ();} finally {_reply.recycle (); _data.recycle ();} return _result;}} static final int transaction_add = (Android.os.IBinder.FIRST_CALL_TRANSACTION + 0);} public int Add (int nValue1, int nValue2) throws android.os.RemoteException;}This code is automatically generated as a look.
3.2, the service side of the calculation of the addition implementation class, write a server
Package Com.example.server;import Android.app.service;import Android.content.intent;import android.os.IBinder; Import Android.os.remoteexception;import android.util.log;/** * server-side compute addition implementation class * @author MMSX * */public class Caculateaddse Rvice extends Service {//addition computed services final String caculate_add = "COM. Caculate. ADD ";//Find Custom Service @overridepublic ibinder onbind (Intent Intent) {if (Intent.getaction (). Equals (Caculate_add)) {return Mibinder_caculate_add;} return null;} @Overridepublic boolean onunbind (Intent Intent) {return super.onunbind (Intent);} @Overridepublic void OnDestroy () {Super.ondestroy ();} @Overridepublic void OnCreate () {super.oncreate ();} The Aidl interface implements private final IBinder Mibinder_caculate_add = new Iboardaddinterface.stub () {@Overridepublic int ADD (int nValue1, int nValue2) throws RemoteException {log.i ("Show", string.valueof (nValue1) + ",,," +string.valueof (nValue2)); return nValue1 + nValue2;}};}
Now that you've written a service, you need to add a registration to the Androidmanifest.xml
<service android:name= "Com.example.server.CaculateAddService" > <intent-filter> <action Android:name= "COM. Caculate. ADD > </action> </intent-filter> </service>
This name is custom: COM.CACULATE.ADD. The path of the service Com.example.server.CaculateAddService.
It is not easy to finish this service-side application. The activity didn't write anything because it just used a service and aidl inside.
4. Client Clients4.1, the service side of the aidl copy to the client, the code does not change
Package Com.example.server;import android.os.bundle;/*** * System private API for talking with the Caculate service. * {@hide} */interface iboardaddinterface{ int Add (int nvalue1,int nValue2);}
automatic compilation of generated code is not posted.
. 4.2. Write a class that binds the compute service Caculatemanager
Package Com.example.clientdemo;import Com.example.server.iboardaddinterface;import Android.content.ComponentName; Import Android.content.context;import Android.content.intent;import Android.content.serviceconnection;import android.os.ibinder;/** * Client Service Calculation Management class * @author MMSX * */public class Caculatemanager {//addition computed service final String Caculate_add = "COM. Caculate. ADD ";//aidi interface service Iboardaddinterface mservice = null; /*** * Service bindings */public void Bindservice (context context) {Mcontext = context; Context.bindservice (New Intent (Caculate_add), serviceconnection, context.bind_auto_create); } Context mcontext = null; /*** * Unbind Service binding */public void Unbindservice () {if (Mcontext! = null) {Mcontext.unbindservice (Servicecon nection);} }/** * Addition calculation * @param nValue1 * @param nValue2 * @return result */public int caculateadd (int NV Alue1,int nValue2) {if (Mservice = = null) return 0;try {return Mservice.add (nValue1, nValue2);} CAtch (Exception e) {return 0;} }//service and AIDL interface binding private serviceconnection serviceconnection = new Serviceconnection () {@Overridepublic void onSe rvicedisconnected (componentname name) {mservice = null;} @Overridepublic void onserviceconnected (componentname name, IBinder service) {Mservice = IBoardADDInterface.Stub.asInterface (service);}};}There is a service to find, to relieve the service. The interface that the method implements.
4.3, activity input data, call interface
Package Com.example.clientdemo;import Android.os.bundle;import Android.app.activity;import Android.view.View; Import Android.view.view.onclicklistener;import Android.widget.edittext;import Android.widget.textview;public Class Mainactivity extends Activity {caculatemanager Caculatemanager = new Caculatemanager (); @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Caculatemanager.bindservice (this); Findviewbyid (R.id.button1). Setonclicklistener (New Onclicklistener () {@ overridepublic void OnClick (View v) {EditText editText1 = (EditText) Findviewbyid (R.ID.EDITTEXT1); EditText editText2 = (EditText) Findviewbyid (R.ID.EDITTEXT2); int nValue1 = Integer.parseint (Edittext1.gettext (). ToString (). Trim ()); int nValue2 = Integer.parseint (Edittext2.gettext (). toString (). Trim ()); int nresult = Caculatemanager.caculateadd (nValue1, nValue2); TextView TextView = (TextView) Findviewbyid (r.id.textview1); Textview.settext ("Calculated result:" + String. ValueOf (Nresult));}});}} The XML code is simple
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:id=" @+id/linearlayout1 "android:layout_width=" Match_parent "Android:layout_hei ght= "match_parent" android:orientation= "vertical" tools:context= ". Mainactivity "> <textview android:layout_width=" wrap_content "android:layout_height=" Wrap_content " android:text= "Use Aidi service to invoke other program calculations, return results"/> <edittext android:id= "@+id/edittext1" android:layout _width= "Match_parent" android:layout_height= "Wrap_content" android:ems= "ten" android:inputtype= "number Decimal "> <requestfocus/> </EditText> <edittext android:id=" @+id/edittext2 " Android:layout_width= "Match_parent" android:layout_height= "Wrap_content" android:ems= "ten" android:in Puttype= "Numberdecimal"/> <textview android:id= "@+id/textview1" android:lAyout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "calculation result:"/> <Button Android:id= "@+id/button1" android:layout_width= "match_parent" android:layout_height= "Wrap_content" android:text= "Addition calculation"/></linearlayout>
Finally, this article's blog code: Download
Android Aidl Communication Detailed