Can someone help me understand how to use Android Service or IntentService correctly. The documentation seems to contradict itself here:
Caution: A service runs in the same process as the application in which it is
declared and in the main thread of that application by default. If your service
performs intensive or blocking operations while the user interacts with an
activity from the same application, the service slows down activity performance.
To avoid impacting application performance, start a new thread inside the service.
and here
public class HelloIntentService extends IntentService {
/**
* A constructor is required, and must call the super IntentService(String)
* constructor with a name for the worker thread.
*/
public HelloIntentService() {
super("HelloIntentService");
}
/**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns, IntentService
* stops the service, as appropriate.
*/
#Override
protected void onHandleIntent(Intent intent) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
}
}
Given the whole purpose of the Service or ServiceIntent is to run long running jobs in the background without affecting the UI why then does the example code do exactly what the Caution indicated you should not do - and I am assuming a call to Thread.sleep() will cause the main thread to block.
Am I correct in the following understanding:
The service itself still runs on the main application thread but has no UI component (Activity) and will continue running even if the application is not used by the user, unlike an Activity which will not
Any long running background work must still create a separate thread to avoid blocking the main application thread
AsyncTask is associated with an Activity which presumably will stop running if the application is no longer the active application (i.e. if the user switches to another application) which is why one would use Service or ServiceIntent if the task needs to keep running.
IntentService will run the task on a separate thread to the main thread so there is no need to worry about blocking the main thread with long tasks or when calling Thread.sleep().
Have I misunderstood something with the description of Android Service or ServiceIntents?
Your first comment is from the the documentation about services in general.
There is nothing in Android named ServiceIntent. Your code snippet is an IntentService.
In Java, we have classes and inheritance. Service is the base class from which all services inherit. IntentService extends Service.
If you call startService(), pointing to a class of yours that inherits directly from Service, you need to implement a background thread yourself, as Service will not do that for you.
If, however, you call startService(), pointing to a class of yours that inherits from IntentService, then you will get a background thread created for you automatically by IntentService. This is code added by IntentService, above and beyond what Service provides.
and I am assuming a call to Thread.sleep() will cause the main thread to block.
No, because onHandleIntent() is called on the IntentService-supplied background thread.
The service itself still runs on the main application thread
No. In Java, objects do not run on threads. Methods run on threads.
Any long running background work must still create a separate thread to avoid blocking the main application thread
Any long-running background work needs to be performed on a background thread. Whether that is a thread that you create (e.g., in a direct subclass of Service) or whether it is a thread that is provided to you (e.g., in a direct subclass of IntentService) varies.
AsyncTask is associated with an Activity which presumably will stop running if the application is no longer the active application
The primary role of a service is to tell Android that we are doing background work that should continue for a while, even if the app's UI moves to the background. That is because Android will terminate your process eventually, to free up system RAM for other apps.
Using a service will tend to keep your process around for a little while longer. An AsyncTask, or a bare Thread, does not do this. When the app's UI moves to the background, your process is not terminated immediately, but it may be terminated soon, and so if you want greater assurance that your work will get done, you use a service to manage that work.
Related
In a recent answer, I read
A service does not run on its own thread, it runs on the UI thread
I've read similar statements in many other service-related questions.
If I call startService() from an Activity, will the Service run on the Activity's UI Thread or does it spawn a new process with it's own UI Thread?
If it runs on the Activity's UI Thread, doesn't that risk making the Activity unresponsive?
Yes services does run on main thread , About ANR(application not responding ) concern , there will higher chances of ANRs if your service is doing a long processing work using CPU so the official docs also recommends to use Worker Threads for efficiency. docs
You must read the caution paragraph in the docs to confirm
If your task is one time shot then Use IntentService which implicitly use threading mechanism for processing but IntentService will destroy itself automatically when the task is done so you will have to start it again for the next time and so.
android:process : Using this to start a service in an another process will cause usage of more memory. This will cause creating two processes for your app in separate heap memory space which also require other maintenance as well.So this is rarely used and i would not recommend to use this for a regular service task.
If I call startService() from an Activity, will the Service run on
the Activity's UI Thread or does it spawn a new process with it's
own UI Thread?
If it's a Service (not an IntentService), it will run on the main Thread of your app's process, as long as you do not define it as a separate process explicitly (by adding the android:process tag in the Manifest).
If it runs on the Activity's UI Thread, doesn't that risk making the
Activity unresponsive?
Yes it does, if you perform CPU intensive/blocking operations.
To prevent that, you can either start new Thread(s) from your Service, or use an IntentService, which will automatically spawn a new worker Thread for its work.
From the Services Docs it clearly explains your answer.
Caution: 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. By using a separate thread, you
will reduce the risk of Application Not Responding (ANR) errors and
the application's main thread can remain dedicated to user interaction
with your activities.
In a recent answer, I read
A service does not run on its own thread, it runs on the UI thread
This is just plain wrong. A Service is an object (an instance of a class). It doesn't run on any thread, it doesn't run at all. It just "is". The methods of the Service may run on any thread, depending...
Specifically, the lifecycle methods of a Service (onCreate(), onStartCommand(), etc.) that are called directly from the Android framework run on the main (UI) thread, which may or may not be the same thread that called startService(). However, a Service can (and usually does) start other background threads, as many as it needs to, to perform the necessary work.
If I call startService() from an Activity, will the Service run on the
Activity's UI Thread or does it spawn a new process with it's own UI
Thread?
See above. If you want your Service to run in a separate process, you can do this by specifying android:process=":service" in the <service> declaration in the manifest. By default, services run in the same process as the other components (Activity, BroadcastReceiver, etc.) of your application.
If it runs on the Activity's UI Thread, doesn't that risk making the
Activity unresponsive?
That depends on what your Service is doing! Obviously if your Service is doing a lot of compute-intensive processing on the UI thread it will make your app unresponsive. If your Service is doing I/O on the UI thread, Android will usually throw exceptions (in more recent versions of Android). This is the reason that services usually start background threads to do work. However, if your Service is lightweight, then there is no reason why methods of your Service cannot run on the UI thread. As I said, it depends...
IntentService runs on the background thread, so, if you want to do one-off tasks then use that.
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?
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() 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 someone can show me an example of something that can be done with an IntentService and can not be done with a Service 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 Intents delivered to onStartCommand(), so if one Intent is being processed by onHandleIntent() on the background thread, other commands queue up waiting their turn
the automatic shutdown of the IntentService, via a call to stopSelf(), once the queue is empty
Any and all of that could be implemented by a Service without extending IntentService.
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() or stopService()
IntentService
It performs long task usually no communication with main thread if communication is needed then it is done by Handler or BroadcastReceiver
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.
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 Thread
IntentService creates a Work Queue which sends request to onHandleIntent() method one by one
When there is no work then IntentService calls stopSelf() method
Provides default implementation for onBind() method which is null
Default implementation for onStartCommand() which sends Intent request to WorkQueue and eventually to onHandleIntent()
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
I'm sure you can find an extensive list of differences by simply googling something such as 'Android IntentService vs Service'
One of the more important differences per example is that IntentService ends itself once it's done.
Some examples (quickly made up) could be;
IntentService: If you want to download a bunch of images at the start of opening your app. It's a one-time process and can clean itself up once everything is downloaded.
Service: A Service which will constantly be used to communicate between your app and back-end with web API calls. Even if it is finished with its current task, you still want it to be around a few minutes later, for more communication.
IntentService
IntentService runs on its own thread.
It will stop itself when it's done. More like fire and forget.
Subsequent calls will be queued. Good for queuing calls.
You can also spin multiple threads within IntentServiceif you need to- You can achieve this using ThreadPoolExecutor.
I say this because many people asked me "why use IntentService since it doesn't support parallel execution".
IntentService is just a thread. You can do whatever you need inside it- Even spinning multiple threads. The only caveat is that IntentService finishes as soon as you spin those multiple threads. It doesn't wait for those threads to come back. You need to take care of this. So I recommend using ThreadPoolExecutor in those scenarios.
Good for Syncing, uploading etc …
Service
By Default Service runs on the main thread. You need to spin a worker thread to do your job.
You need to stop service explicitly.
I used it for a situation when you need to run stuff in the background even when you move away from your app and come back more for a Headless service.
Again you can run multiple threads if you need to.
Can be used for apps like music players.
You can always communicate back to your activity using BroadcastReceivers if you need to.
An IntentService is an extension of a Service that is made to ease the execution of a task that needs to be executed in background and in a seperated thread.
IntentService starts, create a thread and runs its task in the thread. once done, it cleans everything. Only one instance of a IntentService can run at the same time, several calls are enqueued.
It is very simple to use and very convenient for a lot of uses, for instance downloading stuff. But it has limitations that can make you want to use instead the more basic (not simple) Service.
For example, a service connected to a xmpp server and bound by activities cannot be simply done using an IntentService. You'll end up ignoring or overriding IntentService stuffs.
Android IntentService vs Service
1.Service
A Service is invoked using startService().
A Service can be invoked from any thread.
A Service runs background operations on the Main Thread of the
Application by default. Hence it can block your Application’s UI.
A Service invoked multiple times would create multiple instances.
A service needs to be stopped using stopSelf() or stopService().
Android service can run parallel operations.
2. IntentService
An IntentService is invoked using Intent.
An IntentService can in invoked from the Main thread only.
An IntentService creates a separate worker thread to run background
operations.
An IntentService invoked multiple times won’t create multiple
instances.
An IntentService automatically stops after the queue is completed. No
need to trigger stopService() or stopSelf().
In an IntentService, multiple intent calls are automatically Queued
and they would be executed sequentially.
An IntentService cannot run parallel operation like a Service.
Refer from Here
If someone can show me an example of something that you can be done with an IntentService and can not be done with a service and the other way around.
IntentService can not be used for Long Time Listening, Like for XMPP Listeners, its a single time operator, do the job and wave goodbye.
Also it has just one threadworker, but with a trick, you can use it as unlimited.
The Major Difference between a Service and an IntentService is described as follows:
Service :
1.A Service by default, runs on the application's main thread.(here no default worker thread is available).So the user needs to create a separate thread and do the required work in that thread.
2.Allows Multiple requests at a time.(Multi Threading)
IntentService :
1.Now, coming to IntentService, here a default worker thread is available to perform any operation. Note that - You need to implement onHandleIntent() method ,which receives the intent for each start request, where you can do the background work.
2.But it allows only one request at a time.
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?
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() 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 someone can show me an example of something that can be done with an IntentService and can not be done with a Service 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 Intents delivered to onStartCommand(), so if one Intent is being processed by onHandleIntent() on the background thread, other commands queue up waiting their turn
the automatic shutdown of the IntentService, via a call to stopSelf(), once the queue is empty
Any and all of that could be implemented by a Service without extending IntentService.
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() or stopService()
IntentService
It performs long task usually no communication with main thread if communication is needed then it is done by Handler or BroadcastReceiver
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.
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 Thread
IntentService creates a Work Queue which sends request to onHandleIntent() method one by one
When there is no work then IntentService calls stopSelf() method
Provides default implementation for onBind() method which is null
Default implementation for onStartCommand() which sends Intent request to WorkQueue and eventually to onHandleIntent()
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
I'm sure you can find an extensive list of differences by simply googling something such as 'Android IntentService vs Service'
One of the more important differences per example is that IntentService ends itself once it's done.
Some examples (quickly made up) could be;
IntentService: If you want to download a bunch of images at the start of opening your app. It's a one-time process and can clean itself up once everything is downloaded.
Service: A Service which will constantly be used to communicate between your app and back-end with web API calls. Even if it is finished with its current task, you still want it to be around a few minutes later, for more communication.
IntentService
IntentService runs on its own thread.
It will stop itself when it's done. More like fire and forget.
Subsequent calls will be queued. Good for queuing calls.
You can also spin multiple threads within IntentServiceif you need to- You can achieve this using ThreadPoolExecutor.
I say this because many people asked me "why use IntentService since it doesn't support parallel execution".
IntentService is just a thread. You can do whatever you need inside it- Even spinning multiple threads. The only caveat is that IntentService finishes as soon as you spin those multiple threads. It doesn't wait for those threads to come back. You need to take care of this. So I recommend using ThreadPoolExecutor in those scenarios.
Good for Syncing, uploading etc …
Service
By Default Service runs on the main thread. You need to spin a worker thread to do your job.
You need to stop service explicitly.
I used it for a situation when you need to run stuff in the background even when you move away from your app and come back more for a Headless service.
Again you can run multiple threads if you need to.
Can be used for apps like music players.
You can always communicate back to your activity using BroadcastReceivers if you need to.
An IntentService is an extension of a Service that is made to ease the execution of a task that needs to be executed in background and in a seperated thread.
IntentService starts, create a thread and runs its task in the thread. once done, it cleans everything. Only one instance of a IntentService can run at the same time, several calls are enqueued.
It is very simple to use and very convenient for a lot of uses, for instance downloading stuff. But it has limitations that can make you want to use instead the more basic (not simple) Service.
For example, a service connected to a xmpp server and bound by activities cannot be simply done using an IntentService. You'll end up ignoring or overriding IntentService stuffs.
Android IntentService vs Service
1.Service
A Service is invoked using startService().
A Service can be invoked from any thread.
A Service runs background operations on the Main Thread of the
Application by default. Hence it can block your Application’s UI.
A Service invoked multiple times would create multiple instances.
A service needs to be stopped using stopSelf() or stopService().
Android service can run parallel operations.
2. IntentService
An IntentService is invoked using Intent.
An IntentService can in invoked from the Main thread only.
An IntentService creates a separate worker thread to run background
operations.
An IntentService invoked multiple times won’t create multiple
instances.
An IntentService automatically stops after the queue is completed. No
need to trigger stopService() or stopSelf().
In an IntentService, multiple intent calls are automatically Queued
and they would be executed sequentially.
An IntentService cannot run parallel operation like a Service.
Refer from Here
If someone can show me an example of something that you can be done with an IntentService and can not be done with a service and the other way around.
IntentService can not be used for Long Time Listening, Like for XMPP Listeners, its a single time operator, do the job and wave goodbye.
Also it has just one threadworker, but with a trick, you can use it as unlimited.
The Major Difference between a Service and an IntentService is described as follows:
Service :
1.A Service by default, runs on the application's main thread.(here no default worker thread is available).So the user needs to create a separate thread and do the required work in that thread.
2.Allows Multiple requests at a time.(Multi Threading)
IntentService :
1.Now, coming to IntentService, here a default worker thread is available to perform any operation. Note that - You need to implement onHandleIntent() method ,which receives the intent for each start request, where you can do the background work.
2.But it allows only one request at a time.
I'm trying to play around with an Android "Service" but the more I play with it, the more I see that it's intimately tied to the UI thread. What I mean is that I fire up an Activity, and call a Service, just for yucks do a very long for loop in the Service. I would expect that for loop to happen in the "background" and not interfere with my UI, but it's freezing my UI while the for loop is going on (and it releases my UI back to normal when the for loop is done). Why wouldn't the "Service" just run in the "background" instead of messing up my UI? How can I make it run in the "background"?
from the manual:
What is a Service?
Most confusion about the Service class actually revolves around what
it is not:
A Service is not a separate process. The Service object itself does
not imply it is running in its own process; unless otherwise
specified, it runs in the same process as the application it is part
of.
A Service is not a thread. It is not a means itself to do work off
of the main thread (to avoid Application Not Responding errors).
This is how you should do (again, taken from the manual & also mentioned by #Jave):
Note that services, like other application objects, run in the main
thread of their hosting process. This means that, if your service is
going to do any CPU intensive (such as MP3 playback) or blocking (such
as networking) operations, it should spawn its own thread in which to
do that work. More information on this can be found in Processes and Threads. The IntentService class is available as a standard
implementation of Service that has its own thread where it schedules
its work to be done.
From the documentation for Service:
Note that services, like other application objects, run in the main
thread of their hosting process. This means that, if your service is
going to do any CPU intensive (such as MP3 playback) or blocking (such
as networking) operations, it should spawn its own thread in which to
do that work. More information on this can be found in Processes and
Threads. The IntentService class is available as a standard
implementation of Service that has its own thread where it schedules
its work to be done.
class DownloadingService extends Service
{
...
#Override
public void onCreate()
{
...
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block.
Thread notifyingThread = new Thread(null, mTask, "DownloadingService");
notifyingThread.start();
}
private Runnable mTask = new Runnable()
{
public void run()
{
// here the job is going to be done
}
};
}
This question already has answers here:
Service vs IntentService in the Android platform
(11 answers)
Closed 6 years ago.
Can you please help me understand what the difference between an IntentService and a Service is?
Service is a base class of service implementation. Service runs on the application's main thread which may reduce the application performance. Thus, IntentService, which is a direct subclass of Service is available to make things easier.
The IntentService is used to perform a certain task in the background. Once done, the instance of IntentService terminates itself automatically. Examples for its usage would be to download a certain resource from the Internet.
Differences
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 class needs a manual stop using stopSelf(). Meanwhile, IntentService automatically stops itself when it finishes execution.
IntentService implements onBind() that returns null. This means that the IntentService can not be bound by default.
IntentService implements onStartCommand() that sends Intent to queue and to onHandleIntent().
In brief, there are only two things to do to use IntentService. Firstly, to implement the constructor. And secondly, to implement onHandleIntent(). For other callback methods, the super is needed to be called so that it can be tracked properly.
In short, a Service is a broader implementation for the developer to set up background operations, while an IntentService is useful for "fire and forget" operations, taking care of background Thread creation and cleanup.
From the docs:
Service
A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.
IntentService
Service is a base class for IntentService 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.
Refer this doc - http://developer.android.com/reference/android/app/IntentService.html
service: It runs in the background on your system. For example,
If you went to a hotel and you give your order for a soup to a server
The server gets your order and sends to chef
You don't know how the soup is made in the kitchen and what processes are required for making the soup
Once your order is ready, the server brings you the soup.
background process: chef making soup
IntentService:- it's consecutive service.. (i.e) when you order many food items at a time to server but the server delivers those items one by one and not deliver them all at once.
See Tejas Lagvankar's post about this subject.
Below are some key differences between Service and IntentService and other components.
Service
Task with no UI,but should not use for long Task. Use Thread within service for long Task
Invoke by onStartService()
Triggered from any Thread
Runs On Main Thread
May block main(UI) thread
IntentService
Long task usually no communication with main thread if communication is needed then it is done by Handler or broadcast
Invoke via Intent
triggered from Main Thread (Intent is received on main Thread and worker thread is spawned)
Runs on separate thread
We can't run task in parallel and multiple intents are Queued on the same worker thread.
Service runs actually in the same thread of your app; when you extends Service, you must manually spawn new threads to run CPU blocking operations.
vs
IntentService is a subclass of Service which spawns a thread to do background work from there(No need to create a new thread to do CPU blocking operations).
Service: Works in the main thread so it will cause an ANR (Android Not Responding) after a few seconds.
IntentService: Service with another background thread working separately to do something without interacting with the main thread.
Intent service is child of Service
IntentService: If you want to download a bunch of images at the start of opening your app. It's a one-time process and can clean itself up once everything is downloaded.
Service: A Service which will constantly be used to communicate between your app and back-end with web API calls. Even if it is finished with its current task, you still want it to be around a few minutes later, for more communication