The service of Android development four components

Source: Internet
Author: User

Four components of Android development--service

First, Service

Introduction

Service is one of the four components of the Android system (activity, Service, Broadcastreceiver, ContentProvider), which is similar to the level of activity, The difference is that the service can only run in the background without providing a user interface and can interact with other components. A Service is an application component that can run in the background for a long time and does not provide a user interface. Another application component can start a service, and it will continue to run in the background even if the user switches to another application. In addition, a component can be bound to a service to interact with it and even perform interprocess communication (IPC). For example, a service can handle network transactions in the background, play music, perform file I/O, or interact with content providers.

A service can basically have two forms:

Started:

A service will be opened when an application component (for example, an activity) initiates it to invoke StartService (). Once a service is started, it can run indefinitely in the background, even if the component that started it is destroyed. Typically, the start service performs an operation and does not return a result to the caller. For example, it may download or upload files over the network. When the operation is complete, the service should be destroyed automatically.

Bound :

a service is " bound" when an application component binds to it by calling Bindservice (). A binding service provides a client-server interface that allows components to interact with the service, send requests, get results, and even do this across processes and interprocess communication (IPC). A service can be bound to multiple customers at the same time, and when multiple customers are unbound, the service is destroyed

Note: A service runs in its hosting process, and the service does not create its own thread and is not running the main thread in a separate process (unless otherwise specified). This means that if your service is intended to take any time-consuming action (such as MP3 playback or network download, etc.), you should create a new thread in the service to perform the work. By using a separate thread, you will reduce the application's non-responsive (ANR) errors and the application's UI main thread can continue to work in response to the user's actions.

Second, create Service

To create a service, you must create a subclass of services (or one of its existing subclasses). Some callback methods that handle key aspects of the service life cycle in the implemented subclasses, and provide a mechanism by which components are bound to the service and can be rewritten as needed:

Onstartcommand ()

Each time the client calls the StartService () method , the service is called back to the method.

Onbind ()

This method is a method that the subclass of each service must implement. The method returns an IBinder object that the application can communicate with through the object and service components. If you do not want to allow binding, you should return NULL.

OnCreate ()

The method is immediately called back when the service is created for the first time.

OnDestroy ()

When the service is destroyed before the method is called back, the service you create should clean up unused resources in this method , such as threads, registered listeners, receivers, and so on.

registering in a configuration file Service:

<manifest ... >
...
<application ... >
<service Android:name = ". Exampleservice "/>
...
</application>
</manifest>

Third, Intentservice class

Because the first service does not need to process multiple requests at the same time ( It is actually a dangerous multi- threaded case), This may be the best if you implement your service using Intentservice class .

Intentservice is a subclass of the service class that is used to handle asynchronous requests. The client can pass the request to Intentservice through the StartService (Intent) method. Intentservice opens a single thread in the OnCreate () function to handle the tasks of all intent request objects (sent over StartService) by Handlerthread, so that the transaction does not block the main thread. After executing the work for the intent request object, the service is automatically stopped if no new intent request is reached, otherwise the task corresponding to the next intent request is executed.

Intentservice in processing the transaction, or in the handler way, create an internal handler called Servicehandler, and bind it directly to the corresponding sub-thread of Handlerthread. Servicehandler the transaction that deals with a intent is encapsulated into a virtual function called onhandleintent, so we can directly implement the virtual function onhandleintent, and then do the different transaction processing on the basis of the intent.

In addition, Intentservice implements the Onbind () method by default, and the return value is null.

  Use Intentservice Two steps required:

1. Write the constructor function

2, the realization of virtual function onhandleintent, and in the inside according to intent different transaction processing can be.

Benefit: When dealing with asynchronous requests, you can reduce the amount of code that is written and make it easier to implement project requirements

Note: The constructor for Intentservice must be a constructor with an empty argument and then call Super ("name") in this form of a constructor.

Because the instantiation of the service is done by the system, and the system uses a null-parameter constructor to instantiate the service's

Here is an example of Intentservice:

Public class Hellointentservice extends Intentservice {

/**
* A constructor is required, and must call the Super Intentservice (String)
* Constructor with a name for the worker thread.
*/

Public Hellointentservice(){
Super("Hellointentservice");
}

/**
* The Intentservice calls this method from the default Workerthread with
* The intent that started the service. When the This method Returns,intentservice
* Stops the service, as appropriate.
*/

@Override
protected voidOnhandleintent(IntentIntent){
//Normally we would do some work here, like download a file.
//For our sample, we just sleep for 5 seconds.
LongEndTime= System.Currenttimemillis()+5* +;
while (System.Currenttimemillis()<EndTime){
synchronized ( This){
Try {
Wait(EndTime- System.Currenttimemillis());
} Catch(ExceptionE){
}
}
}
}
}

Four, The Lifecycle of a Service

It's not like Activity Lifecycle callback function, you do not need to call the parent class to execute these callback methods.


Note: The diagram on the left shows the use of the StartService () The life cycle of the service created and the diagram on the right show the use StartService () The life cycle of the service being created.

· The lifetime of the service is started from onCreate () and is called until the OnDestroy () method returns. Like activity, the service initializes its work in onCreate () , releasing the remaining resources in OnDestroy () . For example, a music playback service can create a music-playing thread in OnCreate () and stop the thread in Ondestory (). onCreate ()   and OnDestroy () are called by all service, regardless of whether the service is through startservice () or Bindservice () established.

· The life time of the service Active activity (ACTIVELIFETIME) is initiated from Onstartcommand () or onbind () , and they are handled by each the Intent object passed over by the StartService () or Bindservice () method.

if Service is through StartService () Open, then its activity life cycle and the entire life cycle end together.

if Service is through Bindservice () , their active life cycle is ended after the onunbind () method returns.

Note: Although an open service is stopped by calling Stopself () or stopservice () , there is no corresponding callback function corresponding to it , i.e. no OnStop () callback method. So, when the Stop method is called, unless the service and the client component are bound, the system will destroy it directly, and theondestory() method will be called and the only callback method that will be called at this time.

Five, managing the Lifecycleof a Bound Service

When the binding service and all clients unbind, the Android system will destroy it (unless it is also turned on by the Onstartcommand () method).

Therefore, if your service is a purely binding service, then you do not need to manage its life cycle.

However, if you choose to implement the Onstartcommand () callback method, you must explicitly stop the servicebecause the service is now considered to be open.

In this case, the service runs until it calls stopself () or another component calls StopService (), regardless of whether it is bound to the client or not.

Also, if your service is turned on and accepts bindings, then when the system calls your Onunbind () method, if you want to accept a onrebind () call at the next client binding (instead of calling onbind () ), you can choose to return true in onunbind () . The return value of onrebind () is void, but the client still gets the IBinder object in its onserviceconnected () callback method.

Shows the life cycle of this service (which is enabled and also allowed to bind):


To be continued .......

The service of Android development four 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.