Android Intentservice Source Analysis

Source: Internet
Author: User

Intentservice Introduction:Intentservice is aContext.startservice (Intent)start a service that can handle an asynchronous request, and you only need to inherit intentservice and override it.onhandleintent (Intent)The intent method receives an object that automatically stops the service when the asynchronous task completes. All requests are processed in the Intentservice internal worker thread, which executes the task sequentially (but does not block the execution of the main thread) and can only execute one asynchronous request at a time.

Intnetservice Features:1. You do not need to open a thread in the service to handle time-consuming tasks. 2. You do not need to manually stop the service.
Intentservice Use Example:The service-side code is as follows:
Package Com.xjp.broadcast;import Android.app.intentservice;import Android.content.intent;import android.util.Log;/ * * Description: * USER:XJP * DATE:2015/5/4 * time:15:47 */public class Myintentservice extends Intentservice {pri    vate static final String TAG = "Myintentservice";  /** * Creates an intentservice.     Invoked by your subclass ' s constructor.     * * @param name used to name of the worker thread, important only for debugging.    */Public Myintentservice () {Super ("TEST");        } @Override public void OnCreate () {LOG.E (TAG, "====oncreate==");    Super.oncreate ();        } @Override public void OnDestroy () {LOG.E (TAG, "====ondestroy==");    Super.ondestroy (); } @Override public int onstartcommand (Intent Intent, int flags, int startid) {log.e (TAG, "====onstartcommand        ==");        LOG.E (TAG, "====current Thread id==" + thread.currentthread (). GetId ()); Return Super.onstartcommand (Intent, flags, Startid);   } @Override protected void Onhandleintent (Intent Intent) {log.e (TAG, "====onhandleintent==");        LOG.E (TAG, "====current Thread id==" + thread.currentthread (). GetId ());        /** * Here simulates time-consuming task execution */try {thread.sleep (2000);        } catch (Interruptedexception e) {e.printstacktrace ();        } int key = Intent.getintextra ("key", 0);    LOG.E (TAG, "====the key is = = =" + key); }}


The client code is as follows:
Package Com.xjp.broadcast;import Android.app.activity;import Android.content.intent;import android.os.Bundle; Import Android.view.view;import Android.widget.button;public class Mainactivity extends Activity {private Button start    Service;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        StartService = (Button) Findviewbyid (R.id.startservice);                 Startservice.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {                Intent Service2 = new Intent (mainactivity.this, Myintentservice.class);                Service2.putextra ("Key", 3);            StartService (SERVICE2);    }        });        } @Override protected void Onresume () {super.onresume ();        Intent service = new Intent (this, myintentservice.class);        Service.putextra ("Key", 1);        StartService (service); InchTent Service1 = new Intent (this, myintentservice.class);        Service1.putextra ("Key", 2);    StartService (Service1);    } @Override protected void OnDestroy () {Super.ondestroy (); }}

After launching the application, print as follows:


We found that: started two services, performed a oncreate, two times Onstartcommand and thread id=1, stating that the service was executed on the UI thread, performed two onhandleintent and thread id = 234, explaining the abstract method Onh The andleintent is executed in a sub-thread, so the time-consuming task can be executed in this method. And you will find that when the second task is finished, the printout ondestory that the service stops automatically without the need for an artificial stop.
Why is onhandleintent executed in a child thread? When did you create a child thread? Why can Intentservice perform asynchronous time-consuming tasks in onhandleintent? Why does the service stop automatically after the task has been executed?? Next, we solve the mystery from the source angle!!!
intentservice Source Analysis:
/* Copyright (C) The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License") ; * You are not a use this file except in compliance with the License. * Obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by appli Cable law or agreed into writing, software * Distributed under the License is distributed on a "as is" BASIS, * without Warranties or CONDITIONS of any KIND, either express OR implied. * See the License for the specific language governing permissions and * limitations under the License. */package android.app;import android.content.intent;import Android.os.handler;import android.os.HandlerThread; Import Android.os.ibinder;import android.os.looper;import android.os.message;/** * Intentservice is a base class for {@li  NK Service}s that handle asynchronous * requests (expressed as {@link intent}s) on demand. Clients send requests * through {@link Android.content.context#startservicE (Intent)} calls;  The * service is started as needed, handles each Intent in turn using a worker * thread, and stops itself when it runs out of work.  * * <p>this "Work Queue processor" The pattern is commonly used to offload the tasks * from an application ' s main thread.  The Intentservice class exists to * simplify this pattern and take care of the mechanics.  To use it, extend * intentservice and implement {@link #onHandleIntent (Intent)}. Intentservice * would receive the Intents, launch a worker thread, and stop the service as * appropriate. * * <p>all Requests is handled on a single worker thread--they could take as * long as necessary (and would not bloc K The application ' s main loop), but * only one request would be processed at a time. * * <div class= "Special Reference" > * 
We look at the source of the 107--111 line:Intentservice internally implements a thread that handlerthread with a looping message processing mechanism. Refer to the Android Handlerthread source code analysis for Handlerthread and how to use it. As a result, intentservice internally also implements a thread with a looping message processing mechanism. See how the time-consuming task of our client is passed to Intentservice's internal handlerthread thread execution? Every time we start a service, we execute a onstartcommand.
We look at the source of 130 lines:the OnStart method was called.
We look at the source of the 115--120 line:The implementation of the OnStart method, in this method, we encapsulate the client passes over the Intent, passing it through the Handler + message processing mechanism mservicehandler.sendmessage (msg); The time-consuming task of passing to the Handlerthread child thread to perform the client. Let's see how Mservicehandler is implemented.
Source Line 58--68:implements the Mservicehandler, constitutes a Handler + message + Looper loop message processing mechanism.
Source Line 65th:called the Onhandlerintent abstract method with the client's intent message parameter, which leaves the subclass to implement the corresponding asynchronous time-consuming task. Therefore, the Intentservice subclass that we inherit must implement the Onhandlerintent abstract method.
Source line 66th:the Stopself () method is called, and the Servvice is stopped automatically when the asynchronous task finishes executing. Therefore, our clients do not have to manually stop the service themselves.
Intentservice Summary:
Intentservice Analysis is complete,1. In fact, the internal implementation of a handlerthread+handler with a loop message processing mechanism to deal with the background of the time-consuming task, without the user to implement a thread to perform time-consuming tasks. 2. And after the task executes, it automatically calls Stopself to stop the service, without the client to manually manage the service, and the client simply starts the task again when it needs to perform the asynchronous background time-consuming task. 3. If you know something about Handlerthread, you'll see why Intentservice performs asynchronous tasks in sequential order and can only perform one task at a time. Because Handlerthread + Handler is a single worker thread, that is, when the client is running two asynchronous tasks at the same time, only the previous task is completed before the next task is executed, and the second task is blocking the wait. However, it is executed in a child thread and does not affect the UI thread, and there is no ANR.

Android Intentservice Source Analysis

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.