"Turn" in-depth understanding of Android StartService and bindservice--good

Source: Internet
Author: User

Original URL: http://www.cnblogs.com/yejiurui/p/3429451.html

first, let us confirm what is the service?
Service is the services in the Android system, it has a few features: it can not interact directly with the user, it must be explicitly launched by the user or other programs, it has a higher priority, it is lower than the application in the foreground, but higher priority than other applications in the background, This determines that when the system destroys certain underutilized resources because of lack of memory, it is less likely to be destroyed.
second, so, when, we need to use the service?
We know that service is an application running in the background, and for users it loses the focus of attention. After we opened the music, we wanted to look at the pictures, we didn't want the music to stop, we used the service here, for example, after we opened a download link, we certainly didn't want to stare and wait for him to finish downloading and then do something else, right? At this time if we want to download the phone in the background, while you can let me go to see the news, it is necessary to use the service.
Third, service classification:
Generally we think that service is divided into two categories,Local ServiceAndremote service.
Local service as the name implies, that is, and the current application in the same process of service, each other has a common memory area, so for some data sharing is particularly convenient and simple;
Remote service:mainly involved in service access between different processes。 Because of the security of Android system, we cannot share data in a common way between different processes. Here Android provides us with aa aidl tool。 (Android Interface Description Language) Android Interface Description Language. We will introduce them in detail in the rear.
Iv. service life cycle:
Compared to the activity, the service life cycle is simply no longer simple, onlyonCreate ()->onstart ()->ondestroy ( )Three methods.
Activity and service-related methods:
StartService (Intent Intent): Start a service
StopService (Intent Intent): Stop a service
If we want to usesome of the data in the service, or access some of the methods, then we'll go through the following method:
public boolean Bindservice (Intent Intent, serviceconnection conn, int flags);
public void Unbindservice (Serviceconnection conn);
Intent is the Intent that jumps to the service, such as Intent Intent = new Intent (); Intent.setclass (This,myservice.class);
Conn is a class that represents a connection state to a service, and when we connect to a service that succeeds or fails, it actively triggers its internalonserviceconnectedOronservicedisconnectedMethod. If we want to access the data in the service, it can be implemented in the onserviceconnected () method,

steps to use the service:
The first step: We want to inherit the service class and implement our own service.
If you want to access some of the values in the service, we usually provide an inner class that inherits the binder, which is returned to the service request through the Onbund () method. This is actually a clever use of the intrinsic nature of the inner class to access the attributes of the outer class.
Step Two: Register in Androidmanifest.xml, such as:
<!--service configuration starts--
<service android:name= "MyService" ></service>
<!--service configuration ends-
Step Three: Start, bind, unbind, or stop the service in activity.
(Many books say that the service and the user are not interactive, in fact, this is not true, we can fully interact with the service through activity!) I think the exact argument should be that the service cannot interact directly with the user.

-----------------------------

Bindservice Introduction

I. Introduction of Bindservice

Bindservice is the binding service services that perform logical processes in service services.

The service starts with the Context.startservice () method, stops through the Context.stopservice () method, or through the service.stopself () method or Service.stopselfresult () method to stop yourself. The service can be stopped whenever the StopService () method is called, regardless of how many times it was called before the service method was started.

The client establishes a connection to the service and uses this connection to make a call to the service, using the Context.bindservice () method to bind the services, Context.unbindservice () method to shut down the service. Multiple clients can bind to the same service, and the Bindservice () method can start the service if it has not been started.

The above StartService () and Bindservice () two modes are completely independent. You can bind a service that has been started by the StartService () method. For example, a background play music service can play music through StartService (intend) objects. It is possible for the user to perform some action during playback, such as getting some information about the song, at which time the activity can establish a connection to the service by calling the Bindservices () method. In this case, the Stopservices () method does not actually stop the service until the last bind is closed.

If no program stops it or it stops itself, the service runs all the time. In this mode, the service starts at Call Context.startservice () and stops at Context.stopservice (). The service can stop itself by calling Android service life cycle () or Service.stopselfresult (). No matter how many times startservice () is called, you can stop the service by calling only one StopService ().

