Intentservice Source Code Analysis

Source: Internet
Author: User

What is 1.IntentService used for?

In general, the service is run in the main thread, so if processing time-consuming operations can cause ANR problems, but in many scenarios we need to use service for time-consuming operations, a new mechanism is needed, and the concept of Intentservice is introduced.
Let's take a look at the official story.

Intentservice is a base class for Services this handle asynchronous requests (expressed as Intents) on demand. Clients send requests through 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.
This "Work queue processor" pattern was commonly used to offload the tasks from a 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 Onhandleintent (Intent). Intentservice would receive the Intents, launch a worker thread, and stop the service as appropriate.
All requests is handled on a single worker Thread-they could take as long as necessary (and would not block the Applic Ation ' s main loop), but only one request would be processed at a time.

To summarize, it is intentservice in order to meet the following requirements of the scene.

    • Handling Asynchronous requests
    • End automatically after processing requests
2. How to achieve the above requirements? 2.1 Asynchronous processing time-consuming tasks

Take a look at the members of Intentservice first:

 Public Abstract  class intentservice extends Service {Private volatileLooper Mservicelooper;Private volatileServicehandler Mservicehandler;PrivateString Mname;Private BooleanMredelivery;//......}

As you can see here, Intentservice uses the handler mechanism to implement asynchronous
Down into its life cycle.

Public   void onCreate() {//Todo:it would is nice to having an option to hold a partial wakelock    //during processing, and to has a static StartService (Context, Intent)    //method that would launch the service & hand off a wakelock.    Super. OnCreate (); Handlerthread thread =NewHandlerthread ("intentservice["+ Mname +"]");    Thread.Start ();    Mservicelooper = Thread.getlooper (); Mservicehandler =NewServicehandler (mservicelooper);}Public   void onStart(Intent Intent, int startid) {Message msg = Mservicehandler.obtainmessage ();    MSG.ARG1 = Startid;    Msg.obj = Intent; Mservicehandler.sendmessage (msg);}Public   void OnDestroy() {Mservicelooper.quit ();}

As can be seen here, the asynchronous mechanism is initialized with Handlerthread in OnCreate, and the intent parameter is obtained in the OnStart method and placed in the message.
And then there's the handler I wrote in my last blog, and here we take a look at the implementation of the custom Servicehandler here:

Private Final  class servicehandler extends Handler {Public   servicehandler(Looper Looper) {Super(Looper); }@Override    Public   void handlemessage(Message msg) {onhandleintent (Intent) msg.obj);    Stopself (MSG.ARG1); }}

As you can see in the previous create method, we called the constructor, which is associated with the looper of the current thread and handler.
In the Handlermessage method, we first call the Onhandlerintent method to process the message containing the intent

  protected abstract void onHandleIntent(Intent intent);

When implementing Intentservice, you need to override the Onhandleinent method.

2.2 Self-stop function

After executing the processing method, call the Stopself method, terminate the Service,stopself method implemented in its parent class service, and use Activitymanager for the stop operation.
Because the servicehandler here is associated with the current looper, it works in the current thread, processing only one request at a time, and if subsequent requests reach that thread, block in the message queue, and call the Stopself method to stop itself when all requests have been processed. Because of this requirement, Intentservice is not suitable for multiple requests at the same time, and is suitable for responding to a single time-consuming request such as offline data download.

Public   final void stopself(int startid) {if(Mactivitymanager = =NULL) {return; }Try{Mactivitymanager.stopservicetoken (NewComponentName ( This, Mclassname), Mtoken, Startid); }Catch(RemoteException ex) {    }}

In summary, Intentservice constructs a message using the intent pass parameter, and then processes the message through the handler mechanism, enabling asynchronous processing. Call stopself after processing to stop automatically.
This feature allows us to perform time-consuming operations asynchronously in the service and stop ourselves.

?

Intentservice Source Code 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.