Android Service Demo Example using detailed

Source: Internet
Author: User

The Android Service Demo example uses a detailed

Overview
Service is one of the four components of Android, its main role is to perform operations in the background, Activity belongs to the UI interface with the user interaction, and the service does not have a UI interface, all operations are based on the background to complete. And the service can be initiated by other application calls as well as the Activity, and the service remains running even if the user switches the application. A component that is bound to a service (BIND) can interact with the service for data, and can also interact with different processes (IPC). The service is usually used in situations where there are network requests, music manipulation, file I/O operations, and so on.

Start
Service is typically started in the following two ways

StartService

When a component (for example, activity) starts a Service by calling StartService (). Once started, the service will run independently in the background, and the service can continue to run in the background even if the calling component has been destroyed. In general, a single operation is required, and the service is started by the time it is not necessary to return the result of the operation to the caller. For example, when an upload or download operation is done, the Service should call StopService () or stopself () to end the operation when it completes.

Bindservice

When a component (for example, activity) starts a Service by calling Bindservice (). This approach provides a Client-service interface that allows the calling component to send requests and return results to the service (Tengyun technology ty300.com), which can be used for interprocess communication (IPC). Whenever a component binds the service, the service is not destroyed. and multiple components can bind to a service at the same time, and the service is destroyed only when all of the bundled components are untied.

Although the two approaches are discussed separately, they are not mutually exclusive, and can be bound after the service is started using StartService.

Note: Although the Service is running in the background, it is still doing all the work in the mainline thread (Getting Started tutorial qkxue.net). The Service is not on a separate thread or process and is in the main thread unless it is defined separately at startup. So this means that any operation that can block the main thread (for example, music playback or network requests) should open a new thread for operation, otherwise it is prone to ANR.

Method
When creating a service, you must inherit the service and override some of the primary methods of the parent class to implement the functionality. The following is an introduction to the main methods

Onstartcommand ()

The system calls this function when a component (for example, activity,fragment) starts the Service by calling StartService (). After the method is called, the Service is started and runs independently in the background. If this method is overridden, the developer will need to call stopself () or StopService () to end the service after the service has finished executing the operation. You do not need to override this method if you only start the Service in a bind way (BIND).

Onbind ()

The system calls this function when a component (for example, activity, fragment) starts the service by invoking the Bindservice () binding. When implementing this function, it is necessary to return a IBinder inheriting class to communicate with the service. This function must be overridden by default, but if you do not want to start the service by binding, you can return null directly

OnCreate ()

The system calls this method to initialize some one-time variables when the Service is first started. If the service is already started, this method will no longer be called.

OnDestroy ()

The system calls this method when the service is no longer ready to be destroyed. These cleanup methods should be written in this method when the service is useful to thread, listeners, receivers, and so on.

These are some of the ways to implement a Service.

If a component starts the service by calling StartService (), the service will run in the background until the service calls Stopself () or a component calls StopService () To end the service.

If a component starts the service by calling Bindservice (), the service will run in the background until the component is unbound from it. Service will be destroyed when there is no component binding

The following sections will show you how to create a Service by using the two methods described above

Declare Service in Manifest

Similar to Activity, all Service is declared in Manifest, as follows:

<manifest ... >
...
<application ... >
<service android:name= ". Exampleservice "/>
...
</application>
</manifest>
Set the android:exported to False in the <service> tab. You can prevent other programs from starting your Service.

By started the service component (for example, activity, fragment) by calling the StartService () method, the system calls the Onstartcommand () method to implement the started way to start the service 。

When the service is started in this form, the service's entire life cycle is completely independent, even if the component that started the service has been destroyed, the service can run indefinitely in the background. However, the developer should call Stopself () or other component calls StopService () to end the service after the operation in the service has completed.

program components, such as activity, can pass a Intent to StartService () to deliver the data before the component and service. The service is the Onstartcommand () method of the system call that accepts the passed intent, completing the entire data passing process.

Note: The service itself is running on the mainline thread by default, so if the service is going to do something that will clog the threads, be sure to put those operations into a new thread.

The Android framework provides the intentservice to meet the needs of running asynchronous threads in the background.

Intentservice

Intentservice is a subclass of the Service, and all request operations are in an asynchronous thread. If the Service is not required to process multiple requests at the same time, Intentservice will be the best choice. By inheriting and overriding the Onhandleintent () method in Intentservice, you can perform an asynchronous thread operation in the background for the received Intent.

The Intentservice provides several features such as:

An asynchronous thread is created to handle all intents that are sent from the program's main thread to Onstartcommand ().

A queue pool has been created to ensure that only one Intent is passed to the Onhandleintent () method at a time, avoiding multithreading issues.

Provides the implementation of the default Onbind () method, which returns null

Provides the implementation of the default Onstartcommand () method, puts received intent into the queue pool, and then handles it to Onhandleintent ()

All developers need only to implement onhandleintent () to focus on what the Service is doing. See this article for more Intentservice practical tips.

If developers need to rewrite other methods, such as OnCreate (), Onstartcommand (), and OnDestroy (), ensure that the implementation of the parent class is called, so that the intentservice can handle the thread's life cycle correctly. For example:

@Overridepublic int Onstartcommand (Intent Intent, int flags, int startid) {
Toast.maketext (This, "service starting", Toast.length_short). Show (); Return Super.onstartcommand (Intent,flags,startid);
}
System Recovery Resource issues

When the system is out of memory, some Activity and Service is forced to be recycled to get more resources for the programs or pages that the user is interacting with. This requires the Service to automatically restart when the resources are sufficient. This function is implemented by the return value of the Onstartcommand ()

Start_not_sticky

When the system destroys the service because it recycles resources, the service does not start automatically when the resource is again sufficient. Unless the Intent is ready to be sent for processing. This is the safest option to avoid the need for Service to start when your program can easily re-open an unfinished operation.

Start_sticky

When the system destroys the service because it recycles resources, the service is started automatically when the resource is sufficient again, and the Onstartcommand () method is called again, but the last Intent is not passed, whereas the system is in the callback Onstartcommand () Will pass an empty intent. Unless the intent is ready to be sent for processing.

Manuscripts: Diligent Learning qkxue.net

Extended Reading

Http://qkxue.net/info/24418/Android-Service

Android Service Demo Example using detailed

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.