Can be called by an external program through an interface. The external program establishes a connection to the service and operates the service through a connection. Establish the connection adjustment starts at Context.bindservice () and ends at Context.unbindservice (). Multiple clients can bind to the same service, and if the service does not start, Bindservice () can choose to start it.

These 2 modes are not completely detached. You can bind to a service that starts with StartService (). If a intent wants to play music, start the service of playing music in the background through the StartService () method. Then, perhaps the user wants to manipulate the player or get information about the currently playing song, an activity will establish a connection to the service through Bindservice (). In this case, StopService () will not actually stop the service until all the connections have been closed.

Second, Bindservice START process

Context.bindservice ()-onCreate ()-Onbind ()-Service running--> Onunbind ()--OnDestroy () -Service Stop

Onbind () returns a Ibind interface instance to the client, Ibind a method that allows the client to callback the service, such as getting an instance of the services, running state, or other operations. This time the caller (context, for example, activity) is bound together with the service, the context exits, Srevice will call Onunbind->ondestroy exit accordingly.

So the lifetime of the call Bindservice is: onCreate---Onbind (one time, not multiple bindings)--onunbind--and ondestory.

only OnStart can be called multiple times (via multiple StartService calls) during each turn-off of the service, other Oncreate,onbind,onunbind, Ondestory can only be called once in a life cycle.

Three, Bindservice life cycle

Like an activity, a service has some life-cycle methods that can be used to change the state, but less than the activity approach, and the service life-cycle approach has only three public

void OnCreate ()

void OnStart (Intent Intent)

void OnDestroy ()

By implementing these three lifecycle methods, you can listen to the lifecycle of two nested loops of a service:

1, the entire life cycle

The entire life cycle of the service is between the OnCreate () and the OnDestroy () methods. As with activity, initialize in the OnCreate () method and release resources in the OnDestroy () method. For example, a background music playback service can be played in the OnCreate () method and stopped in the OnDestroy () method.

2, the life cycle of the activity

The service's activity life cycle is after OnStart (), which handles intent objects passed through the Startservices () method. The music service can find the music to play by opening the intent object, and then start the background playback. Note: There is no corresponding callback method when the service is stopped, that is, there is no OnStop () method, only the OnDestroy () method is destroyed.

The onCreate () method and the OnDestroy () method are for all services, regardless of whether they start, through Context.startservice () and Context.bindservice () Method can access execution. However, the OnStart () method is called only when the service services are started by the StartService () method .

If a service allows others to bind, then the following additional methods need to be implemented:

IBinder Onbind (Intent Intent)

Boolean onunbind (Intent Intent)

void Onrebind (Intent Intent)

The Onbind () callback method will continue to pass the intent object passed through Bindservice ().

Onunbind () Handles the intent object that is passed to Unbindservice (). If the service allows binding, Onbind () returns the communication handle (instance) that the client is contacting with the service.

If a new client-to-service connection is established, the Onunbind () method can request a call to the Onrebind () method.

Remember: any service regardless of how it is established, the default client can be connected, so any service can receive the Onbind () and the Onunbind () method

Iv. examples of Bindservice and StartService

(1) mainactivity

