823

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
roiberg
  • 13,629
  • 12
  • 60
  • 91
  • 50
    `IntentService is used for short tasks (etc) and a service is for long ones` where did you read that ? – njzk2 Mar 20 '13 at 13:01
  • 9
    aLso, I suggest you read the source code for IntentService. It makes it quite clear what it is and what it does. – njzk2 Mar 20 '13 at 13:02
  • 1
    I edited my question after I saw you comment. – roiberg Mar 20 '13 at 13:07
  • 9
    Code for IntentService: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/app/IntentService.java – greg7gkb Aug 11 '15 at 15:45

11 Answers11

1428

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().

José Juan Sánchez
  • 14,429
  • 1
  • 12
  • 7
  • 13
    short 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 – Shirish Herwade Jun 18 '14 at 11:13
  • @Shiri Hrw: I have just edit the answer with a new point included by CommonsWare. Thanks for the advice! – José Juan Sánchez Jul 04 '14 at 09:01
  • @JoséJuanSánchez easily explained the whole concept of these two components. – Naresh Sharma Aug 14 '14 at 09:43
  • 1
    "The service runs is background but runs on Main thread of app" - Help me understand this. – Darpan Nov 12 '14 at 10:32
  • 12
    @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. – José Juan Sánchez Nov 15 '14 at 15:04
  • 8
    "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(); – Ashok Bijoy Debnath Dec 04 '14 at 07:56
  • 9
    @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! :) – José Juan Sánchez Dec 04 '14 at 09:36
  • which service i should use to update my local application table continuously ? even my application is closed. – pathe.kiran Jun 02 '15 at 11:31
  • 2
    No problem, go for it! – José Juan Sánchez Sep 21 '16 at 22:07
  • 2
    _"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 a `Service`** can run on any Thread, The **lifecycle methods** (`onCreate()`, `onStartCommand()`, `onDestroy()` are called by the Android framework on the main (UI) Thread. When implementing a `Service` it is common to start your own `Thread`s as worker or background threads and perform long-running operations on those threads. `IntentService` is just an extenstion of `Service` that does some of this for you. – David Wasser Dec 27 '16 at 14:21
  • i hope i could +1 again – Shubham AgaRwal Feb 06 '17 at 14:17
  • 1
    service: but shouldn't be too long, can you define "too long" in this context? is it 1min, 2min or 3min...... ? thank you – Kugan Kumar Jul 31 '17 at 06:45
  • So 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](https://developer.android.com/guide/components/services.html) it says **A Service is an application component that can perform long-running operations in the background**. For [IntentService](https://developer.android.com/reference/android/app/IntentService.html) 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... – Laurent Aug 24 '17 at 12:58
  • `"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 is `idle`. https://developer.android.com/about/versions/oreo/background.html – alizeyn Jan 05 '18 at 12:57
  • One 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 Aug 18 '18 at 07:50
174

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • 7
    A little late, but I am finding that `Service` called with `startService` can only run for about 10 seconds before throwing an ANR-- an `IntentService` started with broadcasting an intent doesn't seem to have this limitation – edthethird Nov 18 '13 at 20:56
  • 16
    @edthethird: That is because you were tying up the main application thread. All lifecycle methods on all components, including `onStartCommand()` of a `Service`, 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. – CommonsWare Nov 18 '13 at 21:12
  • 4
    yup I commented too soon. I was doing the work `onStartCommand` instead of `onHandleIntent`-- looks like `onStartCommand` is run on the UI thread, however a separate thread is spawned for `onHandleIntent` execution. – edthethird Nov 18 '13 at 21:22
  • Is stopSelf() something that the programmer has to call, or does the IntentService call that by itself? – IgorGanapolsky Jan 27 '15 at 21:46
  • 3
    @IgorGanapolsky: `IntentService` calls that itself, after `onHandleIntent()` returns, if there is no more work to be done. – CommonsWare Jan 27 '15 at 23:20
  • @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. – eRaisedToX Mar 02 '17 at 07:07
  • @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 of `Service`. However, you can create other subclasses of `Service` as well. – CommonsWare Mar 02 '17 at 12:48
  • One 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 – Ravindra Kushwaha Aug 18 '18 at 09:07
  • @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, the `IntentService` goes away when the process does. And it is possible that you have something else in mind for "removed". – CommonsWare Aug 18 '18 at 11:07
  • @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 – Ravindra Kushwaha Aug 18 '18 at 11:10
  • @RavindraKushwaha: I am sorry, but I still do not understand what you mean. An `IntentService` *is* a `Service`. All normal `Service` rules apply. *In addition*, an `IntentService` stops itself automatically when the work in `onHandleIntent()` completes. Note that `IntentService` does not work especially well on Android 8.0+ -- please consider using `JobIntentService` or (in 2019 and beyond) `WorkManager` for this sort of background work. – CommonsWare Aug 18 '18 at 11:12
  • Sir IntentService depends on Application is running or not? – Ravindra Kushwaha Aug 18 '18 at 11:19
  • @RavindraKushwaha: I do not know what you consider "Application is running or not" to mean, so I cannot answer that, sorry. – CommonsWare Aug 18 '18 at 11:25
  • Sorry for bothering you...What a hell my English...You are not getting me..Thanks, sir anyway @CommonsWare – Ravindra Kushwaha Aug 18 '18 at 11:30
  • One 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? – Ravindra Kushwaha Aug 18 '18 at 11:38
  • 1
    The 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 [mcve] 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?). – CommonsWare Aug 18 '18 at 12:05
  • ok sir @CommonsWare Thanks a lot for urs suggestion.Again thanks sir :) – Ravindra Kushwaha Aug 20 '18 at 05:26
44

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.
MHSaffari
  • 858
  • 1
  • 16
  • 39
Umang Kothari
  • 3,674
  • 27
  • 36
  • 1
    An **IntentService** can be also invoked by `startService`. Please edit your answer accordingly and make it coherent. – daparic Sep 18 '21 at 15:27
42

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

  1. IntentService creates a Worker Thread

  2. IntentService creates a Work Queue which sends request to onHandleIntent() method one by one

  3. When there is no work then IntentService calls stopSelf() method
  4. Provides default implementation for onBind() method which is null
  5. Default implementation for onStartCommand() which sends Intent request to WorkQueue and eventually to onHandleIntent()
Rohit Singh
  • 16,950
  • 7
  • 90
  • 88
  • `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 ? – Wini Sep 23 '20 at 08:37
  • 2
    Downloading songs one by one from a Playlist. @Wini – Rohit Singh Sep 23 '20 at 10:07
15

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

Pritam
  • 339
  • 3
  • 23
Sree Rama
  • 1,207
  • 12
  • 25
14

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.

Stefan de Bruijn
  • 6,289
  • 2
  • 23
  • 31
  • Yea, 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 Mar 20 '13 at 13:06
  • 2
    I didn't find one example that can be done with one and not with the other. just some explanations that didn't help me. – roiberg Mar 20 '13 at 13:09
  • 1
    Try this site, it has a lot of good explanation on basic Android concepts with decent examples http://www.vogella.com/articles/AndroidServices/article.html – Stefan de Bruijn Mar 20 '13 at 13:10
  • 4
    Its 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. – roiberg Mar 20 '13 at 13:14
  • Updated answer with some short examples too. – Stefan de Bruijn Mar 20 '13 at 13:14
  • 5
    that'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 – pelotasplus Mar 20 '13 at 13:15
  • Yea, now I get it!! Thanks! – roiberg Mar 20 '13 at 13:16
  • 29
    when i google that, it brings me here. now i am in an infinite loop. – Lou Morda Oct 04 '14 at 21:57
12

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.

Puja
  • 192
  • 9
Sayooj Valsan
  • 536
  • 5
  • 16
9

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.

njzk2
  • 38,969
  • 7
  • 69
  • 107
  • what 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) – Lassi Kinnunen Feb 26 '14 at 05:24
  • the 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. – njzk2 Feb 26 '14 at 14:19
7

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

Deepak gupta
  • 827
  • 10
  • 10
6

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.

SREE
  • 464
  • 3
  • 20
user3764748
  • 111
  • 1
  • 9
5

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.

MHSaffari
  • 858
  • 1
  • 16
  • 39
Narendrakumar
  • 163
  • 2
  • 6