Analysis of aidl communication mechanism in Android

Source: Internet
Author: User

    • I. BACKGROUND

• 1, the cause of aidl appearance

In the Android system, each program is running in its own process, the process can not communicate, in order to on the Android platform, a process usually can not access the memory space of another process, so to talk, you need to decompose the object into the operating system can understand the basic unit, and orderly through the process boundary. Implementing this data transfer process through code is tedious, and Android provides aidl tools to handle this work, implementing IPC (Inter-communication) similar to RMI in J2E.

• 2. Bind Service

I read a lot of people are not talking about the blog here, in fact, I personally feel that Aidl is a remote client only, the previous bindservice in the service of the inheriting class alone to put out to the remote client, In a locally bound service we typically return an internally defined object of the binder class to the activity in the Onbind method, get the object in active and then go to invoke the method for Bindservice introduction see next blog post. But it's different here. We're going to another process. White point is another application to get the data, so we need some rules on the interface, to standardize the communication between the process, let the server application to send, the client application to accept. Let's say the rules are God's horse?

    • Second, the Aidl service end of the steps

1. Implement the. aidl file

As an example of eclipse development, we need to create a new package---folder under the SRC folder, and then create a new file in that folder directory. The suffix of the file ends in. aidl, which is necessary.

·2. Inside the file, you first give the package name,

·3. In the interface to the data type, in addition to the basic type, string,list,map,charsequence, other than the need to guide the package, even in the same package is also required to guide the package, so inside the class, and methods we need to guide the package.

4. Android ADT will generally help us to automatically compile the written aidl file to generate a Java syntax interface class, this excuse under the Gen file, you can open the inside of the default generated an internal abstract class stub that class inherits binder implements the external interface,

5. Define the method name, all the. aidl files already need to pass the interface of the object must be in the service and the client, it is best to copy the past directly.

----------------------------------The following is the server-side Aidl file definition that provides data access:

1  Package Com.example.service; 2 3 Interface dataservice{4     Double getData (String arg); 5           6 }

6. The following is the implementation of the Aidl interface in the service's custom class, which already explains what we pass through the binding service is actually a IBinder object, where the actual implementation of the interface is automatically generated in Gen Dataservice.java's abstract inner class Stub, because the class inherits the binder, and binder implements the IBinder interface, so we actually need the Dataservice.stub object.

---------------The following is the code in the Server service, which is in fact consistent with the rules for binding services,

=========== goal is consistent is to send a IBinder object agent to the client, the client receives the object, with this object can invoke some methods of the object.

