Android Learning Note 24. Getting Started with Service (ii) binding and communicating with the ground service

Source: Internet
Author: User
Tags call back

to bind and communicate with the service    In the first 3 steps of the previous blog post, we completed a service and an application that uses the service (the service is part of the application). However, when the program starts and shuts down the service through StartService () and StopService (), there is essentially no association between the service and the visitor, so there is no communication or data exchange between the service and the visitor. If we want toa method call or data exchange between a developed service and a visitor, we can let visitors use the Bindservice () and Unbindservice () methods to start and close the service, thus enabling the binding between the visitor and the local service. 1. Start the Service methodContext.bindservice (Intent service,serviceconnection conn,int flags)parameter Description:Service: This parameter is used to set which service the activity specifies to start through intent;Conn: This parameter is an Serviceconnection object that listens to the connection between the visitor and the service. When the connection between the visitor and the service succeeds, thecallback The onserviceconnected of the Serviceconnection object (componentname name,IBinder Service)Method; when The host process where the Service is located is terminated due to an abnormal abort or other reason . The onservicedisconnected (componentname name) method of the callback Serviceconnection object that causes the service to disconnect from the visitor . NOTE: When the caller actively disconnects from the service through the Unbindservice () method, the Serviceconnection object's onservicedisconnected (componentname name) method is not called. Flags: Specifies whether the service is automatically created when binding (if the service has not yet been created). Flags=0, not automatically created; flags=bind_auto_create, automatically created. 2. Source Code Analysis(1) in the service subclass, implement the IBinder class by inheriting binder and declare a IBinder object;(2) When the visitor binds the service, theservice returns a IBinder object to the visitor via the Onbind () method ;(3) in the visitor subclass, when the visitor connects with the service successfully the callback Serviceconnection object's onserviceconnected (componentname Name,ibinder Service) method is gets the Mybinder object returned by the service's Onbind method , which can access the service state data, which is the value of count. 3. Source Code Combat (1)/COm/exanple/android_service_bind/bindservice.java function: Implement a service subclass, and then implement a IBinder inner class and a thread
Package Com.example.android_service_bind;import Android.app.service;import Android.content.intent;import  Android.os.binder;import Android.os.ibinder;public class Bindservice extends Service {private int count; private Boolean Quit Private Myibinder binder=new Myibinder ();//Declare a IBinder object//1. Define a IBinder subclass and implement a method that gets the service run state (count) public class Myibinder extends Binder {public int getcount () {return count;//Return service Run state: Count}} A class that must be implemented by the//2.service subclass to return  IBinder Object Public IBinder onbind (Intent Intent) {System.out.println ("Service is binded!");  Return binder;//returns the IBinder object}//3.service is created when the callback method @Override public void OnCreate () {super.oncreate ();  System.out.println ("Service is Created.");     Create and start a thread that implements dynamic modification of the count status value New Thread () {@Override public void run () {while (!quit)//Identity service shutdown startup State {     try {thread.sleep (1000);    }catch (Interruptedexception e) {} count++; }}}.start (); The callback method @Override public boolean when//4.service is disconnected Onunbind (Intent Intent) {System.out.println ("Service is unbinded"); return true;  }//5.service is closed before the callback method @Override public void OnDestroy () {Super.ondestroy (); This.quit=true; When the method is called (!quit) is false, the thread ends System.out.println ("Service is Destroy"); }}
(2) Androidmanifest.xmlimplementation: Configure a service component for the service subclass and configure the action for the intent-filter of the service component
<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Com.example.android_service_bind "android:versioncode=" 1 "android:versionname=" 1.0 "> &lt ; USES-SDK android:minsdkversion= "8" android:targetsdkversion= "/> <application android:al" Lowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" android:theme= "@style/apptheme" > <activity android:name= ". Bindservicetest "android:label=" @string/app_name "> <intent-filter> <acti On android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNC  Her "/> </intent-filter> </activity> <!--Configuring a service component--<service Android:name= ". Bindservice "> <intent-filter> <!--for this service groupIntent-filter Configuration Action---<action android:name= "Com.example.service.BIND_SERVICE"/> </int Ent-filter> </service> </application></manifest>
(3)/COm/exanple/android_service_bind/bindservicetest.java implementation: Defines a Serviceconnection object that obtains the IBinder object returned by the service through the onserviceconnected () method of the object and specifies the service through intent object initiation and binding.
Package Com.example.android_service_bind;import Android.app.activity;import Android.app.service;import Android.content.componentname;import Android.content.intent;import Android.content.serviceconnection;import Android.os.bundle;import Android.os.ibinder;import Android.view.view;import Android.view.View.OnClickListener; Import Android.widget.button;import Android.widget.toast;public class Bindservicetest extends Activity {Button bind, Unbind,status; 1. Maintain the IBinder object of the service being started Bindservice.myibinder binder; 2. Define a Serviceconnection object private serviceconnection conn = new Serviceconnection () {// A. When the activity and service connection succeeds, callback the method @Override public void onserviceconnected (componentname name, IBinder service) {Sy   STEM.OUT.PRINTLN ("---Service is connected---");  Gets the Mybinder object binder= (bindservice.myibinder) service returned by the Onbind method of the service; //b. Callback this method when the activity and service connection is unsuccessful @Override public void onservicedisconnected (componentname name) {System.out.prin TLN ("---Service is DisconnecTed---"); } };  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);  Setcontentview (R.layout.main);  A. Get the start, stop, Getservicestatus button in the program interface bind = (Button) Findviewbyid (R.id.bind);  Unbind = (Button) Findviewbyid (R.id.unbind);  Status = (Button) Findviewbyid (r.id.getservicestatus);  B. Create Intent final Intent Intent = new Intent () to start the service;  Intent.setaction ("Com.example.service.BIND_SERVICE"); C. Binding Specifies service Bind.setonclicklistener (new Onclicklistener () {@Override public void OnClick (View v) {Bindservice   (intent,conn,service.bind_auto_create);  }  }); D. Unbind service Unbind.setonclicklistener (new Onclicklistener () {@Override public void OnClick (View v) {Unbindse   Rvice (conn);  }  }); E. Get the status of the service, display the service's count value Status.setonclicklistener (new Onclicklistener () {@Override public void OnClick (Vie W v) {toast.maketext (Bindservicetest.this, "The count value of the service is:" +binder.getcount (), toast.length_short). Show (); }  }); } }
(4) main interface layout/res/layout/main.xml
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:orientation= "vertical" Android:layout_width= "Match_parent" android:layout_height= "match_parent" > <linearlayout android:orientation         = "Horizontal" android:layout_width= "Match_parent" android:layout_height= "match_parent" > <Button Android:id= "@+id/bind" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" an droid:layout_weight= "1" android:text= "bind service"/> <button android:id= "@+id/unbind" and Roid:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:layout_weight= "1" an droid:text= "Unbind"/> <button android:id= "@+id/getservicestatus" android:layout_width= "Wrap_cont Ent "android:layout_height=" wrap_content "android:layout_weight=" 1 "android:text=" Get Status "/> &l T;/linearlayout></linearlayouT> 



Effect Demo :(1) When a service is clicked, the visitor invokes the Bindservice () method to start and bind to the specified service. Observe the logcat of DDMS:
(2) when clicked to get service status, the visitor gets the count value by invoking the GetCount () method of the service inner class Myibinder through the IBinder object binder;
(3) When you click Unbind, the Visitor serviceconnection the Unbindservice (conn) method to unbind a service, the system will first call back the service's Onunbind () method, Then callback the OnDestroy () method and the service is closed.
Note: The so-called service state is actually a thread (implemented in the service's OnCreate () method) that implements the count value to run in service services. When a visitor invokes the Bindservice () method to start and bind the service, the thread starts running and count keeps accumulating 1 until the visitor unlocks the service's bindings. sublimation notes: About IBinder objects? The IBinder object is equivalent to the internal hook of the service component, which is associated to the bound service component, and when other program components bind the service, the service subclass will ibinder the object and return it to the other program components .Other program components can communicate with service components in real time through the IBinder object. Birth: The service implements its own IBinder object using the method of inheriting binder (IBinder implementation Class),the IBinder object is returned by the IBinder Onbinder (Intent Intent) method provided by the service.whereabouts: When other program components call the onserviceconnected (componentname Name,ibinder Service) method of the Serviceconnection object, The IBinder object returned by the incoming service component enables communication between other program components and the service being bound.
Reference: Http://wear.techbrood.com/reference/android/app/Service.html

Android Learning Note 24. Getting Started with Service (ii) binding and communicating with the ground service

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.