Most people have probably only heard of Service or only used Service. IntentService is not used. IntentService is a subclass of Service. It is designed to be easier to call and runs in HandlerThread by default without opening a new thread. Ok down and began to learn to understand their differences and usage (first please make sure you have the basic knowledge of the Service if you don’t have god can see guo this article http://blog.csdn.net/guolin_blog/article/details/11952435)

IntentService is much simpler to use than Service. It is enough to inherit the IntentService constructor and override the onHandleIntent method. You can start IntentService using the StartService method as if it were a Service(don’t forget to register the Service in androidmanifest.xml, of course).

Public class MyIntentService extends IntentService {/** * the constructor must be created. MyIntentService is the name of the worker threadMyIntentService() {
      super("MyIntentService"); Override protected void onHandleIntent(Intent Intent) {// Override protected void onHandleIntent(Intent Intent) {// Override protected void onHandleIntent(Intent Intent) {// Override protected void onHandleIntent(Intent Intent) {// Override protected void onHandleIntent(Intent Intent);Copy the code

If you just want to know how it works you don’t have to read it, okay

IntentService: IntentService: IntentService: IntentService: IntentService: IntentService: IntentService: IntentService

  • By default, HandlerThread does not need to open a new thread
  • Process tasks in a queue
  • Services are automatically terminated after tasks are completed

You can see that HandlerThread and Handler are created in the onCreate method, and the name of the HandlerThread is the argument in our constructor. So that makes it clear why you don’t need to create a new thread, right

We all know that a Service will never be created again if it exists. It’s calling the onStartCommand method so if you look at the onStartCommand method it’s adding a new Intent to the queue using message. This also explains why tasks are executed one by one with IntentService.

OnHandleIntent () : if the task id is the last one, stop the service. The onDestroy method calls mServicelooper.quit (); Method to clear tasks

At this point. The veil of IntentService is lifted. The source code is also very simple.