Android--Service bindings and Aidl

Source: Internet
Author: User

Service is one of the four main components of Android, previously on the service life cycle, as well as examples of the life cycle of unbound types, this time to share the binding form.

The application component (client) can call Bindservice () to bind to a service. The Android system then calls the service's Onbind () method, which returns a ibinder that is used to interact with the service.

The binding is asynchronous, and Bindservice () returns immediately, and it does not return IBinder to the client. To receive IBinder, the client must create an instance of Serviceconnection and pass it to Bindservice (). The serviceconnection contains a callback method that is called by the system to pass the IBinder to be returned.

    • Implement Serviceconnection

The implementation must override the two callback methods:

Onserviceconnected ()

The system calls this to transmit the IBinder returned in the service's Onbind ().

Onservicedisconnected ()

The Android system calls this when the connection to the service is accidentally lost. For example, when the service crashes or is strongly killed. This method is not invoked when the client is unbound.

  • Call Bindservice () and pass it to the serviceconnection implementation.

  • When the system calls your onserviceconnected () method, you can start invoking the service using the method of the interface definition.

  • To disconnect from the service, call Unbindservice ().

  • Program

     Public classMainactivityextendsActivity {PrivateButton Btn_start; PrivateButton Btn_stop; PrivateButton Btn_change; PrivateButton Btn_bind; PrivateButton Btn_unbind; Privatemyconn myconn; PrivateIService Mybinder; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Btn_start=(Button) Findviewbyid (R.id.btn_start); Btn_stop=(Button) Findviewbyid (r.id.btn_stop); Btn_change=(Button) Findviewbyid (R.id.btn_change); Btn_bind=(Button) Findviewbyid (R.id.btn_bind); Btn_unbind=(Button) Findviewbyid (R.id.btn_unbind); Buttonlistener BL=NewButtonlistener ();        Btn_change.setonclicklistener (BL);        Btn_start.setonclicklistener (BL);        Btn_stop.setonclicklistener (BL);        Btn_bind.setonclicklistener (BL);            Btn_unbind.setonclicklistener (BL); }    classButtonlistenerImplementsOnclicklistener {@Override Public voidOnClick (View v) {Switch(V.getid ()) { Caser.id.btn_start:intent Intent_start=NewIntent (Getapplicationcontext (), Bindservice.class);                StartService (Intent_start);  Break;  Caser.id.btn_stop:intent intent_stop=NewIntent (Getapplicationcontext (), Bindservice.class);                StopService (Intent_stop);  Break;  CaseR.id.btn_change:if(Mybinder! =NULL) Mybinder.dochange ("La La la");  Break;  CaseR.id.btn_bind:if(myconn = =NULL) {myconn=Newmyconn (); Intent Intent_bind=NewIntent (Getapplicationcontext (), Bindservice.class);                Bindservice (Intent_bind, myconn, bind_auto_create); }                 Break;  Caser.id.btn_unbind:intent Intent_unbind=NewIntent (Getapplicationcontext (), Bindservice.class); if(MyConn! =NULL&& Mybinder! =NULL) {unbindservice (myconn); MyConn=NULL; Mybinder=NULL; }                 Break; default:                 Break; }        }    }        Private classMyConnImplementsserviceconnection {@Override Public voidonserviceconnected (componentname name, IBinder service) {System.out.println ("The agent is back, onserviceconnected."); Mybinder=(iservice) service; } @Override Public voidonservicedisconnected (componentname name) {System.out.println ("Contact binding, onservicedisconnected."); }            }        }

    Service class:

     Public classBindserviceextendsService {@Override Publicibinder onbind (Intent Intent) {System.out.println ("Service binding succeeded, Onbind"); //returns a custom proxy object        return NewMybinder ();//here the return is returned to the mainactivity inside the binding myconn} @Override Public BooleanOnunbind (Intent Intent) {System.out.println ("Service Unbind succeeded, Onunbind"); return Super. Onunbind (Intent); }     Public classMybinderextendsBinderImplementsIService {//indirect use of proxies to invoke the Changeservicething method         Public voidDochange (String) {changeservicething (what); }} @Override Public voidonCreate () {System.out.println ("Service Open, OnCreate"); Super. OnCreate (); } @Override Public voidOnDestroy () {System.out.println ("Service off, OnDestroy"); Super. OnDestroy (); }         Public voidchangeservicething (String) {Toast.maketext (Getapplicationcontext (), what+ "Transformed, changeservicething", Toast.length_long). Show (); }        }

    IService:

     Public Interface IService {    publicvoid  Dochange (String of what);}

    Results

    After clicking "Open Service" and then "bind service", it is useless to "close the service" after executing it, first "release service" and then "close service". If you directly "bind the service", then click "Close Service" is not used, you need to click "Unbind Service".

    Aidl

    interprocess communication--caller and service if not within a process, you need to use the remote service invocation mechanism in Android.

    Android uses aidl to define communication interfaces between processes. The syntax of AIDL is similar to the Java interface, with the following points to note:

      • The Aidl file must have a. aidl as the suffix name.
      • The type of data used in the Aidl interface, except for the basic type, String, List, Map, charsequence, all other types require a guide package, even if both are within the same package. The element types in list and map must be types supported by Aidl.
      • The interface name needs to be the same as the file name.
      • When the parameter or return value of a method is a custom type, the custom type must implement the Parcelable interface.
      • All non-Java base type parameters need to be prefixed with in, out, inout to indicate whether the parameter is an input parameter, an output parameter, or an input/output parameter.
      • Access modifiers and static, final, and so on cannot be used before interfaces and methods.

    Interprocess communication requires the creation of a aidl file, Iservice.aidl:

     Public Interface IService {    publicvoid  Dochange (String of what);}

    The interface has a static abstract inner class Stub,stub class that inherits the Binder class and implements the Iremoteservice interface.

     Public classMainactivityextendsActivity {PrivateIntent Intent; PrivateIService IService; PrivateServiceconnection myconn; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);    Setcontentview (R.layout.activity_main); }     Public voidbind (view view) {Intent=NewIntent (); Intent.setaction ("Com.yydcdut.alipay"); MyConn=Newmyconn (); BooleanFlag =Bindservice (Intent, myconn, bind_auto_create); System.out.println ("Flag------>" +flag); }    Private classMyConnImplementsserviceconnection {@Override Public voidonserviceconnected (componentname name, IBinder service) {IService=IService.Stub.asInterface (service); } @Override Public voidonservicedisconnected (componentname name) {}} Public voidmethod (view view) {Try{iservice.callmethodinservice (); } Catch(RemoteException e) {//TODO Auto-generated catch blockE.printstacktrace (); }    }}

    I built two programs to achieve this, so that I could communicate between the two processes. comes with the source code.

    I'm the dividing line of the king of the Land Tiger.

    Source code: HTTP://PAN.BAIDU.COM/S/1DD1QX01

    Service Learning 2.zip

    Aidl Learning. zip

    Aidl Learning Package 2.zip

    Reprint Please specify source: Http://www.cnblogs.com/yydcdut

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.