Android four components (ii) Service usage

Source: Internet
Author: User

A. Service Introduction

Service is one of Android's four components and is often used in many places. There are two different ways to open a service: StartService and Bindservice. Different ways of opening, service execution life cycle methods are also different.

Sub-display/implicit invocation, but the official website recommends an explicit way to start the service. The following service is used to display the call, note that the implicit call, the implicit call on the 5.0 system will be an error. So here only the use of display calls is described.

No more time-consuming operation in the service, or ANR; a child thread is required to process the time-consuming operation.

Two. Service is used with 1.startService.
Intent Intent = new Intent (this, testservice.class);
LOG.W (Tag, "activity==== Start-up service");
StartService (Intent);

Execution effect:

LOG.W (Tag, "activity==== stop Service"); StopService (intent);

Execution effect:

2.bindService bindings.
Private class MyConnection implements Serviceconnection {        @Override public        void onserviceconnected ( ComponentName name, IBinder service) {            //only if we write our own MyService Onbind method return value is not NULL, it will be called            LOG.E ("Call", " Onserviceconnected ");        }        @Override public        void onservicedisconnected (componentname name) {            //This method is only called when an exception occurs, and the server exits normally without calling.            log.e ("Call", "onservicedisconnected");        }    }

LOG.W (Tag, "activity==== binding service");
MyConnection conn = new myconnection ();//First parameter: Intent intent//second parameter: is an interface that receives a service open or stopped message via this interface, and this parameter cannot be null// The third parameter: operation when the service is turned on, Bind_auto_create representative automatically creates service Bindservice (service, Conn, bind_auto_create); Bindservice (Intent, Conn, bind_auto_create);

Execution effect:

LOG.W (Tag, "activity====-binding service");
Unbindservice (conn);

Execution effect:

 

3. Difference:

following from the network, subsequent validation :

The service cannot run itself and needs to start the service by calling the Context.startservice () or Context.bindservice () method. Both of these methods can start the service, but they are used in different situations.

The service is enabled with the StartService () method, the caller is not connected to the service, and the service is still running even if the caller exits. Using the Bindservice () method to enable the service, the caller and the service are bound together, and once the caller exits, the service terminates, and there is a "no need to live at the same time Must Die" feature.

If you plan to start the service with the Context.startservice () method , the system calls the service's OnCreate () method first, and then calls the OnStart () method when the service is not created. If the StartService () method is called before the service has been created, calling the StartService () method multiple times does not cause the service to be created more than once, but results in multiple calls to the OnStart () method. Services started with the StartService () method can only call the Context.stopservice () method to end the service, and the OnDestroy () method is called at the end of the service.

If you plan to start the service with the Context.bindservice () method , the system calls the service's OnCreate () method first, and then calls the Onbind () method when the service is not created. This time the caller and the service are bound together and the caller exits, the system calls the service's Onunbind () method first, and then calls the OnDestroy () method. If the service is already bound before the Bindservice () method is called, multiple calls to the Bindservice () method do not cause the service and bindings to be created multiple times (that is, the OnCreate () and Onbind () methods are not called multiple times). If the caller wants to unbind the service being bound, it can call the Unbindservice () method, and calling the method will also cause the system to invoke the service's Onunbind ()-->ondestroy () method.

Three. Service Considerations:

Use the following method on the 5.0 system when start or bind starts the service:

Intent Intent = new Intent ();  Intent.setaction ("Com.example.user.firstapp.FIRST_SERVICE"); Bindservice (intent,coon,service.bind_auto_create);

StartService (Intent);

  

On Android 5.0, error:Illegalargumentexception:service Intent must be explicit

The reason is: Android5.0 in the service intent must be explicit declaration !!!

Four. Attach the core activity code:
Package Com.example.hp.testapp;import Android.content.componentname;import Android.content.intent;import Android.content.serviceconnection;import Android.os.ibinder;import android.support.v7.app.AppCompatActivity; Import Android.os.bundle;import android.util.log;import Android.view.view;import Android.widget.textview;import Com.example.hp.testapp.service.testservice;import Org.w3c.dom.text;public class Mainactivity extends    Appcompatactivity implements View.onclicklistener {private String Tag = "Testservicetag";    Private TextView Tv_btn_start;    Private TextView tv_btn_stop;    Private TextView Tv_btn_bind;    Private TextView Tv_btn_unbind;    Intent Intent;    MyConnection Conn;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Intent = new Intent (this, testservice.class);        conn = new myconnection ();        Initview ();    Initlistener (); } Private VOID Initview () {Tv_btn_start = (TextView) Findviewbyid (R.id.tv_btn_start);        Tv_btn_stop = (TextView) Findviewbyid (r.id.tv_btn_stop);        Tv_btn_bind = (TextView) Findviewbyid (R.id.tv_btn_bind);    Tv_btn_unbind = (TextView) Findviewbyid (R.id.tv_btn_unbind);        } private void Initlistener () {Tv_btn_start.setonclicklistener (this);        Tv_btn_stop.setonclicklistener (this);        Tv_btn_bind.setonclicklistener (this);    Tv_btn_unbind.setonclicklistener (this);                } @Override public void OnClick (view view) {switch (View.getid ()) {r.id.tv_btn_start:                /** * Start Service */LOG.W (Tag, "activity==== start Service");                StartService (Intent);            Break Case R.ID.TV_BTN_STOP:/** * Stop service */LOG.W (Tag, "activity===                = Stop Service ");                StopService (Intent);            Break CaSE r.id.tv_btn_bind:/** * Binding Service */LOG.W (Tag, "activity==== tied                Service "); First parameter: Intent intent//second parameter: is an interface that receives a service open or stopped message via this interface, and this parameter cannot be NULL//third parameter: operation when the service is opened, Bind_aut                O_create representative automatically creates service Bindservice (service, Conn, bind_auto_create);                Bindservice (Intent, Conn, bind_auto_create);            Break Case R.id.tv_btn_unbind:/** * Unbind service */LOG.W (Tag, "activity=                = = = Unbind Service ");                IF (conn! = null) {unbindservice (conn);        } Default:break;        }} @Override protected void OnStart () {LOG.W (Tag, "Activity====onstart");    Super.onstart ();        } @Override protected void Onrestart () {LOG.W (Tag, "Activity====onrestart");    Super.onrestart (); } @Override public void onstatenotsaved () {Log. W (Tag, "activity====onstatenotsaved");    Super.onstatenotsaved ();        } @Override protected void Onresume () {LOG.W (Tag, "Activity====onresume");    Super.onresume ();        } @Override protected void OnPause () {LOG.W (Tag, "activity====onpause");    Super.onpause ();        } @Override protected void OnStop () {LOG.W (Tag, "activity====onstop");    Super.onstop ();        } @Override protected void OnDestroy () {LOG.W (Tag, "Activity====ondestroy");    Super.ondestroy (); } Private class MyConnection implements Serviceconnection {@Override public void onserviceconnected (Comp Onentname name, IBinder service) {//only if we write our own MyService Onbind method return value is not NULL, it will be called LOG.E ("call", "onSe        Rviceconnected "); } @Override public void onservicedisconnected (componentname name) {//This method is only called when an exception occurs, and the server exits normally without            Use.        LOG.E ("Call", "onservicedisconnected"); }    }}

  

Android four components (ii) Service usage

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.