The Service is not completely parsed, and the Service is not parsed.

Source: Internet
Author: User

The Service is not completely parsed, and the Service is not parsed.

This article does not introduce service usage and lifecycle, but records and analyzes some key points.

We all know that a Service is an application component executed in the background for long-term operations in the background, such as network transactions and playing background music. It also has two startup modes. If other application components want to communicate with the service in-process (IPC), they can be bound to the service. The problem about the life cycle is not long-winded. The figure of releasing the official document directly:

Regardless of the method to start the service, any application component can use the service. If you want your app to use the service, you must addandroid:exportedAnd set it to false. Android officially recommends that you use an explicit method to start the service to ensure app security.

In addition, we need to note that by default, the service does not restart an independent thread to run, but runs in the main thread of the host process. Obviously, if we need to perform time-consuming operations, such as playing background music and network operations, what should we do?

    • We can create a thread in the activity and start and destroy the thread in the activity;
    • Use asyncTask to complete the task;
    • Open a new thread in the service to complete these tasks to prevent ANR errors.

IntentService

When we do not need to process multiple requests at the same time, our best solution is to use IntentService to complete the task, and we only need to rewrite onHandleIntent () to complete the processing logic. In IntentService, the following tasks are performed:

    • A new worker thread is started to execute intent tasks submitted to the onStartComand method.
    • A work queue is created to store multiple request tasks. Each time, only one intent is passed to the onHandleIntent () method for processing.
    • When all request tasks are completed, the service is automatically stopped.
    • In the default onStartCommand () method, pass the received intent parameter to onHandleIntent () for processing.

The following 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 worker thread with   * the intent that started the service. When this method returns, IntentService   * stops the service, as appropriate.   */  @Override  protected void onHandleIntent(Intent intent) {      // Normally we would do some work here, like download a file.      // For our sample, we just sleep for 5 seconds.      long endTime = System.currentTimeMillis() + 5*1000;      while (System.currentTimeMillis() < endTime) {          synchronized (this) {              try {                  wait(endTime - System.currentTimeMillis());              } catch (Exception e) {              }          }      }  }}

Here we only need to implement a simple constructor and intent processing method. Of course, we can also rewrite other methods in the service life cycle as needed, but remember to call the parent class method. It should be clear that all tasks submitted to the service are stored in the queue in the form of intent, and the only worker thread in IntentService gets an intent for processing each time, the IntentService is automatically disabled after processing.

If you want to process tasks in multiple threads concurrently, you must inherit the service to process the tasks. The specific code will not be demonstrated here, but a little reminder is required. The onStartCommand method returns an int value. Generally, the method of the parent class is returned. The int value describes the operation after the system kills the service. Its constant options are as follows:

    • START_NOT_STICKY: When the onStartCommand method returns, the system kills the service and will not restart the service unless an intent request is passed in. This option can ensure that when the application restarts those unfinished work without running the service, avoid starting the service.
    • START_STICKY: After the onStartCommand method is returned, the system will restart the service and execute the onStartCommand method. However, the re-transmitted intent is not the previous intent, instead, null is used (unless a new intent request exists ). This option is applicable to a service similar to a media player. It does not execute any command but is always running a waiting task.
    • START_REDELIVER_INTENT: When the onStartCommand method returns, the system will restart the service and execute the onStartCommand method. The intent passed in again is the same as the previous one, subsequent intent requests will be executed in sequence. This option applies to a service similar to a download task, which is always active and needs to be restored immediately once it fails.

In addition, the service is often used in conjunction with notification, so that the service can run to the foreground, such as music playback tasks, and can interact with users. The content will be introduced later.

 

Related Article

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.