Detailed analysis of Android service class services

Source: Internet
Author: User

What does a service do?

Many people do not understand what the service is for, in fact, the service as one of the four components of Android, can be understood as a running in the background activity, it is suitable for dealing with some long-time background operation does not disturb the user, such as your player to play music after the jump to other pages, Music needs to continue to play, then this time you can play the music has been running in the background service, need to start playing when the activity to start the service, and then through the service to call playback, need to stop when the service stopped.


one might ask, thread can also be run in the background, why use the service without thread? The service and thread are two completely different concepts, thread is a child thread and is not the intersection of the main thread, and Service is running on the main thread is the intersection with the main line threads. Of course you would say why does the service run in the main thread without compromising performance? Why use it? In fact, the service as a component of the Android system, and activity, and so on, we can fully define the sub-thread in the background operation. If a large amount of background time-consuming data processing is required, the best way to do this is to open a sub-thread in the service instead of just opening a sub-thread, in order to increase the priority of the child thread and not be easily killed by the system.


thread is independent of the main thread, even if the activity is over, if you do not actively shut down its sub-thread, thread may still be running silently, this time, you can not control these sub-threads because you have to hold the activity to the end, This is not safe for the program.

For example: If your app is a chat app, you'll need to create a thread to access the server every few minutes and show if someone sent you a message, and then when you jump to another activity such as a personal settings page, And the original possession of the thread activity has been finfish, when you go back to the time you have been in the chat activity created by the child thread, the same can not gracefully shut down these sub-threads. That's when the service is needed, because the service is activity-independent, where you can create child threads, and even if the activity is closed, you can manage or shut down these sub-threads. And the service is not the same as activity one by one, you can have multiple activity corresponding to a service, these thread is not possible.


How to use the service:

The original way to create the service:
Define a class as MyService, inherit from service, and implement the only abstract method: Onbind (), which is useful for the following:

public class MyService extends service{@Overridepublic ibinder onbind (Intent arg0) {//TODO auto-generated method Stubretu RN null;}}

Such a primitive service class is created, and next we start it in the activity (via intent):

Intent Intent = new Intent (mainactivity.this,myservice.class); StartService (Intent);

This time I ran the program, will find the program crashed. Error: Android:content:ActivityNotFoundException:Unable to find Exnlicit activity class. The problem is that service is also one of Android's four components and must be registered in the Androidmainfest.xml file:


Once the registration is complete and run again, the service starts successfully.
How to stop a service:

Intent Intent = new Intent (mainactivity.this,myservice.class); StopService (Intent);



To create a service with BIND mode:
The above is the StartService way to start the service, in this case, unless the active shutdown, or even if the activity is closed, the service can still run in the background
There is another service that can be bundled with activity, in which case the service shuts down as soon as the activity is closed:

At this point we need to call the Onbind method that we started with, binder at this time is equivalent to the connection points:
In our custom MyService class, add a IBinder object and create an Mybinder inner class, where you define a method to get the current service, and override the Onbind and Onunbind methods:

public class MyService extends Service{private final IBinder binder = new Mybinder ();  public class Mybinder extends Binder {          MyService getService () {              return myservice.this;          }      } @ Overridepublic ibinder onbind (Intent Intent) {//TODO auto-generated method Stublog.d ("MyService", "Onbind ..."); return Binder;} @Overridepublic boolean onunbind (Intent Intent) {//TODO auto-generated method Stublog.d ("MyService", "Onunbind ..."); return Super.onunbind (Intent);}}


Starting the service in this way requires a call to the Onbind method:

Intent Intent = new Intent (mainactivity.this,myservice.class); Bindservice (Intent, connection, context.bind_auto_ CREATE);//The service is bound and started here

You can see that there are 3 parameters, the first one that is passed in to start the MyService intent, the second passed in is a Serviceconnection object, and the third is to call the system's variable representation automatic binding, where the connection is created as follows:

Final Serviceconnection connection = new Serviceconnection () {@Overridepublic void onservicedisconnected (componentname ARG0) {//TODO auto-generated Method stub//onservicedisconnected () is not normally called, it is called when the service is destroyed, for example, when the memory is out of resources } @Overridepublic void onserviceconnected (componentname arg0, IBinder binder) {//TODO auto-generated method Stubmybinder Mybinder = (mybinder) binder; MyService MyService = Mybinder.getservice ();  Get the service//get a variety of information about the service here including status, etc.}};

Stop service: By calling the Onunbind method, passing in the connection, you will stop the service



We've shown in two ways to create an initial service, but there's a question: how do I see if the service is running?

public boolean isservicework (Context mcontext, String serviceName) {  Boolean iswork = false;  Activitymanager Myam = (activitymanager) mcontext.getsystemservice (context.activity_service);  list<runningserviceinfo> myList = myam.getrunningservices (+);  if (mylist.size () <= 0) {  return false;  }  for (int i = 0; i < mylist.size (); i++) {  String mname = Mylist.get (i). Service.getclassname (). toString ();  if (Mname.equals (ServiceName)) {  iswork = true;  break;  }  }  return iswork;  }  

Call this method and pass in the current activity context, and the service Name: Package name + Service class name (for example: Com.example.MyService)
If the result returns true indicates that it is running, false indicates that it has been closed.



Service life cycle:

The life cycle of the original way:
We can view them by rewriting the OnCreate, Onstartcommand, OnDestroy methods in the service and printing the logs individually:

public class MyService extends service{@Overridepublic ibinder onbind (Intent arg0) {//TODO auto-generated method Stubretu RN null;} @Overridepublic void OnCreate () {//TODO auto-generated method Stubsuper.oncreate (); LOG.D ("MyService", "onCreate ..."); @Overridepublic int Onstartcommand (Intent Intent, int flags, int startid) {//TODO auto-generated method Stublog.d ("MyServ Ice "," Onstartcommand ... "); return Super.onstartcommand (Intent, flags, Startid); @Overridepublic void OnDestroy () {//TODO auto-generated method Stubsuper.ondestroy (); LOG.D ("MyService", "OnDestroy ...");}}


Create two buttons in a layout file:


Code calls:

StartService = (Button) This.findviewbyid (r.id.startservice); stopservice = (Button) This.findviewbyid ( R.id.stopservice) Startservice.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View arg0) {// TODO auto-generated Method Stubintent Intent = new Intent (Mainactivity.this,myservice.class); StartService (intent);}}); Stopservice.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated Method Stubintent Intent = new Intent (Mainactivity.this,myservice.class); StopService (intent);}});

To run the program, click the Start Service button to view Logcat printing:



Click the Start service button several times:


Click the Close Service button:


As can be seen, when we first click the start service, call the OnCreate method of the service, when we click on multiple launches, only invoke the service's Onstartcommand method, click Close, call the service OnDestroy method. So we probably know the life cycle of the service:
1. When you start the service for the first time, call OnCreate
2. The second time the service is started, OnCreate is not called again but calls Onstartcommand
3. When the service is closed, call OnDestroy to destroy
The flowchart is as follows:




The life cycle of the binding method:
The code above has been described, and here no longer describes, the same way in the Onbind and Onunbind methods to print the log, you can get its running flow as follows:
OnCreate--Onbind (only once, not multiple times)--onunbind---Ondestory

Detailed analysis of Android service class services

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.