140

Why do I read in the answer to most questions here a lot about AsyncTask and Loaders but nothing about Services? Are Services just not known very well or are they deprecated or have some bad attributes or something? What are the differences?

(By the way, I know that there are other threads about it, but none really states clear differences that help a developer to easily decide if he is better off using the one or the other for an actual problem.)

erikbstack
  • 12,878
  • 21
  • 81
  • 115

6 Answers6

275

In some cases it is possible to accomplish the same task with either an AsyncTask or a Service however usually one is better suited to a task than the other.

AsyncTasks are designed for once-off time-consuming tasks that cannot be run of the UI thread. A common example is fetching/processing data when a button is pressed.

Services are designed to be continually running in the background. In the example above of fetching data when a button is pressed, you could start a service, let it fetch the data, and then stop it, but this is inefficient. It is far faster to use an AsyncTask that will run once, return the data, and be done.

If you need to be continually doing something in the background, though, a Service is your best bet. Examples of this include playing music, continually checking for new data, etc.

Also, as Sherif already said, services do not necessarily run off of the UI thread.

For the most part, Services are for when you want to run code even when your application's Activity isn't open. AsyncTasks are designed to make executing code off of the UI thread incredibly simple.

Computerish
  • 9,590
  • 7
  • 38
  • 49
  • 2
    It is interesting that in this talk from Google I/O in 2010 http://www.youtube.com/watch?v=xHXn3Kg2IQE the presenter gives 3 different methods for getting data from a REST API and the first one uses a service. I'm not an Android expert but I was also under the impression that what Computerish said is basically correct. – wuliwong Sep 30 '12 at 03:35
  • 10
    The last paragraph, "Services are for when you want to run code even when your application's Activity isn't open". This is also the case with AsyncTask or background threads. i.e. when you press back in your activity or call finish() and your activity not visible, but still your background threads are executing until you kill your app process (e.g. by swapping from recent tasks). I have checked this with 4.4.2 Google Nexus AOSP grouper – Shirish Herwade Jul 16 '14 at 14:45
  • 10
    However AsyncTask can be tricky if the Activity that started it is killed while the AsyncTask is still running and needs to update the UI once it's done...(which won't work since Activity is already destroyed). Why not use an IntentService which afaik you don't need to stop manually, since it simply ends once done? – AgentKnopf Sep 15 '14 at 08:09
  • great points.good explanation about service.That is service running in background continuously even the work is done. – BABU K Sep 26 '14 at 18:39
  • @AgentKnopf: It's just as tricky for a *Service* to update the UI when it's done if the Activity that started it is destroyed. Right? – LarsH Nov 02 '16 at 16:37
  • 3
    @LarsH Correct me if I am wrong, but I think you could use a BroadcastReceiver in your Activity/Fragment and from the IntentService you simply fire a Broadcast once you're done. Since you can re-register for Broadcasts upon Activity/Fragment re-creation that should have you covered. Another alternative would be using an EventBus for updating the UI (though I try to avoid those - makes the code harder to follow imo). – AgentKnopf Dec 04 '16 at 21:51
  • @AgentKnopf: OK, I didn't realize you were talking about a case where the activity/fragment has been created again. That makes sense. – LarsH Dec 05 '16 at 11:11
57

Services are completely different: Services are not threads!

Your Activity binds to a service and the service contains some functions that when called, blocks the calling thread. Your service might be used to change temperature from Celsius to Degrees. Any activity that binds can get this service.


However AsyncTask is a Thread that does some work in the background and at the same time has the ability to report results back to the calling thread.

Just a thought: A service may have a AsyncTask object!

Sherif elKhatib
  • 45,786
  • 16
  • 89
  • 106
  • 2
    Services are described as running in the background, continuing even when ur application is closed, though. AsyncTask also is used to do something in the background. Know what I mean? – erikbstack Aug 05 '11 at 14:33
  • 1
    yeah but services may or may not be doing something. They are a long-lasting OBJECT – Sherif elKhatib Aug 05 '11 at 14:41
  • "A service may have a AsyncTask object!" Thanks for pointing that out. But is it a good idea - is it something you'd recommend? Or would it be better to use more basic threading techniques in a service? – RenniePet Jul 30 '13 at 14:59
  • "Your Activity binds to a service" not necessarily. – JacksOnF1re Aug 28 '15 at 14:40
  • @JacksOnF1re I know this is like when I first started coding :p but "Your activity binds to a service" is a true statement. I could also be binding to this service. A refrigerator could be binding as well. This does not make the statement invalid.. anyway jk – Sherif elKhatib Aug 29 '15 at 06:50
7

Service is one of the components of the Android framework, which does not require UI to execute, which mean even when the app is not actively used by the user, you can perform some operation with service. That doesn't mean service will run in a separate thread, but it runs in main thread and operation can be performed in a separate thread when needed. Examples usages are playing music in background, syncing data with server in backgroud without user interaction etc

AsyncTask on other hand is used for UI blocking tasks to be performed on a separate thread. It is same like creating a new thread and doing the task when all the tasks of creating and maintaining the threads and send back result to main thread are taken care by the AsyncTask Example usage are fetching data from server, CRUD operations on content resolver etc

