Service parsing of Android components

Source: Internet
Author: User

Original articles, reproduced please specify http://blog.csdn.net/leejizhou/article/details/50866875 Li Zizhou Blog

Service is one of the four components of Android. Service is mainly in the background, can do some background operations, it does not have a real user interface. It is similar to activity, and in a sense it can be understood as "service is an activity with no real user interface", so when do we need to use the service? For example: Music app is playing music we want to switch to the reading app and don't want to let the music stop will use the service, music app is downloading music we switch to the desktop and do not want to stop the download will be used to the service.

Writing an activity requires two steps: 1: Writing activity Subclass 2: Configuring this activity in Androidmanifest.xml requires two steps for the same authoring service:

1: Define a subclass that inherits from service
2: Configure this service in Androidmanifest.xml

StartService

Let's start by writing a simple StartService Demo sample program to demonstrate how to implement Android background operations
Define a subclass of the service and then make some life-cycle functions

/** * Blog:http://blog.csdn.net/leejizhou * Li Zizhou's Blog * * Public  class myservice extends Service {    the only abstract method in//service. Must be implemented in subclasses to communicate with the activity. return NULL first    @Nullable    @Override     PublicIBinderOnbind(Intent Intent) {return NULL; }some life cycle functions for the//Replication Service    The //oncreate will be called when the service is created for the first time    @Override     Public void onCreate() {Super. OnCreate (); LOG.D ("MyService","----onCreate executed----"); }//onstartcommand will be invoked every time the service is started.    @Override     Public int Onstartcommand(Intent Intent,intFlagsintStartid) {LOG.D ("MyService","----onstartcommand----");return Super. Onstartcommand (Intent, flags, Startid); }//ondestroy will be called when the service is destroyed    @Override     Public void OnDestroy() {Super. OnDestroy (); LOG.D ("MyService","----OnDestroy----"); }}

Here are the service life cycles, why are there two kinds of? Because there are two ways to start Servcie, the first is StartService () is used primarily to start a service running background task without communication, and the other is Bindservice () is to start a service that is bound to the component to communicate, The first introduction is StartService ().

This service is then configured in Androidmanifest.xml. Don't forget.

  <service android:name=".MyService"></service>

Once the service is defined, the next step is to start and stop it. Starting and stopping is largely achieved by intent, where I define two buttons to start and stop. Some of the code is slightly (the source code is provided at the end of the article), mainly the implementation code to start and stop the service.

 //Open serviceFindviewbyid (R.id.startservice). Setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {Intent intent=NewIntent (mainactivity. This, Myservice.class);            StartService (Intent); }        });//Stop serviceFindviewbyid (R.id.stopservice). Setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {Intent intent=NewIntent (mainactivity. This, Myservice.class);            StopService (Intent); }        });

Click on the service to see OnCreate and Onstartcommand are running, a simple backend service is started

then click Stop. Can see that OnDestroy is running.

You may be asked here. Start Service,oncreate and Onstartcommand are all running, what difference do they have? OnCreate will be called when the service is first created, assuming a service does not start the service again without a stop, the OnCreate method will not be called again, but each onstartcommand will be called. So the code logic that needs to run in the background we usually need to put in the Onstartcommand method.

Ok in the activity to start a simple service backend services is finished, but you have to know through StartService () to start the service after the activity is not related, Even if your activity is destroyed, the service will still run in the background. Remember to call StopService () in activity after the service task is started by StartService () to end this service. or call Stopself () in the Servcie subclass to end yourself.

The above describes the StartService startup service, it can be very simple to start the background service for some logical operation, but unable to control and communication, the following introduction Bindservice can solve the problem.

Bindservice

The following implements a background service for numeric increment operations. Activity can see a small demo sample of the value of the service at this time to understand the use of bindservice.

Define the service. Here we are going to implement the Onbind method. There is no need to onstartcommand here, because the service is not callback because it is started by Bindservice. The service's oncreate inside a cyclic numerical operation.

/** * Blog:http://blog.csdn.net/leejizhou * Li Zizhou's Blog * * Public  class myservice extends Service {    //Current value    Private intnum=0;//Whether to stop the loop    Private Booleanisgo=true;//bindservice needs to implement the Onbind method itself to define a binder object to return    PrivateMybinder binder=NewMybinder ();@Nullable    @Override     PublicIBinderOnbind(Intent Intent) {returnBinder } Public  class mybinder extends Binder{         //Create a method to return the current value          Public int Getnum(){returnNum }     }//service Create callback This method here defines a loop that constantly changes the value of Num    @Override     Public void onCreate() {Super. OnCreate ();//cycle operation, value plus 1 per second       NewThread (NewRunnable () {@Override            Public void Run() { while(Isgo) {Try{Thread.Sleep ( +); }Catch(Interruptedexception e)                   {E.printstacktrace ();                   } num++; LOG.I ("MyService", num+"");    }}). Start (); }//There is no need to replicate this method here. This method is not called because the Bindservice startup service//@Override//public int Onstartcommand (Intent Intent, int flags, int startid) {//Return Super.onstartcommand (Intent, flags, startid);//    }    callback This method when//service is disconnected    @Override     Public Boolean Onunbind(Intent Intent) {LOG.I ("MyService","----onunbind----");return Super. Onunbind (Intent); }//service Destroy is callback this method    @Override     Public void OnDestroy() {Super. OnDestroy (); isgo=false; LOG.I ("MyService","----OnDestroy----"); }}

Then androidmanifest.xml in the configuration service, must certainly not forget.

<service android:name=".MyService"></service>

After that, the activity inside the activity through the Bindservice to start the service, three buttons used to start stopping and retrieving values

/** * Blog:http://blog.csdn.net/leejizhou * Li Zizhou's Blog * * Public  class mainactivity extends appcompatactivity {    //Get Binder objects in serviceMyservice.mybinder Binder;//Define a Serviceconnection object    PrivateServiceconnection connection=NewServiceconnection () {@Override         Public void onserviceconnected(componentname name, IBinder service) {//activity Callback This method when the service connection is successfulBinder= (myservice.mybinder) service; }@Override         Public void onservicedisconnected(componentname name) {//activity Callback This method when disconnected from the service, the active call Unbindservice will not use this method. Called only at the time of the exception terminationLOG.I ("MyService","----onservicedisconnected-----"); }    };@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main);//Start serviceFindviewbyid (R.id.bindservice). Setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {Intent bindintent=NewIntent (mainactivity. This, Myservice.class);//Here The first parameter is passed in intent the second parameter is passed into the Serviceconnection object                The third parameter refers to whether the service is created by activity and service binding. It's good to pass the bind_auto_create directly here. After the service oncreate will be runBindservice (Bindintent,connection, service.bind_auto_create); }        });//Stop serviceFindviewbyid (R.id.unbindservice). Setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {//Unbind serviceUnbindservice (connection); }        });//Get the value of the moment in serviceFindviewbyid (R.id.getnum). Setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {Toast.maketext (mainactivity). This,"Value of service"+binder.getnum () +"", the). Show ();    }        }); }}

Bindservice Operating life cycle

Notice that there is a IBinder object in the Onserviceconnected method in the Serviceconnection object in activity, which enables communication between activity and service. When starting a service using Bindservice, the service subclass must implement the Onbind method, and the IBinder object returned by the Onbind method will be passed to onserviceconnected (componentname Name, IBinder service) where communication interaction is implemented.

This is done with a small demo sample of activity and service communication, and it is worth noting that starting Service,service with the Onbind method and the activity is bound state. Then assuming that the activity is destroyed, the service will also be destroyed. Note that the difference between StartService and bindservice should be distinguished.

So you might ask, suppose I want the service to be able to communicate with the activity at the same time and not destroy it with the activity? It is only necessary for StartService and bindservice to be called together. Assuming that start and bind are called at the same time, calling Unbindservice will not stop the service, but must call StopService or the stopself to stop the services.

There is a misconception in using the service that some people think that time-consuming operations can take place in OnCreate in the service. This is not true, the service is still running in the main thread, assuming that the straightforward time-consuming operation is easy to cause the ANR, so even the time-consuming operation in the service will still be placed in the child thread.

Finally summarize under what circumstances use StartService or bindservice it. Suppose you just want to start a backend service to run a certain long-term task, use StartService to do it. Assuming you want to get in touch with a running background service, you can use Bindservice, assuming that you want the service to run for a long time without destroying it with the activity and being able to communicate then call Bindservice after you call StartService. A summary of the service was first concluded. What's the problem to be able to leave a comment below, thanks.

This source code http://download.csdn.net/detail/leejizhou/9459862

Service parsing of Android components

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.