1 ImportCom.example.service.DataService;2 3 ImportAndroid.app.Service;4 Importandroid.content.Intent;5 ImportAndroid.os.Binder;6 ImportAndroid.os.IBinder;7 Importandroid.os.RemoteException;8 9  Public classMyServiceextendsService {Ten  One @Override A      Publicibinder onbind (Intent Intent) { -         //This binder is the object to be sent to the remote client, after the connection is established, the client obtains the object and invokes the object's method to fetch the data.  -         returnBinder; the     } -     ///Another thing to note is that our service needs to be registered in the configuration file, while adding an action filter to facilitate our invocation, binding.  -     //because a IBinder object is required to return and this object is an interface, it is necessary to implement the object of the class specifically, Binder implements the interface, so we need to create a binder object, -     //and the interface in our defined Aidl file is compiled to automatically generate an inner class stub that inherits the binder +     //defines the methods that are provided to client clients for invocation -Binder Binder =Newdataservice.stub () { + @Override A          Public DoubleGetData (String Arg)throwsRemoteException { at             //TODO auto-generated Method Stub -              -             if(Arg.equals ("a")) { -                 return1; -}Else if(Arg.equals ("B")) { -                 return2; in             } -              to             return0; +         } -     }; the  *}

The ===================== above runs directly to run and can be empty activity.

The following is the operation of the client

The client first is to have the Aidl file above already mentioned, the following is directly on the code

---------------First is a layout file, simply two buttons

1<relativelayout xmlns:android= "Http://schemas.android.com/apk/res/android"2Xmlns:tools= "Http://schemas.android.com/tools"3Android:layout_width= "Match_parent"4android:layout_height= "Match_parent"5android:paddingbottom= "@dimen/activity_vertical_margin"6android:paddingleft= "@dimen/activity_horizontal_margin"7android:paddingright= "@dimen/activity_horizontal_margin"8android:paddingtop= "@dimen/activity_vertical_margin"9Tools:context= ". Mainactivity ">Ten  One<Button AAndroid:id= "@+id/button1" -Android:layout_width= "Wrap_content" -android:layout_height= "Wrap_content" theAndroid:layout_alignparenttop= "true" -Android:layout_centerhorizontal= "true" -android:layout_margintop= "92DP" -android:text= "bind service"/> +  -<Button +Android:id= "@+id/button2" AAndroid:layout_width= "Wrap_content" atandroid:layout_height= "Wrap_content" -android:layout_below= "@+id/button1" -Android:layout_centerhorizontal= "true" -android:layout_margintop= "88DP" -Android:text= "Inter-process communication"/> -  in</RelativeLayout>
View Code

Here is the code in the activity, we want to establish a connection with the server, we must bind to the service class defined on the server in the Bindservice method.

Ok

1 ImportCom.example.service.DataService;2 3 ImportAndroid.os.Bundle;4 ImportAndroid.os.IBinder;5 Importandroid.app.Activity;6 ImportAndroid.content.ComponentName;7 ImportAndroid.content.Context;8 Importandroid.content.Intent;9 Importandroid.content.ServiceConnection;Ten ImportAndroid.view.View; One ImportAndroid.widget.Button; A  -  Public classMainactivityextendsActivity { -  the     PrivateButton button1, button2; -     PrivateDataService DataService; -  - @Override +     protected voidonCreate (Bundle savedinstancestate) { -         Super. OnCreate (savedinstancestate); + Setcontentview (r.layout.activity_main); AButton1 =(Button) Findviewbyid (r.id.button1); atButton2 =(Button) Findviewbyid (r.id.button2); -  -         //binding -Button1.setonclicklistener (NewView.onclicklistener () { -  - @Override in              Public voidOnClick (View v) { -                 //TODO auto-generated Method Stub toIntent Intent =NewIntent (DataService.class. GetName ()); +                 //Binding Service -                 /*Bindservice (SERVICE, Conn, flags) The parameters of the method explain the * 1.service: Indicates the service to start with this parameter * * 2.conn: This parameter is a serviceconnection, the object is used for the connection between the sword and the Rain service, when the visitor and the service $ * The onserviceconnected (componentname name, IBinder Service) method is called when the connection is successful, which is used to obtainPanax Notoginseng * The IBinder object in the service that gets the data through the object. Connection failed onservicedisconnected.  -                  */ the                  + Bindservice (Intent, connection, context.bind_auto_create); A             } the         }); +  -Button2.setonclicklistener (NewView.onclicklistener () { $  $ @Override -              Public voidOnClick (View v) { -                 //TODO auto-generated Method Stub the                 Try { -                     Doubleresult = Dataservice.getdata ("a");WuyiSYSTEM.OUT.PRINTLN ("--->>" +result); the  -}Catch(Exception e) { Wu                     //Todo:handle Exception - e.printstacktrace (); About                 } $             } -         }); -     } -  A     //The client connects to the service +     PrivateServiceconnection connection =Newserviceconnection () { the @Override -          Public voidonservicedisconnected (componentname name) { $             //TODO auto-generated Method Stub the  the         } the  the @Override -          Public voidonserviceconnected (componentname name, IBinder service) { in             //TODO auto-generated Method Stub the             //These are several classes of DataService.Stub.asInterface that are automatically generated by the SDK, as referenced in the API the             //The IBinder object passed over by the client, in exchange for the DataService object, About             //Here you need to use one of the methods in the internal stub that is automatically generated after the Aidl file is compiled Asinterface, the function of which is the type conversion theDataService =DataService.Stub.asInterface (service); the         } the     }; +}

Summary In fact, this aidl and binding service is not much different, but we put the service's inheritance class on the client, adding some protocol specifications.

Analysis of aidl communication mechanism in Android

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.