Service vs IntentService in the Android platform
Solution 1
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
- The Service and IntentService may be triggered from any thread, activity or other application component.
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()
orstopService()
. (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()
.
Solution 2
If someone can show me an example of something that can be done with an
IntentService
and can not be done with aService
and the other way around.
By definition, that is impossible. IntentService
is a subclass of Service
, written in Java. Hence, anything an IntentService
does, a Service
could do, by including the relevant bits of code that IntentService
uses.
Starting a service with its own thread is like starting an IntentService. Is it not?
The three primary features of an IntentService
are:
the background thread
the automatic queuing of
Intent
s delivered toonStartCommand()
, so if oneIntent
is being processed byonHandleIntent()
on the background thread, other commands queue up waiting their turnthe automatic shutdown of the
IntentService
, via a call tostopSelf()
, once the queue is empty
Any and all of that could be implemented by a Service
without extending IntentService
.
Solution 3
Service
- Invoke by
startService()
- Triggered from any
Thread
- Runs on
Main Thread
- May block main (UI) thread. Always use thread within service for long task
- Once task has done, it is our responsibility to stop service by calling
stopSelf()
orstopService()
IntentService
- It performs long task usually no communication with main thread if communication is needed then it is done by
Handler
orBroadcastReceiver
- Invoke via
Intent
- Triggered from
Main Thread
- Runs on the separate thread
- Can't run the task in parallel and multiple intents are Queued on the same worker thread.
Solution 4
Don't reinvent the wheel
IntentService extends Service class which clearly means that IntentService
is intentionally made for same purpose.
So what is the purpose ?
`IntentService's purpose is to make our job easier to run background tasks without even worrying about
Creation of worker thread
Queuing the processing multiple-request one by one (
Threading
)- Destroying the
Service
So NO, Service
can do any task which an IntentService
would do. If your requirements fall under the above-mentioned criteria, then you don't have to write those logics in the Service
class.
So don't reinvent the wheel because IntentService
is the invented wheel.
The "Main" difference
The Service runs on the UI thread while an IntentService runs on a separate thread
When do you use IntentService?
When you want to perform multiple background tasks one by one which exists beyond the scope of an Activity then the IntentService
is perfect.
How IntentService
is made from Service
A normal service runs on the UI Thread(Any Android Component type runs on UI thread by default eg Activity
, BroadcastReceiver
, ContentProvider
and Service
). If you have to do some work that may take a while to complete then you have to create a thread. In the case of multiple requests, you will have to deal with synchronization
.
IntentService
is given some default implementation which does those tasks for you.
According to developer page
IntentService
creates a Worker ThreadIntentService
creates a Work Queue which sends request toonHandleIntent()
method one by one- When there is no work then
IntentService
callsstopSelf()
method - Provides default implementation for
onBind()
method which is null - Default implementation for
onStartCommand()
which sendsIntent
request to WorkQueue and eventually toonHandleIntent()
Solution 5
Adding points to the accepted answer:
See the usage of IntentService within Android API. eg:
public class SimpleWakefulService extends IntentService {
public SimpleWakefulService() {
super("SimpleWakefulService");
}
@Override
protected void onHandleIntent(Intent intent) { ...}
To create an IntentService component for your app, define a class that extends IntentService, and within it, define a method that overrides onHandleIntent().
Also, see the source code of the IntentService, it's constructor and life cycle methods like onStartCommand...
@Override
public int More ...onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
Service together an AsyncTask is one of best approaches for many use cases where the payload is not huge. or just create a class extending IntentSerivce. From Android version 4.0 all network operations should be in background process otherwise the application compile/build fails. separate thread from the UI. The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread. For more discussion of this topic, see the blog post
from Android developers guide:
IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(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.
Design pattern used in IntentService
: This "work queue processor" pattern is commonly used to offload tasks from an application's main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.
All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.
The IntentService class provides a straightforward structure for running an operation on a single background thread. This allows it to handle long-running operations without affecting your user interface's responsiveness. Also, an IntentService isn't affected by most user interface lifecycle events, so it continues to run in circumstances that would shut down an AsyncTask.
An IntentService has a few limitations:
It can't interact directly with your user interface. To put its results in the UI, you have to send them to an Activity. Work requests run sequentially. If an operation is running in an IntentService, and you send it another request, the request waits until the first operation is finished. An operation running on an IntentService can't be interrupted. However, in most cases
IntentService is the preferred way to simple background operations
**
Volley Library
There is the library called volley-library for developing android networking applications The source code is available for the public in GitHub.
The android official documentation for Best practices for Background jobs: helps better understand on intent service, thread, handler, service. and also Performing Network Operations
roiberg
Updated on July 08, 2022Comments
-
roiberg almost 2 years
I am seeking an example of something that can be done with an
IntentService
that cannot be done with aService
(and vice-versa)?I also believe that an
IntentService
runs in a different thread and aService
does not. So, as far as I can see, starting a service within its own thread is like starting anIntentService
. Is that correct? -
roiberg about 11 yearsYea, but what does it mean?! ends it self? If the service is not doing anything than its "done". isn't it? I mean, If a code in a service is doing something short and simple, than when the code is done than the service is also done.. or what?
-
roiberg about 11 yearsI didn't find one example that can be done with one and not with the other. just some explanations that didn't help me.
-
Stefan de Bruijn about 11 yearsTry this site, it has a lot of good explanation on basic Android concepts with decent examples vogella.com/articles/AndroidServices/article.html
-
roiberg about 11 yearsIts another example of "how to use". not when specifically use service and when intentservice. Please give me a theoretical example and not links to "how to use" or any other likns for that metter. I am not asking you to "work" for me while im doing nothing its just that I already saw all of those liks and still am not sure.
-
Stefan de Bruijn about 11 yearsUpdated answer with some short examples too.
-
pelotasplus about 11 yearsthat's pretty important difference. for example, if you use service to keep persistent connection with server, you cannot use intentservice for that as it's terminated right after it finishes all its tasks
-
roiberg about 11 yearsYea, now I get it!! Thanks!
-
edthethird over 10 yearsA little late, but I am finding that
Service
called withstartService
can only run for about 10 seconds before throwing an ANR-- anIntentService
started with broadcasting an intent doesn't seem to have this limitation -
CommonsWare over 10 years@edthethird: That is because you were tying up the main application thread. All lifecycle methods on all components, including
onStartCommand()
of aService
, are called on the main application thread. You cannot tie up this thread for more than a few milliseconds without freezing your UI, and if you take many seconds, you will get the service equivalent of an ANR. -
edthethird over 10 yearsyup I commented too soon. I was doing the work
onStartCommand
instead ofonHandleIntent
-- looks likeonStartCommand
is run on the UI thread, however a separate thread is spawned foronHandleIntent
execution. -
Lassi Kinnunen over 10 yearswhat seems is that most people who want to run a real long running service in the background end up trying to find about IntentService because the docs make it seem like that it is for doing that, But you could mostly be just as well using new Thread(new Runnable()).start(). in other words, when it speaks about "spawns a new thread" that is all it does, it does not move it to a separate process which is actually what most people look to do when they want to separate some running code out from the Activity!(because just spawning threads is a one liner anyways)
-
njzk2 over 10 yearsthe intentService also takes care of the life cycle of the thread, and uses a looper, which helps the scheduler. It also makes sure only one instance is running, and queues other calls.
-
Shirish Herwade almost 10 yearsshort and sweet, but its better if you edit your answer including points by CommonsWare, as lot of people only read accepted or most upvoted answers
-
José Juan Sánchez almost 10 years@Shiri Hrw: I have just edit the answer with a new point included by CommonsWare. Thanks for the advice!
-
Naresh Sharma almost 10 years@JoséJuanSánchez easily explained the whole concept of these two components.
-
Lou Morda over 9 yearswhen i google that, it brings me here. now i am in an infinite loop.
-
Darpan over 9 years"The service runs is background but runs on Main thread of app" - Help me understand this.
-
José Juan Sánchez over 9 years@Darpan A Service is an application component that can perform long-running operations in the background and does not provide a user interface. A service runs in the main thread of its hosting process. The Service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work.
-
Ashok Bijoy Debnath over 9 years"The IntentService must be triggered from Main Thread." Are you sure? Inside my MainActivity onCreate(), when I call an IntentService from a new Thread (code below), it still works for me. new Thread(new Runnable() { @Override public void run() { Intent intent = new Intent(context, HelloIntentService.class); startService(intent); } }).start();
-
José Juan Sánchez over 9 years@AshokBijoyDebnath You are right! The Services and IntentServices can be started from any thread, activity or other application component. I have just edit the text of the answer to fix this issue. Thank you for your edit suggestion! :)
-
IgorGanapolsky over 9 yearsIs stopSelf() something that the programmer has to call, or does the IntentService call that by itself?
-
CommonsWare over 9 years@IgorGanapolsky:
IntentService
calls that itself, afteronHandleIntent()
returns, if there is no more work to be done. -
pathe.kiran about 9 yearswhich service i should use to update my local application table continuously ? even my application is closed.
-
Arun almost 8 yearssuperb short explanation
-
José Juan Sánchez over 7 yearsNo problem, go for it!
-
David Wasser over 7 years"The Service runs in background but it runs on the Main Thread of the application." This is wrong. A
Service
is an object. It doesn't run on any Thread. The methods of aService
can run on any Thread, The lifecycle methods (onCreate()
,onStartCommand()
,onDestroy()
are called by the Android framework on the main (UI) Thread. When implementing aService
it is common to start your ownThread
s as worker or background threads and perform long-running operations on those threads.IntentService
is just an extenstion ofService
that does some of this for you. -
Shubham AgaRwal over 7 yearsi hope i could +1 again
-
eRaisedToX over 7 yearsIt could be better , if you could give short ,upto the point answer.
-
eRaisedToX over 7 years@CommonsWare ,what I don't understand is, in starting you've mentioned "IntentService is a subclass of Service" and then you wrote "could be implemented by a Service without extending IntentService" which confuses me of "which is super and which is sub class" kindly help.
-
CommonsWare over 7 years@eRaisedToX: The concept of superclasses and subclasses is a general Java concept, not unique to Android.
Service
is a Java class.IntentService
is a subclass ofService
. However, you can create other subclasses ofService
as well. -
Kugan Kumar almost 7 yearsservice: but shouldn't be too long, can you define "too long" in this context? is it 1min, 2min or 3min...... ? thank you
-
Laurent almost 7 yearsSo regarding this answer a Service is for short tasks and IntentService is for long task.... But if I check in the official doc for Service it says A Service is an application component that can perform long-running operations in the background. For IntentService it says they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time. . So both for long tasks ? not clear to me...
-
alizeyn over 6 years
"it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService()"
Well it's no quite true science now for apps which targeting API 26 and above. Background service is getting killed by OS when app isidle
. developer.android.com/about/versions/oreo/background.html -
Adil about 6 yearsgreat i find this ans last 1 hour
-
Ravindra Kushwaha almost 6 yearsOne question @JoséJuanSánchez ... Does IntentService finish as the application is removed from background or forground?As i know the Services runs even application is present or not on background and forground
-
Ravindra Kushwaha almost 6 yearsOne question @CommonsWare ... Does IntentService finish as the application is removed from background or forground?As i know the Services runs even application is present or not on background and forground
-
CommonsWare almost 6 years@RavindraKushwaha: I am uncertain exactly what you mean by "removed". If the user presses HOME or BACK, and the UI of the app is no longer in the foreground, the
IntentService
is unaffected. If Android terminates the process, theIntentService
goes away when the process does. And it is possible that you have something else in mind for "removed". -
Ravindra Kushwaha almost 6 years@CommonsWare Sir... I just want to ask that when Application is not on background and foreground also..Than Our IntentService also terminated or not...Like i know Service runs even the app is running or not until and unless system or we removed it.. Thanks sir for urs reply
-
CommonsWare almost 6 years@RavindraKushwaha: I am sorry, but I still do not understand what you mean. An
IntentService
is aService
. All normalService
rules apply. In addition, anIntentService
stops itself automatically when the work inonHandleIntent()
completes. Note thatIntentService
does not work especially well on Android 8.0+ -- please consider usingJobIntentService
or (in 2019 and beyond)WorkManager
for this sort of background work. -
Ravindra Kushwaha almost 6 yearsSir IntentService depends on Application is running or not?
-
CommonsWare almost 6 years@RavindraKushwaha: I do not know what you consider "Application is running or not" to mean, so I cannot answer that, sorry.
-
Ravindra Kushwaha almost 6 yearsSorry for bothering you...What a hell my English...You are not getting me..Thanks, sir anyway @CommonsWare
-
Ravindra Kushwaha almost 6 yearsOne last attemp.. Suppose i am downloading the file from server which will download after 1 hour and I am using the IntentService for it...During the downloading file , i have CLOSED the app (Not even running in background)....Than my question is that Does my IntentService also finishes OR not?
-
CommonsWare almost 6 yearsThe issue is not English, but programming. For example, "i have CLOSED the app" has no precise definition, so I cannot tell you what happens when that occurs. I also do not know how "i have CLOSED the app" relates to "will download after 1 hour". You might consider asking a separate Stack Overflow question, where you can provide a minimal reproducible example of "will download after 1 hour". There, you can explain in detail what "i have CLOSED the app" means (for example, what specifically does the user do to close the app?).
-
Ravindra Kushwaha almost 6 yearsok sir @CommonsWare Thanks a lot for urs suggestion.Again thanks sir :)
-
Wini over 3 years
When you want to perform multiple background tasks one by one which exists beyond the scope of an Activity then the IntentService is perfect.
==> can you give example ? -
Rohit Singh over 3 yearsDownloading songs one by one from a Playlist. @Wini
-
truthadjustr over 2 yearsAn IntentService can be also invoked by
startService
. Please edit your answer accordingly and make it coherent.