The principle and use of Intentservice in Android

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, first look at the official explanation:

Intentservice is a base class forServiceS, handle asynchronous requests (expressed asIntents) on Dem and. Clients send requests throughStartService (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

Simply put, Intentservice is a class that inherits from the service and processes asynchronous requests, and within Intentservice there is a worker thread to handle the time-consuming operation, starting the Intentservice in the same way as the traditional service, and When the task is finished, the Intentservice will stop automatically without the need for us to manually control it. 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.

There is also a note:

All requests is handled on a single worker thread--they could take as long as necessary (and would not block the Applicati On ' s main loop), but only one request would be processed at a time.

The general meaning is that 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 omit the hassle of manual threads in the service, and second, when the operation is complete, we do not have to stop the service manually, third, it's so easy to use!

OK, next let's take a look at how to use, I wrote a demo to simulate two time-consuming operations, Operation1 and Operation2, first execute must wait 1 execution to execute:

New project, create a new class that inherits Intentservice, I'm Intentservicedemo.java here.

1  Public classIntentservicedemoextendsIntentservice {2 3      PublicIntentservicedemo () {4         //you must implement the parent class's construction method5         Super("Intentservicedemo");6     }7     8 @Override9      Publicibinder onbind (Intent Intent) {TenSystem.out.println ("Onbind"); One         return Super. Onbind (intent); A     } -  -  the @Override -      Public voidonCreate () { -System.out.println ("OnCreate"); -         Super. OnCreate (); +     } -  + @Override A      Public voidOnStart (Intent Intent,intStartid) { atSystem.out.println ("OnStart"); -         Super. OnStart (Intent, startid); -     } -  -  - @Override in      Public intOnstartcommand (Intent Intent,intFlagsintStartid) { -System.out.println ("Onstartcommand"); to         return Super. Onstartcommand (Intent, flags, startid); +     } -  the  * @Override $      Public voidSetintentredelivery (Booleanenabled) {Panax Notoginseng         Super. Setintentredelivery (enabled); -System.out.println ("Setintentredelivery"); the     } +  A @Override the     protected voidonhandleintent (Intent Intent) { +         //intent is sent from the activity, carry the identification parameters, according to different parameters to perform different tasks -String action = Intent.getextras (). getString ("param"); $         if(Action.equals ("Oper1")) { $System.out.println ("Operation1"); -}Else if(Action.equals ("Oper2")) { -System.out.println ("Operation2"); the         } -         Wuyi         Try { theThread.Sleep (2000); -}Catch(interruptedexception e) { Wu e.printstacktrace (); -         } About     } $  - @Override -      Public voidOnDestroy () { -System.out.println ("OnDestroy"); A         Super. OnDestroy (); +     } the  -}
View Code

I've printed out the life cycle method, and then we'll see how it performs. Next is the activity, which starts the intentservice in the activity:

1  Public classTestactivityextendsActivity {2     /**Called when the activity is first created.*/3 @Override4      Public voidonCreate (Bundle savedinstancestate) {5         Super. OnCreate (savedinstancestate);6 Setcontentview (r.layout.main);7         8         //can be started multiple times, each time you start, a new work thread is created, but the Intentservice instance always has only one9         //Operation 1TenIntent startserviceintent =NewIntent ("Com.test.intentservice"); OneBundle bundle =NewBundle (); ABundle.putstring ("param", "oper1"); - Startserviceintent.putextras (bundle); - StartService (startserviceintent); the          -         //Operation 2 -Intent StartServiceIntent2 =NewIntent ("Com.test.intentservice"); -Bundle Bundle2 =NewBundle (); +Bundle2.putstring ("param", "oper2"); - Startserviceintent2.putextras (bundle2); + StartService (startServiceIntent2); A     } at}
View Code

Finally, don't forget to configure the service because it inherits from the service, so it's still a service.

1 <service android:name= ". Intentservicedemo ">2             <intent-filter >3                 <action android:name=" Com.test.intentservice "/>4             </intent-filter>5         </service>
View Code

OK, and finally take a look at the results:


As you can see from the results, the OnCreate method executes only once, and the Onstartcommand and OnStart methods execute two times, opening two work Thread, which confirms what was said earlier, starts several times, but the Intentservice instance has only one, This 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.

This is Intentservice, a class that allows us to handle business processes, which is a service, but smarter than service.

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.