Android Service--android Service Comprehensive Summary

Source: Internet
Author: User

First, the basic knowledge of the service:

One of the four components of a serviceandroid system (Activity, Service, Broadcastreceiver, ContentProvider) is also an application component that is similar to the level of activity, But you can't run it on your own only in the background, and you can interact with other components without interacting with the user to apply the component. Typically does not have a visible user interface. Other application components can start a service, and the service will always run in the background even after the user switches to another application. such as multimedia playback when the user started other activity this time the program to continue to play in the background, such as the detection of the file on the SD card changes, or in the background to record your geographic information changes and so on, in short, the service is always hidden in the background.

Each service must be declared by <service> in manifest. Can be started by Contect.startservice and Contect.bindserverice. Service, like other application components, runs in the main thread of the process. This means that if the service requires a lot of time-consuming or blocking operations, it needs to be implemented in its child threads.

Local Service The Local Service is used inside the application.
It can start and run until someone stops it or it stops itself. In this way, it starts with a call to Context.startservice () and ends with a call to Context.stopservice (). It can call Service.stopself () or Service.stopselfresult () to stop itself. No matter how many times the StartService () method is called, you only need to call once StopService () to stop the service.
Some time-consuming tasks for implementing the application itself, such as querying the upgrade information, and not consuming the application such as the activity of the thread, but the single-threaded background execution, so the user experience is better.

Remote Service Remote Service is used between applications within the Android system.
It can be manipulated by its own defined and exposed interfaces. The client establishes a connection to the service object and invokes the service through that connection. The connection is established to call the Context.bindservice () method to call Context.unbindservice () to close. Multiple clients can bind to the same service. If the service is not loaded at this time, bindservice () loads it first.
Can be reused by other applications, such as the weather forecast service, other applications do not need to write such a service, call the existing can.

Each service can exist in the following two ways:

· Started (startup) when an application starts a service with StartService (), the service will be in the "Started" state. Once started, the service can be run in the background, even if the application that launched it has been launched. Typically, a service that is in the "Started" state completes a feature without returning the result to the application component that started it. For example, the service may be uploading or downloading a file, and when the task is completed, the service exits itself.

· Bound (binding) When an application component binds a service with Bindservice (), the service is in a "Bound" state. A service in the "Bound" state provides a client/service (c/s) calling interface that supports other application components and interacts with it, such as when a request occurs, returns a result, or uses IPC to complete cross-process communication. A service that is "Bound" can only run with the application to which it is bound. Multiple application components can be bound to the same service. When all bound application components exit the binding, the service that is "bound" is destroyed.

For a service, it can be "Started", "Bound" or two states at the same time. Any other application component, such as an activity, can use this service, even if other application components are in different applications. Of course you can define the service as private so that other applications cannot use the service you define.

It is important to note that a service runs in the main thread of its host process--services do not create new threads themselves or run in separate processes (unless you specifically specify them). This means that if your service needs to perform some CPU-intensive operations (such as playing MP3, or using a network), you should create a new thread in the service to do this, reducing the risk of a program not responding (ANR).

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.

1. Using the StartService () method to enable the service, the caller is not connected to the service, and the service is still running even if the caller exits.

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.

2. Using the Bindservice () method to enable the service, the caller and the service are bound together, once the caller exits, the service terminates, there is a "no need to live at the same time, must die" characteristics.

Onbind () The method is only invoked when the service is started with the Context.bindservice () method. This method is called when the caller and the service are bound, and the Context.bindservice () method is called multiple times when the caller is tied to the service and does not cause the method to be called more than once.

Using the Context.bindservice () method to start a service can only call the Onunbind () method to disassociate the caller from the service and call the OnDestroy () method at the end of the service.

Check out the official comparison process:

Official documentation tells us that a service can start and bind at the same time, in which case the system will keep the service running if the service has already started or the BIND_AUTO_CREATE flag is set. If no condition is met, the system will invoke the Ondestory method to terminate the service. All cleanup work (terminating thread, anti-registration sink) is done in Ondestory.

