Service of four components of Android development (example)

Source: Internet
Author: User

A detailed description of the service development has been in the previous article: Android development four components of the service (detailed article) is very clear, this article mainly on the service development examples to do the next explanation.

Program run:


Program code:

Bindservice:

Package Com.jph.servicedemo;import Android.app.service;import Android.content.intent;import android.os.Binder; Import android.os.ibinder;/** * describe:</br> * Service Subclass * Bindservice implements service and re-writes the parent class's * onbind, OnCreate, Methods such as OnDestroy, Onunbind * and OnDestroy. * and create and start a thread in the OnCreate method, dynamically modify the value of the count variable, * Create a subclass of binder LocalService class that is used as the return object of the callback method when the service is bound. * @author JPH * date:2014.07.21 * */public class Bindservice extends Service {private int count=0;private booleanisquit=f alse;//defines the object returned by the GetService method public LocalService localservice=new LocalService ();//Create Binder Subclass public class LocalService Extends Binder{public int GetCount () {return count;} Public Bindservice GetService () {return bindservice.this;}} The service subclass must implement a method that binds the service when the callback method @overridepublic IBinder onbind (Intent Intent) {//TODO auto-generated Stubreturn LocalService;} Service is created to call the method @overridepublic void OnCreate () {//TODO auto-generated method StubSystem.out.println ("service is Created. "); /create and start a thread, dynamically modify the value of the count variable new THread () {@Overridepublic void Run () {//TODO auto-generated method Stubwhile (!isquit) {try {thread.sleep (1000);// Causes the current thread to hibernate 1000 milliseconds} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} count++;}}}. Start (); Super.oncreate ();} Call @overridepublic void OnDestroy () {//TODO auto-generated method StubSystem.out.println ("Service is" after all Onunbind are recalled) Destroyed. "); Isquit=true;super.ondestroy ();} Defines a method that returns the name of the instance public String Getdemoname () {return "service instance";} Callback @overridepublic Boolean onunbind (Intent Intent) {//TODO auto-generated method after all service bound clients are unbound) StubSystem.out.println ("Service is Unbind."); Return true;//indicates that the next client binding will accept a onrebind () call (instead of calling Onbind ())}}
Servicedemo:

Package Com.jph.servicedemo;import Com.jph.servicedemo.bindservice.localservice;import Android.os.Bundle;import Android.os.ibinder;import Android.app.activity;import Android.content.componentname;import android.content.Intent ; import Android.content.serviceconnection;import Android.view.view;import android.view.View.OnClickListener; Import Android.widget.button;import android.widget.toast;/** * describe:</br> * Service Instance * This example simply implements the binding service and communicates with it * @author JPH * date:2014.07.21 * */public class Servicedemo extends Activity {Button btnbind,btn Unbind,btngetservicestatus; Bindservice Bindservice; LocalService Localservice;private boolean isbind=false, @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (R.layout.main); btnbind= (Button) Findviewbyid (R.id.btnBind); btnunbind= (Button) Findviewbyid (r.id.btnunbind); btngetservicestatus= (button) Findviewbyid ( R.id.btngetservicestatus); Onclicklistener listener=new Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method Stubswitch (V.getid ()) {case R.id.btnbind://intent intent=new in Tent ();//intent.setaction ("Com.jph.servicedemo.BIND_SERVICE"); Implicit startup Serviceintent intent=new Intent (Servicedemo.this,bindservice.class);//display start service//binding specified Servicebindservice (Intent, serviceconnection, bind_auto_create); Isbind=true;break;case r.id.btnunbind:if (Isbind) {// Unbind Serviceunbindservice (serviceconnection); isbind=false;bindservice=null; Toast.maketext (Servicedemo.this, "--service is unbind.--", Toast.length_long). Show (); else {toast.maketext (servicedemo.this, "-you have not yet bound service--", Toast.length_long). Show (); Break;case R.id.btngetservicestatus:if (bindservice==null) {Toast.maketext (servicedemo.this, "Please bind service first", Toast.length_long). Show ();} else {toast.maketext (servicedemo.this, "App Name:" +bindservice.getdemoname () + "\ n count:" +localservice.getcount (), Toast.length_long). Show ();} break;}}; Btnbind.setonclicklistener (listener); Btngetservicestatus.setonclicklistener (listener); Btnunbind.setonclicklistener (listener);} Define a Serviceconnection object private serviceconnection serviceconnection=new serviceconnection () {// callback method when activity and service connection succeeds @overridepublic void onservicedisconnected (componentname name) {//TODO auto-generated Method Stubbindservice=null; Toast.maketext (Servicedemo.this, "--service unconnected.--", Toast.length_long). Show (); Callback the method @overridepublic void onserviceconnected (componentname name, IBinder when the activity is disconnected from the service through the non-Unbind () method) Service) {//TODO auto-generated method stub//Gets the Bindservice object returned by the GetService () method Localservice= ((LocalService) service); Bindservice=localservice.getservice (); Toast.maketext (Servicedemo.this, "--service connected.--", Toast.length_long). Show (); System.out.println ("--service connected.--");}; }

Androidmanifest.xml:

<!--Configure a service component--><service android:name= ". Bindservice "><intent-filter><!--Configure the Intent-filter for the service component with action---                <action Android:name = "Com.jph.servicedemo.BIND_SERVICE" ></action>            </intent-filter>                    </service>
Example Analysis:

The output is shown by the Logcat of the DDMS:

If the user clicks the " Bind service" button on the program interface, they see the "service is Created" shown. With the output of "--service connected.--". When the service is bound in the activity, the activity can also get the running state of the service through the LocalService object, if the user clicks on the program interface Get the Service status button to see a popup message from the program interface. If we click the Unbind button, we can see the logcat in the

Output information: "service is Unbind.", "service is destroyed." When the program calls the Ubbindservice () method to dismiss a Service binding, the system will first callback the service's Ubbindservice () method and then callback the ondestory () method, which validates the OnDestroy () is the last callback method in the service life cycle.

Unlike multiple calls to the startservice() method to start a service, multiple calls to the Bindservice () method do not duplicate the binding. In this instance, the system will only callback the service's onbind() method once, regardless of the number of times the user clicks Bind service.

Service of four components of Android development (example)

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.