24

What is the difference between Service and an IntentService in Android?

What is the difference between AsyncTask and an IntentService in Android?

GreenROBO
  • 4,725
  • 4
  • 23
  • 43
vijaycaimi
  • 317
  • 1
  • 2
  • 6

1 Answers1

35

1. Difference between Service and IntentService

Service: It is the base class for the Android services, that you can extend for creating any service. Since the service run inside the UI thread, it requires that you create a working thread for executing its work.

IntentService: it is a subclass of Service, that simplifies your work. It works already in a working thread, and can receive asynchronous requests. So, you don't need to create it manually, or to worry about synchronization. You can simply extend it and override the method:

onHandleIntent(Intent intent)

where you can manage all the incoming requests.

Taking a look at the documentation, you can see in details what the IntentService do for you:

  • Creates a default worker thread that executes all intents delivered to onStartCommand() separate from your application's main thread.
  • Creates a work queue that passes one intent at a time to your onHandleIntent() implementation, so you never have to worry about multi-threading.
  • Stops the service after all start requests have been handled, so you never have to call stopSelf().
  • Provides default implementation of onBind() that returns null.
  • Provides a default implementation of onStartCommand() that sends the intent to the work queue and then to your onHandleIntent() implementation.

So, if you need more control you can use the Service class, but often for a simple service the best solution is the IntentService.

2. Difference between AsyncTask and Service

They are two different concepts.

Service: can be intended as an Activity with no interface. It is suitable for long-running operations.

AsyncTask: is a particular class that wraps a working thread (performing background operations), facilitating the interaction with the UI Thread, without managing threads or handlers directly.

Community
  • 1
  • 1
GVillani82
  • 17,196
  • 30
  • 105
  • 172
  • 1
    There are nice explanation here http://stackoverflow.com/a/15772151/1533670 – Yohanim May 10 '17 at 02:42
  • This explanation is nice but if you could go into some more detail on AsyncTask (especially the downsides) it would be better. – Mike Vella Nov 23 '17 at 10:55
  • There is quite a lot to say about `AsyncTask`, and there is the documentation for that. I tried to keep it short just pointing out the differences with the `Service` – GVillani82 Nov 23 '17 at 10:59