[Android] Intentservice use of detailed understanding and example introduction

Source: Internet
Author: User

Intentservice definition

Intentservice inheritance and service, used to process asynchronous requests. The client can pass the request to Intentservice through the StartService (Intent) method. Intentservice opens a thread in the OnCreate () function to process all the tasks of the intent request object in turn by Handlerthread.
  
This would prevent the transaction from blocking the main thread (ANR). After executing the work for the intent request object, if no new intent request is reached, the * * automatically stops the **service; 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 directly implement the virtual function onhandleintent, It is possible to do different transactions on the inside according to the different intent.
In addition, Intentservice implements the Onbind () method by default, and the return value is null.

There are two ways to implement using Intentservice:
  

    • constructor function

      The constructor for the Intentservice must be a constructor with an empty argument , and then call Super ("name") in the 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

    • Implement virtual function Onhandleintent

      Different transactions are performed on the inside according to the different intent.
        
      Benefit: When dealing with asynchronous requests, you can reduce the amount of code written and make it easier to implement the project's requirements.

The difference between Intentservice and service

Service is not a standalone process, nor is it a standalone thread, it relies on the main thread of the application, it is not recommended to write time-consuming logic and operations in the service, otherwise it will cause ANR.

Intentservice it creates a separate worker thread to handle all the intents that pass through Onstartcommand () to the service (inserting intent into the work queue). Send intent to Onhandleintent () one by one through the work queue.
  
You do not need to actively call STOPSELFT () to end the service. Because, after all intent are processed, the system automatically shuts down the service.

The default implementation of Onbind () returns NULL.

Intentservice Example Introduction

First, Myintentservice.java.

 Public  class myintentservice extends intentservice {    //------------------must be implemented-----------------------------     Public Myintentservice() {Super("Myintentservice");//Note the constructor parameter is empty, and this string is the name of the worker thread}@Override    protected void onhandleintent(Intent Intent) {//different transaction processing according to the different intentString taskname = Intent.getextras (). GetString ("TaskName");Switch(TaskName) { Case "Task1": LOG.I ("Myintentservice","Do Task1"); Break; Case "Task2": LOG.I ("Myintentservice","Do Task2"); Break;default: Break; }           }//--------------------for the print life cycle--------------------   @Override   Public void onCreate() {LOG.I ("Myintentservice","OnCreate");Super. OnCreate ();}@Override     Public int Onstartcommand(Intent Intent,intFlagsintStartid) {LOG.I ("Myintentservice","Onstartcommand");return Super. Onstartcommand (Intent, flags, Startid); }@Override     Public void OnDestroy() {LOG.I ("Myintentservice","OnDestroy");Super. OnDestroy (); }}

Then remember to register the service in the Manifest.xml

<service android:name=".myIntentService">            <intent-filter >                  <action android:name="cn.scu.finch"/>              </intent-filter>             </service>

Finally, open the service in activity

 Public  class mainactivity extends Activity {    @Override    protected void onCreate(Bundle savedinstancestate) {//TODO auto-generated method stub        Super. OnCreate (Savedinstancestate);//The same service will only open a worker thread and process the intent request sequentially in the Onhandleintent function. Intent i =NewIntent ("Cn.scu.finch"); Bundle bundle =NewBundle (); Bundle.putstring ("TaskName","Task1");          I.putextras (bundle);          StartService (i); Intent i2 =NewIntent ("Cn.scu.finch"); Bundle Bundle2 =NewBundle (); Bundle2.putstring ("TaskName","Task2");          I2.putextras (Bundle2);         StartService (I2); StartService (i);//Multiple start-up}}

Operation Result:

 

Intentservice opens a thread in the OnCreate () function to process all the tasks of the intent request object in turn by Handlerthread.
  
Passed to the service via Onstartcommand () intent is inserted sequentially into the work queue. The work queue then sends intent one by one to Onhandleintent ().

Attention:
It has only one worker thread, the name is the string of the constructor, that is, "Myintentservice", we know that the service is opened multiple times, only one OnCreate method is called (Creating a worker thread), Multiple Onstartcommand methods (for incoming intent to be processed through the work queue and then sent to the Onhandleintent function).

[Android] Intentservice use of detailed understanding and example introduction

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.