A process with a service has a higher priority

The official documentation tells us that the Android system will try to keep the process running with the service as long as the service has been started (start) or the client is connected (Bindservice) to it. When memory is low, it needs to be maintained, and the process with the service has a higher priority.

1. If the service is calling the Oncreate,onstartcommand or Ondestory method, then the process used for the current service becomes the foreground process to avoid being killed.

2. If the current service has been started (start), the process that owns it has a lower priority than those visible to the user, but is more important than the invisible process, which means that the service is generally not killed.

3. If the client is already connected to service (Bindservice), the process that owns the service has the highest priority and can be considered to be visible.

4. If the service can use the Startforeground (int,notification) method to set the service as the foreground state, the system is considered visible to the user and does not killed when the memory is low. If there are other application components running in the same process as service,activity, it will increase the importance of the process.

Second, service START process

Context.startservice () Start process:

Context.startservice ()->oncreate (), OnStart (), servicerunning, Context.stopservice (), Ondestro Y ()-Servicestop

If the service is not running, Android calls OnCreate () first and then calls OnStart ();

If the service is already running, only OnStart () is called, so a service's OnStart method may be called repeatedly.

If the stopservice will be directly OnDestroy, if the caller is directly exiting without calling StopService, the service will be running in the background, The service can be shut down by StopService after the caller has started up again.

So the life cycle of calling StartService is: onCreate---OnStart (can be called multiple times)--OnDestroy

Context.bindservice () Start process:

Context.bindservice (), OnCreate (), Onbind (), servicerunning, Onunbind (), OnDestroy () Se Rvice 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 life cycle of calling Bindservice is: onCreate-->onbind (only once, not multiple bindings)-->onunbind-->ondestory.

Only OnStart can be called multiple times (through multiple StartService calls) during each turn-off of the service, and the other oncreate,onbind,onunbind,ondestory can only be called once in a life cycle.

Third, service life cycle

Service life cycle is not as complex as activity, it only inherits OnCreate (), OnStart (), OnDestroy () three methods

When we first started the service, the OnCreate (), OnStart () methods were called, and the OnDestroy () method was executed when the service was stopped.

It is important to note that if the service is started, when we start the service again, the OnCreate () method is not executed, but the OnStart () method is executed directly.

It can stop itself through the service.stopself () method or the Service.stopselfresult () method, as long as the StopService () method is called to stop the service, regardless of how many times the startup service method is invoked.

1, Bindservice Introduction

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.


2. Bindservice Start-up process

Context.bindservice ()-onCreate ()-Onbind ()-servicerunning--> onunbind ()- 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 life cycle of calling Bindservice is: onCreate-->onbind (only once, not multiple bindings)-->onunbind-->ondestory.

Only OnStart can be called multiple times (through multiple StartService calls) during each turn-off of the service, and the other oncreate,onbind,onunbind,ondestory can only be called once in a life cycle.

3. 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

Voidoncreate ()

Voidonstart (Intent Intent)

Voidondestroy ()

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 or not, can be accessed through the Context.startservice () and Context.bindservice () methods. 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:

Ibinderonbind (intentintent)

Booleanonunbind (intentintent)

Voidonrebind (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.

Interview questions Related:

1. The difference and understanding between activity cycle and life cycle

The overall life cycle refers to the service between OnCreate () and OnDestroy (). Similar to activity, the service can perform some initialization work in OnCreate () and release resources in OnDestroy (). For example, a music player can create a thread to play music in OnCreate () and stop the thread at OnDestroy ().

Activity life Cycle The service begins activity after Onstartcommand () or Onbind (), each of which processes the request Intent from StartService and Bindservice () respectively. If it is a service of "Started", then the life cycle of its activity is consistent with the entire life cycle of the service. If it is a "bound" service, then its activity life cycle terminates with Unbind ().

Classification by usage:

2. Difference before two different starting modes

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

3. What is the difference between service and Thread and why services are used?

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. In the case of remote service, 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.

Android Service--android Service Comprehensive Summary

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.