Android interview, the principle and use of intentservice

Source: Internet
Author: User

In Android development, we may encounter such a business need, a task is divided into several sub-tasks, sub-tasks executed sequentially, after the completion of all subtasks, the task is only successful. Then, it is possible to do this with a few sub-threading sequence execution, but each thread must be manually controlled, and another child thread will be opened after one of the sub-threads has finished executing. Or, put them all in one thread and let them execute sequentially. This can be done, however, if this is a background task, you have to put in the service, because the service and activity are peer, so to perform time-consuming tasks, you have to open a sub-thread in the service to execute. So, is there a simple way to deal with this process, the answer is Intentservice.

What is Intentservice,intentservice is a class that inherits from the service and processes an asynchronous request, and within Intentservice there is a worker thread to handle the time-consuming operation, Starting the Intentservice is the same as starting a traditional service, and when the task is finished, Intentservice will stop automatically without the need for manual control. In addition, you can start intentservice multiple times, and each time-consuming operation is performed in the Onhandleintent callback method of Intentservice in the form of a work queue, and only one worker thread is executed at a time, and then the second executes the first one, and so on.   All requests are in one single thread and do not block the application's main thread (UI Thread), and only one request is processed at a time.   So what are the benefits of using Intentservice? First, we eliminate the hassle of manual threads in the service, and second, we don't have to stop the service manually when the operation is complete.  code                                                          ,         &N Bsp                 next let's take a look at how to use it, I wrote a demo to simulate two time-consuming operations, Operation1 and Operation2, You must wait 1 to execute before you can perform:  new project, create a new class that inherits Intentservice, I'm intentservicedemo.java public class. Intentservicedemo extends Intentservice {       public Intentservicedemo () {   & nbsp   &nbsp You must implement the parent class's construction method          Super ("Intentservicedemo");                 @Override      public IBinder Onbind Tent Intent) {         SYSTEM.OUT.PRINTLN ("Onbind"),          return su Per.onbind (Intent);               @Override      public void OnCreate () {& nbsp;        SYSTEM.OUT.PRINTLN ("onCreate");          super.oncreate ();             @Override      public void OnStart (Intent Intent, int Startid) {         SYSTEM.OUT.PRINTLN ("OnStart"),          Super.onsta RT (Intent, Startid);               @Override      public int Onstartcommand (Intent Intent, int flags, inT Startid) {         SYSTEM.OUT.PRINTLN ("Onstartcommand"),          RET Urn Super.onstartcommand (Intent, flags, Startid);               @Override      public void Setintentredelivery (Boolean enabled) {         super.setintentredelivery (enabled);           SYSTEM.OUT.PRINTLN ("Setintentredelivery");             @Override      protected void onhandleintent (Intent Intent) {        //intent is from activity, carry identification parameters, perform different tasks according to parameters          String action = Intent.getextras (). getString ("param");          if (action.equals ("Oper1")) {             System.out . println ("Operation1");         }else if (action.equals ("Oper2")) {            SYSTEM.OUT.PRINTLN ("Operation2");         }                    try {              Thread.Sleep (2000);         } catch (Interruptedexception e) {             E.PRI Ntstacktrace ();         }     }        @Override      PU Blic void OnDestroy () {         SYSTEM.OUT.PRINTLN ("OnDestroy"),        &NBS P Super.ondestroy ();         } I've printed out the life cycle method, and we'll see how it performs. Next is activity, in activity to start Intentservice: public class Testactivity extends activity {    /** Called when the activity is first created. */     @Override      public void onCreate (Bundle savedinstancestate) {   &NBsp     Super.oncreate (savedinstancestate);          Setcontentview (R.layout.main);                   //can be started multiple times, each time you start, you will create a new work thread, However, Intentservice instances always have only one         //operation 1          Intent Startserv Iceintent = new Intent ("Com.test.intentservice");          Bundle bundle = new bundle ();          bundle.putstring ("param", "oper1");          Startserviceintent.putextras (bundle);          StartService (startserviceintent);                   //operation 2          Intent StartServiceIntent2 = new Intent ("Com.test.intentservice");          Bundle bundle2 = new bundle ();          bundle2.putstring ("param", "oper2");          Startserviceintent2.putextras (bundle2);          StartService (STARTSERVICEINTENT2);       } Copy the code Finally, do not forget to configure the service, because it inherits from the service, so it is a service, must be configured, otherwise it will not work, I just forget, the results half a day did not respond.  <service android:name= ". Intentservicedemo >              <intent-filter >        & nbsp         <action android:name= "Com.test.intentservice"/>          & nbsp   </intent-filter>          </service> Last look at the results: 1 from the result you can see that the OnCreate method only executes once, The Onstartcommand and OnStart methods were executed two times, and two work Thread was opened, which confirmed what was said earlier, started several times, but only one instance of Intentservice, which is the same as the traditional service. Operation1 also before Operation2 printing, and I let two operations between the pause 2s, and finally OnDestroy destroyed Intentservice.

Android interview, the principle and use of intentservice

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.