arjun
  • 3,514
  • 4
  • 27
  • 48
  • can you specify why you think that your answer adds anything to the question? – erikbstack Feb 09 '17 at 20:58
  • 2
    other answers are either too short or too long for beginners to understand. so I answered precisely in simple words with examples – arjun Feb 10 '17 at 03:16
6

Service and asynctasks are almost doing the same thing,almost.using service or a asynctask depends on what is your requirement is.

as a example if you want to load data to a listview from a server after hitting some button or changing screen you better go with a asynctask.it runs parallel with main ui thread (runs in background).for run asynctack activity or your app should on main UI thread.after exit from the app there is no asynctask.

But services are not like that, once you start a service it can run after you exit from the app, unless you are stop the service.like i said it depends on your requirement.if you want to keep checking data receiving or check network state continuously you better go with service.

happy coding.

Ashana.Jackol
  • 3,064
  • 28
  • 22
  • 1
    Hi Ashana, can I ask why you provided this answer to a question that is already answered? Are you unhappy with the existing marked answer? Or do you try to build a SO profile by writing your opinion to all questions you have something to say about? Or something completely different? Can't figure it out, but I see that pattern quite often lately. – erikbstack Apr 25 '17 at 11:02
  • 3
    ya i know answer is already given and i dont see much problem here if i give the right answer or my opinion in here bro? because you are not the only one who looking for the answer to same question, if someone hard to understand the solution in above answers he/she can scroll down to looking for a answer that well fit for them, easily understand one.Thats it.Thanks for the comment bro, im not a genius or pro in programming, just want to help others, try to teach others what i know already :) – Ashana.Jackol Apr 28 '17 at 05:08
1

In few cases, you can achieve same functionality using both. Unlike Async Task, service has it's own life cycle and inherits Context (Service is more robust than an Async Task). Service can run even if you have exited the app. If you want to do something even after app closing and also need the context variable, you will go for Service.

Example: If you want to play a music and you don't want to pause if user leaves the app, you will definitely go for Service.

sayem siam
  • 1,281
  • 3
  • 13
  • 26
1

Comparison of a local, in-process, base class Service✱ to an AsyncTask:

✱ (This answer does not address exported services, or any service that runs in a process different from that of the client, since the expected use cases differ substantially from those of an AsyncTask. Also, in the interest of brevity, the nature of certain specialized Service subclasses (e.g., IntentService, JobService) will be ignored here.)

Process Lifetime

A Service represents, to the OS, "an application's desire to perform a longer-running operation while not interacting with the user" [ref].

While you have a Service running, Android understands that you don't want your process to be killed. This is also true whenever you have an Activity onscreen, and it is especially true when you are running a foreground service. (When all your application components go away, Android thinks, "Oh, now is a good time to kill this app, so I can free up resources".)

Also, depending on the last return value from Service.onCreate(), Android can attempt to "revive" apps/services that were killed due to resource pressure [ref].

AsyncTasks don't do any of that. It doesn't matter how many background threads you have running, or how hard they are working: Android will not keep your app alive just because your app is using the CPU. It has to have some way of knowing that your app still has work to do; that's why Services are registered with the OS, and AsyncTasks aren't.

Multithreading

AsyncTasks are all about creating a background thread on which to do work, and then presenting the result of that work to the UI thread in a threadsafe manner.

Each new AsyncTask execution generally results in more concurrency (more threads), subject to the limitations of the AsyncTasks's thread-pool [ref].

Service methods, on the other hand, are always invoked on the UI thread [ref]. This applies to onCreate(), onStartCommand(), onDestroy(), onServiceConnected(), etc. So, in some sense, Services don't "run" in the background. Once they start up (onCreate()), they just kinda "sit" there -- until it's time to clean up, execute an onStartCommand(), etc.

In other words, adding additional Services does not result in more concurrency. Service methods are not a good place to do large amounts of work, because they run on the UI thread.

Of course, you can extend Service, add your own methods, and call them from any thread you want. But if you do that, the responsibility for thread safety lies with you -- not the framework.

If you want to add a background thread (or some other sort of worker) to your Service, you are free to do so. You could start a background thread/AsyncTask in Service.onCreate(), for example. But not all use cases require this. For example:

  • You may wish to keep a Service running so you can continue getting location updates in the "background" (meaning, without necessarily having any Activities onscreen).
  • Or, you may want to keep your app alive just so you can keep an "implicit" BroadcastReceiver registered on a long-term basis (after API 26, you can't always do this via the manifest, so you have to register at runtime instead [ref]).

Neither of these use cases require a great deal of CPU activity; they just require that the app not be killed.

As Workers

Services are not task-oriented. They are not set up to "perform a task" and "deliver a result", like AsyncTasks are. Services do not solve any thread-safety problems (notwithstanding the fact that all methods execute on a single thread). AsyncTasks, on the other hand, handle that complexity for you.

Note that AsyncTask is slated for deprecation. But that doesn't mean your should replace your AsyncTasks with Services! (If you have learned anything from this answer, that much should be clear.)

TL;DR

Services are mostly there to "exist". They are like an off-screen Activity, providing a reason for the app to stay alive, while other components take care of doing the "work". AsyncTasks do "work", but they will not, in and of themselves, keep a process alive.

greeble31
  • 4,894
  • 2
  • 16
  • 30