Service of Android four components (ii)

Source: Internet
Author: User

Here we mainly describe the use of service components.

1. Define a subclass that inherits the service

As follows:

Package Com.service;import Android.app.service;import Android.content.intent;import Android.os.ibinder;public class       Defaultservice extends Service {int mstartmode;      Indicates how to behave if the service is killed IBinder Mbinder; Interface for clients this bind Boolean mallowrebind; Indicates whether Onrebind should be used @Override public void onCreate () {//The service is being creat ED} @Override public int onstartcommand (Intent Intent, int flags, int. Startid) {//the service is Starti    Ng, due to a call to StartService () return mstartmode;        } @Override Public IBinder onbind (Intent Intent) {//A client are binding to the service with Bindservice ()    return mbinder;        } @Override public boolean onunbind (Intent Intent) {//All clients has unbound with Unbindservice ()    return mallowrebind; } @Override public void Onrebind (Intent Intent) {//A client is binding to The service with Bindservice (),//After Onunbind () have already been called} @Override public void Onde Stroy () {//The service is no longer used and is being destroyed}}

2. Configure the service with the <service> tag in Androidmanifest.xml

<service android:name= "Com.service.defaultService" >             <intent-filter>                         <action android:name= "Com.service.dService"/>             </intent-filter> </service>

Note: The first name is the location of the service, including the full package name and service name. If the package name is the name of the package that you defined, that is, the name of the package under the Gen directory, the direct ". Service name" is available. The second name is Intent.setaction () in the call service, which can be used as a parameter.

3. The following life cycle methods are defined in the service:

[1] ibinder onbind (Intent Intent): This method is a method that the service subclass must implement, which returns a IBinder object that the application can use to communicate with the service component;

[2] void OnCreate (): callback the service component as soon as it is created for the first time;

[3]void OnDestroy (): callback The method before the service is closed;

[4]void onstartcommand (Intent intent,int flags,int startid): Earlier versions of the method were OnStart (Intent intent,int Startid), The method is called back each time the client calls the StartService () method to start the service;

[5]boolean onunbind (Intent Intent): This method is called when all clients bound by the service are disconnected

When other components start the service through the Context.startservice () method, a service object is created and the OnCreate () method and the Onstartcommand () method are called sequentially. The service is in a running state until Context.stopservice () or stopself () is called. If you call the StartService () method multiple times, the system will only call the Onstartcommand () method multiple times and will not call the OnCreate () method repeatedly. No matter how many times the StartService () method is called, you can stop the service by simply calling the StopService () method once. The OnDestroy () method is called before the service object is destroyed, so the work related to resource deallocation should be done in this method.

3, the service start stop

[1] Way one:

When a program starts and stops service () through the StartService () method and the StopService () method, there is essentially no association between the service and the visitor, so communication and data exchange between the service and the visitor is not possible.

[2] The way two:

Start, stop service () with the Bindservice () and the Unbindservice () method.

4, the way two detailed

Bindservice (Intent serivce,serviceconnection connection,int Flags) method start:

[1] The first parameter specifies the service to be started by intent;

[2] The second parameter is used to listen to the connection between the visitor and the service;

The Serviceconnection object is used to listen to the connection between the visitor and the service, and when the connection between the visitor and the service succeeds, the onserviceconnected of the Serviceconnection object is recalled ( ComponentName Name,ibinder Service) method, when the service is in a process that terminates abnormally or for other reasons, causes the service to be disconnected from the visitor. The onservicedisconnected (componentname name) method of the Serviceconnection object will be recalled (when the Unbindservice () method is actively invoked to break the connection to the service, The callback method is not called).

Notice that there is a IBinder object in the onserviceconnected (componentname Name,ibinder Service) method of the Serviceconnection object, The object is the communication between the implemented and the service being bound.

[3] The third parameter specifies whether the service is automatically created when binding (if the service has not yet been created). This parameter can be specified as 0 (not created automatically) or bind_auto_create (automatically created).

5. IBinder Onbind (Intent Intent) method must be provided when developing service class

In the case of binding the ground service, the IBinder object returned by the Onbind (Intent Intent) method will be passed to Serviceconnection object onserviceconnected (componentname Name,ibinder Service) method to enable communication with the service.

In fact, development often implements its own IBinder objects in a way that inherits binders (IBinder implementation classes).

Package Com.service;import Android.app.service;import Android.content.intent;import android.os.binder;import  Android.os.ibinder;public class Bindservice extends service{private int count;  Identifies the running state of the service private Boolean quit;    Flag whether the service is closed//defines the object returned by the Onbind () method private DefaultBinder binder = new DefaultBinder ();            public class DefaultBinder extends Binder {public int getcount () {//Get service running Status: Count         return count;        }} @Override public IBinder onbind (Intent Intent) {System.out.println ("Service is binded!");    return binder;        //service is created when the method is called back @Override public void OnCreate () {super.oncreate ();        System.out.println ("Serivce is created!");                Starts a new thread, dynamically changes the count value new thread () {@Override public void run () { while (!quit) {try{Thread.Sleep (1000);                    } catch (Interruptedexception e) {e.printstacktrace ();                } count++;    }}}.start ();        }//service is closed before the callback method @Override public void OnDestroy () {Super.ondestroy ();        This.quit=true;    System.out.println ("Service is destroyed!");  The method is//service when disconnected @Override public boolean onunbind (Intent Intent) {System.out.println ("Service is        Unbinder ");    return true; }}

6. Next bind the service in an activity and access the internal state of the service through the DefaultBinder object in the activity.

[1] The layout file is as follows

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "     xmlns:tools=" Http://schemas.android.com/tools "     android:layout_width=" Match_parent     " android:layout_height= "Match_parent"     android:orientation= "vertical"     tools:context= ". Mainactivity ">    <button         android:id=" @+id/bind "         android:layout_width=" Match_parent         " android:layout_height= "Wrap_content"         android:text= "bind service"/>     <button         android:id= "@+id/ Unbind "         android:layout_width=" match_parent "         android:layout_height=" wrap_content "         android:text=" Unbind "/>     <button         android:id=" @+id/status "         android:layout_width=" Match_parent "         Android : layout_height= "wrap_content"         android:text= "Get Service status"/></linearlayout>

[2] The activity is as follows:

Package Com.myandroid;import Com.service.bindservice;import Android.app.activity;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 Serviceactivity extends activity{private Button    Bind,unbind,status;  Bindservice.defaultbinder Binder;         Maintains the IBinder object for the service being started//defines a Serviceconnection object private serviceconnection conn=new serviceconnection () { @Override public void onserviceconnected (componentname name, IBinder service) {System.ou            T.println ("Service connected!");        Gets the Mybinder object binder= (bindservice.defaultbinder) service returned by the Onbind () method of the service; } @Override public void onservicedisconnected (componentname name) {System.out.println ("Se Rvice Disconnected! ");};        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.service);        Get Interface button bind= (button) Findviewbyid (R.id.bind);        Unbind= (Button) Findviewbyid (R.id.unbind);        Status= (Button) Findviewbyid (r.id.status);        Create a Intent final Intent intent=new Intent () that initiates the service;        Intent.setclassname (This, "Nku.jerry.crazyit.crazyit_22.BindService");            Bind.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v)            {//Binding specified service Bindservice (intent,conn,bind_auto_create);        }        });            Unbind.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v)            {//Unbind service Unbindservice (conn);        }        }); Status.setoncliCklistener (New Onclicklistener () {@Override public void OnClick (View v) { Get Service status information Toast.maketext (serviceactivity.this, "service count value is:" +binder.getcount (), TOAST.L            Ength_long). Show ();    }        }); }}

Service of Android four components (ii)

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.