Analysis of Asinterface in binder

Source: Internet
Author: User

When using aidl communication, a asinterface function is generated in the stub class, which is analyzed in the example of "Android development Art exploration", which generates the Asinterface function source code:

1         /**2 * Cast an IBinder object to an Com.willhua.demoaidl.aidl.IBookManager3 * interface, generating a proxy if needed.4          */5          Public StaticCom.willhua.demoaidl.aidl.IBookManager Asinterface (6 Android.os.IBinder obj) {7             if(obj = =NULL)) {8                 return NULL;9             }TenAndroid.os.IInterface iin =Obj.querylocalinterface (descriptor); One             if(((Iin! =NULL) && (iininstanceofCom.willhua.demoaidl.aidl.IBookManager )) { A                 return((Com.willhua.demoaidl.aidl.IBookManager) iin); -             } -             return Newcom.willhua.demoaidl.aidl.IBookManager.Stub.Proxy (obj); the}

We know that the role of Asinterface is to return different instance objects depending on whether the call belongs to the same process, but what is going on in the process, what is returned, and perhaps a lot of children's shoes are not very clear, share a little of my understanding on this issue. Clearly, it is clear from the code that the decision to return the key to what object is the return result of Obj.querylocalinterface (descriptor).

Let's look at the actual demo to understand the process. The code is based on an example from "Android Exploration for art".

There are two main things in the demo, one is Mainactivity, one is bookservice,mainactivity will go to bind Bookservice, and bookservice by setting up Android in Manifest :p rocess and Mainactivity to run in the same process and different processes respectively.

Main code:

 Public class extends Service {    privatenew  ibookmanager.stub () {    ...    };        @Override    public  ibinder onbind (Intent Intent) {        //  TODO auto-generated method Stub        LOG ("Bookservice onbind mbinder:" +mbinder.getclass (). GetName () + "Process:" +< c18> process.mypid ());         return Mbinder;}    }
 Public classMainactivityextendsactivity{PrivateIbookmanager Mservice; PrivateButton Mquery; PrivateTextView Moutinfo; ... @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main);    Connectservice (); }        Private voidConnectservice () {Intent Intent=NewIntent (Getapplicationcontext (), Bookservice.class); Bindservice (Intent,Newserviceconnection () {@Override Public voidonservicedisconnected (componentname name) {//TODO auto-generated Method Stub} @Override Public voidonserviceconnected (componentname name, IBinder service) {//TODO auto-generated Method StubLOG ("onserviceconnected" +service); Mservice=IBookManager.Stub.asInterface (service);            }}, Bind_auto_create); }    ...}

     Public Static Abstract classStubextendsAndroid.os.BinderImplementsCom.willhua.demoaidl.aidl.IBookManager {Private Static FinalJava.lang.String descriptor = "Com.willhua.demoaidl.aidl.IBookManager"; /**Construct The stub at attach it to the interface.*/         PublicStub () { This. Attachinterface ( This, descriptor); }        /*** Cast an IBinder object to an com.willhua.demoaidl.aidl.IBookManager * interface, generating a pro         XY if needed. */         Public Staticcom.willhua.demoaidl.aidl.IBookManager asinterface (Android.os.IBinder obj) {if(obj = =NULL)) {                return NULL; } android.os.IInterface iin=Obj.querylocalinterface (descriptor); if(((Iin! =NULL) && (iininstanceofCom.willhua.demoaidl.aidl.IBookManager )) {return((Com.willhua.demoaidl.aidl.IBookManager) iin); }            return Newcom.willhua.demoaidl.aidl.IBookManager.Stub.Proxy (obj); }...}

Androd.os.Binder Part Source:

 Public classBinderImplementsIBinder {//...    /*** Convenience method for associating a specific interface with the Binder. * After calling, Querylocalinterface () is implemented for you * to return the given owner IInterface when the Cor     Responding * descriptor is requested. */     Public voidAttachinterface (iinterface owner, String descriptor) {Mowner=owner; Mdescriptor=descriptor; }        /*** Use information supplied to Attachinterface () to return the * associated IInterface if it matches the Reque     sted * Descriptor. */     Publiciinterface querylocalinterface (String descriptor) {if(Mdescriptor.equals (descriptor)) {returnMowner; }        return NULL; }        //...        Final classBinderproxyImplementsIBinder {//...                 Publiciinterface querylocalinterface (String descriptor) {return NULL; }                //...    }}    

With log, we find that, in the onserviceconnected function, if mainactivity and Bookservice are in the same process, the printed log is:

If mainactivity and Bookservice process, and mainactivity cross-process binding Bookservice service, the printed log is:

analyze the same process first ,

In the same process, the type of service object received by Onserviceconnected is bookservices$1, and we know that $ represents the inner class in bookservices, and in the definition of bookservices, We only defined a subclass of Ibookmanager.stub () in Mbinder initialization, which is the ibookmanager.stub () type that is received at onserviceconnected when the same process is in progress. and Ibookmanager.stub () Extenders Android.os.Binder implements Ibookmanager, The Querylocalinterface method is derived from super-class Android.os.Binder. For the descriptor passed in the method, the code known by Asinterface is the descriptor defined in the stub, and the Mdescriptor defined in the binder is assigned in the Attachinterface function. The Attachinterface function is called in the stub constructor, and its invocation is

This.attachinterface (this, descriptor);

And the call in Onserviceconnected is:

Mservice = IBookManager.Stub.asInterface (service);

Note that Sercice is ibookmanager.stub, so we can know that

If (mdescriptor.equals (descriptor))

The Mdescriptor and descriptor in the judgment statement are all descriptor defined in Ibookmanager.stub, and Querylocalinterface is returned. So what is mower? Careful children's shoes are estimated to know the answer, in the stub constructor call in Attachinterface, has been assigned to mower, and assigned to this, that the stub object itself! And then go back to the logic of Asinterface, we can conclude that the same process, call Asinterface returned is the stub object, is actually the Mbinder returned in Onbind.

To analyze the case of cross-process calls

As the above log shows, when cross-process calls are made, The service received in onsericeconnected is Android.os.BinderProxy type, and the above source code is given, Binderproxy is the final class, and its Querylocalinterface method directly returns NULL, combined with a Sinterface The code logic, it is known that it returns the IBookManager.Stub.Proxy object, and concludes that when the same process is called, Asinterface returns the Stub.proxy object.

At this point, the questions mentioned at the outset should be clear. But it raises a new question: Why is the Os.binderproxy received in onserviceconnected when the cross-process is tuned, and Ibookmanager.stub is received when the same process is called?

And listen to the next ...

Analysis of Asinterface in binder

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.