Full summary of Service in Android

Source: Internet
Author: User

1. Type of service

 

By Run location Category:

Category Difference Advantages Disadvantages Application
On-premises Services (local) The service is attached to the main process, The service is attached to the main process rather than the independent process, thus saving resources to some extent, and the local service because it is in the same process and therefore does not require IPC, nor does it require aidl. The corresponding bindservice will be much more convenient. After the main process is killed, the service terminates. Very common applications such as: HTC Music Play service, every day music playing service.
Remote Services (remotes) The service is an independent process, The service is a standalone process, and the corresponding process name format is the package name plus the android:process string you specified. Because it is an independent process, the service is still running, unaffected by other processes, and has a high degree of flexibility in providing services to multiple processes when the activity's process is killed. The service is a standalone process, consumes a certain amount of resources, and uses aidl for IPC to be a little more troublesome. Some service providers that provide system services are resident.

In fact, remote services are still very rare, and generally are system services.

Classification by Run Type:

Category Difference Application
Front desk Service Will show ongoing's Notification in the notification column, When the service is terminated, the notification column of the Notification will also disappear, so that the user has a certain role in the notification. Common such as music playback services.
Background services The default service is a background service, which means that ongoing Notification is not displayed in the notification column. When the service is terminated, the user cannot see the effect. Some services that do not need to run or terminate the prompt, such as weather updates, date synchronization, mail synchronization, and so on.

Some classmates may ask, backstage service we can create ongoing's Notification by ourselves so as to become the front desk service? The answer is no, the front desk service is required to call Startforeground (Android 2.0 and later) or Setforeground (previous versions of Android 2.0) to make the service a front-end service after doing the above work. The advantage of this is that when the service is forcibly terminated externally, the ongoing Notification will still be removed.

Classification by usage:

Category Difference
StartService Start-up services Primarily used to start a service to perform background tasks without communication. Stop service using StopService
Bindservice Start-up services This method initiates the service to communicate. Stop service using Unbindservice
StartService also bindservice start-up service Stop service should use both Stepservice and Unbindservice

Services initiated in the above three ways have a different life cycle, which will be given later.

2. The difference between Service and Thread

 

Many times, you may ask, why use the Service, instead of thread, because the thread is very convenient, than the Service is more convenient, I would like to explain in detail below.

1). Thread:thread is the smallest unit of program execution, and it is the basic unit for allocating CPUs. You can use the Thread to perform some asynchronous operations.

2). Service:service is a mechanism for Android, and when it runs, if it is a local service, then the corresponding service is running on the main thread of the master process. such as: Oncreate,onstart These functions are run on the main thread of the master process when they are called by the system. If it is remoteservice, then the corresponding Service is running on the main thread of the standalone process. So please do not interpret the Service as a thread, it has no relationship with the thread of half a dime!

In that case, why should we use Service? Actually this is related to the Android system mechanism, we first take the Thread to say. The thread runs independently of the activity, meaning that if you do not actively stop the thread or the Run method in thread does not complete after an activity is finished, thread will always execute. So there's a problem here: When the Activity is finished, you no longer have a reference to that Thread. On the other hand, you have no way to control the same Thread in different Activity.

For example, if your thread needs to be connected to a server for some sort of synchronization over time, the thread needs to be running when the Activity does not start. This time when you start an activity there is no way to control the Thread that was created in the activity. So you need to create and start a service, create, run, and control the Thread within the service, which solves the problem (because any Activity can control the same service, and the system will only create an instance of the corresponding service).

So you can think of the service as a message, and you can call Context.startservice, Context.stopservice, Context.bindservice,context.unbindservice, to control it, you can also register Broadcastreceiver in the Service, in other places by sending broadcast to control it, of course, these are The Thread cannot do that.

3. Service life cycle

onCreate onStart OnDestroy onbind

1). The life cycle of the service being started: If a service is started by an activity call Context.startservice method, Then the service runs in the background regardless of whether or not activity is unbound to the service using Bindservice bindings or Unbindservice. If a service is started multiple times by the StartService method, the OnCreate method is only called once, OnStart will be called multiple times (corresponding to the number of calls StartService), And only one instance of the service is created (so you should know that only one stopservice call is needed). The service will always run in the background, regardless of whether the program's activity is running until it is called StopService, or its own Stopself method. Of course, if the system resources are insufficient, the Android system may end the service.

2). The lifecycle of a service that is bound: If one service is started by an activity call Context.bindservice method binding, no matter how many calls Bindservice calls, The OnCreate method is called only once, and the OnStart method is never called. When the connection is established, the service will run until the call to Context.unbindservice disconnects or the Context of the previous call to Bindservice does not exist (for example, when activity is finished), The system will automatically stop the service and the corresponding OnDestroy will be called.

3). The life cycle of a service that is started and bound: If a service is also started and bound, that service will always run in the background. And no matter how it is called, OnCreate is always called only once, how many times the service's onstart is called, and how many times the StartService is called. Calling Unbindservice will not stop the service, but must call StopService or the stopself of the services to stop it.

4). The Purge service when a service is stopped: the OnDestroy method will be called when one of the services is terminated (1, call stopservice;2, call stopself;3, no longer have a bound connection (not started)). Here you should do some cleanup work, such as stopping the threads created and running in the service.

Special attention:

1, you should know that when the call Bindservice bound to the service, you should make sure to call Unbindservice in a certain place to unbind (although the Activity by the time the binding will be removed automatically, and the service will automatically stop);