public class Mainactivity extends Activity {button startservicebutton;//start service button buttons shutdownservicebutton;//off        Button startbindservicebutton;//start the Bind service button @Override protected void OnCreate (Bundle savedinstancestate) {        Super.oncreate (savedinstancestate);                Setcontentview (R.layout.activity_main);        Getwidget ();    Regiestlistener ();        }/** Gets the component */public void Getwidget () {Startservicebutton = (Button) Findviewbyid (R.id.startserverbutton);        Startbindservicebutton = (Button) Findviewbyid (R.id.startbindserverbutton);    Shutdownservicebutton = (Button) Findviewbyid (R.id.sutdownserverbutton);        }/** Add Listener for button */public void Regiestlistener () {Startservicebutton.setonclicklistener (StartService);        Shutdownservicebutton.setonclicklistener (Shutdownservice);    Startbindservicebutton.setonclicklistener (Startbinderservice); }/** event listener for start service */public Button.onclicklistener StartservIce = new Button.onclicklistener () {public void OnClick (view view) {/** Start the service when the button is clicked */Intent            Intent = new Intent (mainactivity.this, countservice.class);                        StartService (Intent);        LOG.V ("Mainstadyservics", "Start Service");    }    }; /** Close Service */public Button.onclicklistener shutdownservice = new Button.onclicklistener () {public void OnClick (V Iew view) {/** Start service when the button is clicked */Intent Intent = new Intent (Mainactivity.this, CountS            Ervice.class);            /** exit activity Yes, stop service */stopservice (intent);        LOG.V ("Mainstadyservics", "ShutDown Serveice");    }    }; /** Open BIND Service activity */public Button.onclicklistener startbinderservice = new Button.onclicklistener () {public void OnClick (view view) {/** Start service when the button is clicked */Intent Intent = new Intent (Mainactivity.this, USEBRIDER.C            LASS); StartActivity (iNtent);        LOG.V ("Mainstadyservics", "Start Binder Service");    }    };  @Override public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu, this adds items to the action Bar        If it is present.        Getmenuinflater (). Inflate (R.menu.main, menu);    return true; }

(2) Service

Package com.example.testservice;/** introduces class import Android.os.ibinder;import for packet */import android.app.service;//Services Android.os.binder;import android.content.intent;import android.util.log;/** Count Service */public class CountService extends    Service {/** Create parameter */Boolean threaddisable;    int count;    Public IBinder Onbind (Intent Intent) {return null;        } public void OnCreate () {super.oncreate (); /** creates a thread, a counter plus one per second, and a log output in the console */new Thread (new Runnable () {public void run () { (!threaddisable)                    {try {thread.sleep (1000);                    } catch (Interruptedexception e) {} count++;                LOG.V ("Countservice", "Count is" + count);    }}). Start ();        } public void OnDestroy () {Super.ondestroy ();    When the/** service stops, the count process is terminated */this.threaddisable = true;       } public int Getconunt () { return count;  }//This method is for instances where the service can be obtained in acitity   
Class Servicebinder extends Binder {public        countservice GetService () {            return countservice.this;}}    }

(3) Bindservice (be sure to remember that this is the object to get, link to)

Package com.example.testservice;/** Introduction Pack */import android.app.activity;import Android.content.componentname;import Android.content.context;import Android.content.intent;import Android.content.serviceconnection;import Android.os.bundle;import android.os.ibinder;import android.util.log;/** start and end services by Bindservice and Unbindserivce */    public class Usebrider extends Activity {/** parameter settings */Countservice countservice;        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                Setcontentview (New Usebriderface (this));        Intent Intent = new Intent (usebrider.this, Countservice.class);    /** Enter Activity start service */Bindservice (Intent, Conn, context.bind_auto_create); } private Serviceconnection conn = new Serviceconnection () {/** operation when getting service object */public void ONSERVICEC onnected (componentname name, IBinder service) {//TODO auto-generated method Stub countservice = (( countservice.seRvicebinder) service). GetService (); /** cannot get Action on service object */public void onservicedisconnected (componentname name) {//TODO Auto-gener        ated method Stub countservice = null;    }    };        protected void OnDestroy () {Super.ondestroy ();        This.unbindservice (conn);    LOG.V ("Mainstadyservics", "out"); }}

Note: This place has friends that may appear onserviceconnected do not invoke the situation.

The problem is that when the Bindservice method is called, the activity's onserviceconnected is recalled, and in this method a IBinder instance is passed to the activity, acitity need to save the instance

In the service, you need to create an inner class that implements IBinder (this inner class is not necessarily implemented in service, but must be created in the service).

You need to return an IBinder instance in the Onbind () method, otherwise the Onserviceconnected method will not be called.

However, I am able to pass null here can also be called, we judge according to the situation, if it is to return a IBinder instance, the sample code is as follows:

Public IBinder Onbind (Intent Intent) {        //TODO auto-generated method stub        System.out.println ("Onbind ...");         IBinder result = null;              if (null = = result) result = new Mybinder ();        Toast.maketext (This, "Onbind", Toast.length_long);        return result;    }

"Turn" in-depth understanding of Android StartService and bindservice--good

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.