I am seeking an example of something that can be done with an IntentService
that cannot be done with a Service
(and vice-versa)?
I also believe that an IntentService
runs in a different thread and a Service
does not. So, as far as I can see, starting a service within its own thread is like starting an IntentService
. Is that correct?
Service class uses the application's main thread, while IntentService creates a worker thread and uses that thread to run the service. IntentService creates a queue that passes one intent at a time to onHandleIntent() . Thus, implementing a multi-thread should be made by extending Service class directly.
Service : is a component of android which performs long running operation in background, mostly with out having UI. Thread : is a O.S level feature that allow you to do some operation in the background.
IntentService is an extension of the Service component class that handles asynchronous requests (expressed as Intent s) on demand. Clients send requests through Context.
You can think Service as an Android component that is used to perform some long-running operations in the background like that in the Music app, where we run the app in the background and use other applications of the mobile parallelly.
Tejas Lagvankar wrote a nice post about this subject. Below are some key differences between Service and IntentService.
When to use?
The Service can be used in tasks with no UI, but shouldn't be too long. If you need to perform long tasks, you must use threads within Service.
The IntentService can be used in long tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. Another case of use is when callbacks are needed (Intent triggered tasks).
How to trigger?
The Service is triggered by calling method startService()
.
The IntentService is triggered using an Intent, it spawns a new worker thread and the method onHandleIntent()
is called on this thread.
Triggered From
Runs On
The Service runs in background but it runs on the Main Thread of the application.
The IntentService runs on a separate worker thread.
Limitations / Drawbacks
The Service may block the Main Thread of the application.
The IntentService cannot run tasks in parallel. Hence all the consecutive intents will go into the message queue for the worker thread and will execute sequentially.
When to stop?
If you implement a Service, it is your responsibility to stop the service when its work is done, by calling stopSelf()
or stopService()
. (If you only want to provide binding, you don't need to implement this method).
The IntentService stops the service after all start requests have been handled, so you never have to call stopSelf()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With