2, you should pay attention to use StartService start the service, must use StopService stop service, regardless of whether you use Bindservice;

3, at the same time use StartService and bindservice to notice, service termination, need to unbindservice and stopservice simultaneously call, can terminate Service, regardless of StartService and The order in which Bindservice is called, if Unbindservice is called first, the service does not terminate automatically, then the service stops after calling StopService, and if StopService is called first, the service will not terminate, and then call Unbindservice or previously called Bindservice the Context does not exist (such as when the activity was finished) after the service will automatically stop;

4, when rotating mobile phone screen, when the phone screen in the "horizontal" "vertical" transformation, at this time if your activity will automatically rotate, the rotation is actually the activity of re-creation, so the rotation before the use of Bindservice established connection will be disconnected (Context does not exist), the life cycle of the corresponding service is the same as above.

5, in the SDK 2.0 and later versions, the corresponding OnStart has been rejected into the Onstartcommand, but the previous OnStart still valid. This means that if you are developing an application with an SDK of 2.0 and later, you should use Onstartcommand instead of OnStart.

4. StartService Start-up service

 

Want to start the service with StartService, whether local or Remote we need to do the work is just as simple. Of course, remember to register the service in Androidmanifest.xml.

Based on the life cycle above, we will give the code framework in the Service:

+ View Code

The corresponding lifecycle system callback function has been described above, with the appropriate code in place. Here's the code to start and stop the Service:

+ View Code

The corresponding Intent is the Intent of the flag service class.

5. Local and Remote service bindings

Also remember to register the service in the Androidmanifest.xml

1). Local Service bindings:The binding of the local service is simpler, first in the service we need to implement the service's abstract method Onbind, and return an object that implements the IBinder interface.

The code in the Service:

+ View Code

The key point of the above code is that Onbind (Intent) Returns an object that implements the IBinder interface, which will be used to bind the service's Activity to the Local service communication. Here is the code in the Activity:

+ View Code

In Activity, we get callbacks that make connection and connection accidental loss through the Serviceconnection interface. The Bindservice has three parameters, the first is the Intent that distinguishes the Service from the Intent in StartService, the second is the object that implements the Serviceconnection interface, and the last is the flag flag bit. There are two flag,bind_debug_unbind and Bind_auto_create, the former for debugging (details can be viewed Javadoc described above), the latter is used by default. Unbindservice unbind, the parameter is the Serviceconnection interface object created previously. Also, calling Unbindservice multiple times to release the same connection throws an exception, so I create a Boolean variable to determine if Unbindservice has been called.

Operation Result:

2). Remote Service bindings:remote service bindings because the service is in another process, you need to use Android's IPC mechanism. This is going to be a very long topic, so I'm going to write another Android IPC analysis, and I'll go over it in detail, and then update the link here, so stay tuned.

Special attention:

1. Service.onbind If NULL is returned, calling Bindservice starts the service but does not connect to the service, so serviceconnection.onserviceconnected is not called. But you still need to use the Unbindservice function to break it so that the Service stops.

6. Create a front -office service

 

The advantages of the front desk service are explained above, but setting up the service for Front desk service, we need to note that the method used in SDK 2.0 and later version is Startforeground and Stopforeground, the previous version used is Setforeground, So if your application has a minimum operating environment requirement of 2.0, then you can use the new method directly, and if the running environment is below 2.0, then for backward compatibility, you must use the reflection technique to invoke the new method.

Here are some of the changes I've made to the code that I've re-knocked with Apidemos, so it's more descriptive:

+ View Code

Special attention:

1, using Startforeground, if the ID is 0, then notification will not be displayed.

 

7. Under what circumstances use StartService or bindservice or use both StartService and Bindservice

 

If you just want to start a background service for a long time to do a task then use StartService. If you want to get in touch with a running Service, there are two ways, one is to use broadcast, and the other is to use Bindservice, the disadvantage of which is that if communication is more frequent, it can cause performance problems, and Broadcastreceiver The time it takes to execute the code is very short (perhaps halfway, the code will not execute), and the latter does not, so we definitely choose to use Bindservice (this time you are using both StartService and Bindservice, which It is useful to update some of the operating states of the Service in the Activity. In addition, if your service only exposes a remote interface, it is used to remotely invoke the execution method on the client side of the connection (Android service is the C/S architecture). At this point you can save a lot of system resources by not letting the service run from the start, but only using bindservice, so that the instance of the service is created at the first Bindservice, which saves a great deal of resource, especially if your services are remote service, The more obvious the effect will be (of course, it will take some time when the Service is created and you should be aware of that).

 

8. Common options for Service elements in Androidmanifest.xml

Android:name-------------Service class name

Android:label--------------The name of the service, if this is not set, the service name displayed by default is the class name

Android:icon Icons for--------------services

Android:permission-------Affirm the permissions for this service, which means that only apps that have this permission available to control or connect to the service

Android:process----------Indicates whether the service is running in another process, and if this is set, then the string will be appended to the package name to indicate the name of the other process.

Android:enabled----------If this is set to true, then the Service will be booted by default, not set to False by default

Android:exported---------Indicates whether the service can be controlled or connected by another application, and does not set the default to False

This article is code: Http://files.cnblogs.com/newcj/ServiceTest.zip

Transferred from: http://www.cnblogs.com/newcj/archive/2011/05/30/2061370.html

Full summary of Service in Android

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.