Advanced Android Notes: Aidl internal Implementation Details (ii)

Source: Internet
Author: User

Then the analysis of the aidl process. Know that Aidl is mainly to use IBinder to achieve cross-process communication. Since it is encapsulated in various methods of binder, it is also possible to implement cross-process communication without using aidl itself through binder. Then this blog is mainly to write about through the previous (Android Advanced Note: Aidl detailed (a)) summed up the knowledge to achieve cross-process communication to more thorough understanding of aidl core logic.

First the previous blog (Android Advanced Note: Aidl detailed (a)) summed up a conclusion ———— "Ontransact method is provided to the server side, The Transact method (the inner class proxy encapsulates the Transact method) and the Asinterface method is used for the client side. "It is therefore clear that as long as we implement the methods (similar to the Aidl interface implementations) and the ontransact methods that cross-process calls on the server side, the service side can use Aidl to implement cross-process communication by invoking the Transact method with the obtained IBinder object." Now that the idea has been sorted out, it is one step at a pace to achieve it.

Server Side

First, the server side is to use the service's Onbind method to give the client a Binder object, then start with this binder object. Let's start by creating a Mybinder class with the following code:

Mybinder.java

PublicClassMybinderExtendsBinder {Of the markup methodPrivateStaticFinalint Method_add_code =1001;That identifies the binder object.PrivateStaticFinal String DESCRIPTION ="Not use Aidl";@OverrideProtectedBooleanOntransact (int code, PARCEL data, Parcel reply,int flags) throws remoteexception {if (code = = Method_add_code) {//Verify binder Data.enforceinterface (DESCRIPTION); //read parameters from Parcel object int arg0 = Data.readint (); int arg1 = Data.readint (); //Write Results Reply.writeint (add (arg0, arg1)); return true;} return super.ontransact (code, data, reply, flags);} private int add ( int arg0, int arg1) {return arg0 + Arg1; }} 

The code is very simple, just to re-write the Ontransact method. In fact, there are only 4 steps:

    1. According to the value of code to determine the client side specifically want to invoke which method;
    2. Reads the parameters passed in the Parcel object (data);
    3. Call your own local method (add) and pass in the parameters;
    4. The result is written to the parcel object (reply);

Then simply return the instance of the Mybinder class of your own definition through the Service.onbinder method to the client side.

Myservice.java

public class myservice extends Service {private mybinder Mybinder; public myservice () {}  @Override public void onCreate () {super.oncreate (); //Create instance Mybinder = new Mybinder ();}  @Override public ibinder onBind (Intent Intent) {//returns a custom binder object return Mybinder;}      

Client Side

The client side of the code is nothing more than the previous written in the aidl of the proxy internal class method to take out. See the code specifically:

Withoutaidlactivity.java

PublicClassWithoutaidlactivityExtendsappcompatactivity {Private Serviceconnection serviceconnection;Private IBinder Binder;The following two parameters are consistent with the server sideTag method (tells the server which method to invoke)PrivateStaticFinalint Method_add_code =1001;That identifies the binder object.PrivateStaticFinal String DESCRIPTION ="Not use Aidl";@OverrideProtectedvoidOnCreate (Bundle savedinstancestate) {Super.oncreate (savedinstancestate); Setcontentview (R.LAYOUT.ACTIVITY_WITHOUT_AIDL); Serviceconnection =New Serviceconnection () {@OverridePublicvoidonserviceconnected (componentname name, IBinder service) {LOG.D ("Onserviceconnected","Onserviceconnected:connected success! "); Binder = Service;This replaces the proxy in AIDL to call the Transact method directlyFirst prepare the parameter Parcel data = Parcel.obtain (); Parcel reply = Parcel.obtain (); Data.writeinterfacetoken (DESCRIPTION); Data.writeint (123); Data.writeint (456);try {Call the Transact method Binder.transact (Method_add_code, data, reply,0);Get resultsint result = Reply.readint (); LOG.D ( "onserviceconnected",  "result =" + result);} catch (remoteexception e) {e.printstacktrace ();} finally {data.recycle (); Reply.recycle ();}}  @Override public void onservicedisconnected (componentname name) {binder = null;}}; Bindservice (new Intent ( "Com.coder_f.aidlserver.MyService") , Serviceconnection, bind_auto_create); }  @Override protected void Span class= "Hljs-title" >ondestroy () {super.ondestroy (); Unbindservice ( Serviceconnection); }}

First the connection succeeds, the IBinder instance is obtained in the Serviceconnection.onserviceconnected method, and then a total of 3 things are done:

    1. Create two parcel objects to hold parameter (data) and return value (Reply)
    2. Call the Transact method, pass in the data,reply, and the method you want to call code. The last flag passed in 0 indicates a return value (1 means no and return value)
    3. Get results from reply

By completing the above work, cross-process communication can be achieved without aidl. But let's just say that this is a simple Add method that is not time-consuming for our server, and the Transact method is actually executed in the main thread when the Onserviceconnected method is invoked. If the Add method is replaced by a time-consuming method, the main thread (UI thread) will be stuck, and when the Transact method is called, the thread will be suspended knowing that the result is returned (it is interesting to try it, just add a thread.sleep to the Add method). So the best way to do this is to start a thread that calls the Transact method.

Advanced Android Notes: Aidl internal Implementation Details (ii)

Related Article

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.