Difference between Service, Async Task & Thread?
Asked Answered
L

6

151

What is the difference between Service, Async Task & Thread. If i am not wrong all of them are used to do some stuff in background. So, how to decide which to use and when?

Litterbug answered 16/7, 2010 at 11:35 Comment(1)
It seems there is one more thing with which people can get confused often - Loaders. Related thread - Asynctask vs Thread vs Services vs LoaderGuano
L
190

Probably you already read the documentation description about them, I won't repeat them, instead I will try to give answer with my own words, hope they will help you.

  • Service is like an Activity but has no user interface. Probably if you want to fetch the weather for example you won't create a blank activity for it, for this you will use a Service.

  • A Thread is a Thread, probably you already know it from other part. You need to know that you cannot update UI from a Thread. You need to use a Handler for this, but read further.

  • An AsyncTask is an intelligent Thread that is advised to be used. Intelligent as it can help with it's methods, and there are three methods that run on UI thread, which is good to update UI components.

I am using Services, AsyncTasks frequently. Thread less, or not at all, as I can do almost everything with AsyncTask.

Luscious answered 16/7, 2010 at 11:44 Comment(8)
Thanks for your explanation. So, if i need to make an application which fetches data from the web, which would be a better option service or async task?Litterbug
You need to use both. You create a Service and inside that you use AsyncTask.Luscious
Add to above answer, AsyncTask goes through 4 steps onPreExecute(),onProgressUpdate(Progress...)onPostExecute(Result),{running in UI thread}, doInBackground(Params...){running in background thread}. Since it provides 3 methods in UI thread, user need not worry about using handlers or callbacks to update UI.Litterbug
@Luscious : instead of Service+AsyncTask, you often can use an IntentServiceLiverpool
Also notable is that by default Android services run on the main (UI) thread. If your service needs to do work in the background, it needs to be launched in a separate thread (or AsyncTask) explicitly. Otherwise it can risk interrupting the UI responsiveness and throw Application Not Responding errors. A service wrt Android is essentially an 'invisible' and 'miniature' Activity, NOT necessarily a 'background' worker.Edible
@Edible Isn't it interesting. Run the Service in an AsyncTask or in a Thread and then in a Service use another Thread or AsyncTask to do your work. Thread-> Service -> Thread :DGoodson
AsyncTasks are controlled internally by a shared (static) ThreadPoolExecutor and a LinkedBlockingQueue. ThreadPoolExecutor will wait for a future ready state and executes the task when an execute() call made from an AsyncTask. The ready state is determined using core pool size and maximum pool size. If new task comes in and the number of current threads in active execution are less than core pool size, the task will executed immediately, else it will wait for a thread to finish execution and starts a new thread for executing the new task.Ganesha
If we can perform our function and can do our task with Async Task, then why we need Thread. I am confused, that if every thing is possible with Async Task, and it is good to use, then what is the main purposes of thread which differentiate it from Async Task??? please clear meCorded
P
25

This is the easiest answer for your question

Thread

is an unit of execution who run "parallel" to the Main Thread is an important point, you can't update a UI component from the any thread here except main thread.

AsyncTask

is a special thread, which gives you helper methods to update UI so basically you can update the UI even AsyncTask will run on a background thread. Interprocess communication handling is not required to be done explicitly.

Service

solve the above problem because it live separate from the activity that invoke it so it can continue running even when the activity is destroyed, it run in the Main Thread(beware of ANR) use a background service (extend IntentService it create the worker thread automatically for you). Service is like an activity without UI, is good for long task

Pollen answered 2/11, 2015 at 16:48 Comment(2)
AyncTask wouldn't be recreated on rotating the device because it is not in sync with the Activity lifecycle methods.Dandle
you create the AsyncTask in an Activity lifecycle hook and when you rotate the phone the Activity is destroyed and restarted. The previus instance of the AsyncTask is connected to that Activity that you just destroyed and for that reason you will get a "Force Close" but you will also see how a new instance of the AsynTask getting trigger again. You can use Fragments to retain AsyncTask and set setRetainInstance(true) on the Fragment that will help you.Pollen
D
15

Few more information I wish someone had told me a few days ago:

  • You can share global variables - such as threads - between Activities and Services.
  • Your application together with all its global variables will not be wiped out as long as there is an Activity or a Service still present.
  • If you have an instance of a Service in your app and the OS needs resources, it first kills your Activities, but as long as there is the Service, the OS won't wipe out your application together with its global variables.

My use case is like this: I have one thread in global space that is connected to a server and an Activity that shows the results. When user presses the home button, the Activity goes to background and a new Service is started. This service then reads results from the thread and displays information in the notification area when needed. I don't worry about the OS destroying my Activity because I know that as long as the Service is running it won'd destroy the thread.

Disabuse answered 1/10, 2013 at 12:35 Comment(0)
B
10

In short, Service for time consuming tasks, AsyncTask for short-lived tasks, Thread is a standard java construction for threads.

Bovine answered 2/2, 2015 at 18:38 Comment(0)
L
4

From developer's perspective:

Thread: Used to execute the set to codes parallely to the main thread. But you cannot handle the UI inside the thread. For that you need to use Handler. Hadler binds thread Runnable with Looper that makes it a UI thread.

ASyncTask: Used for handling those tasks that you cannot make to work on the main thread. For example, an HTTP request is a very heavy work that cannot be handled on the main thread, so you handle the HTTP request in the ASyncTask It works parallelly with your main thread Asynchronously in the background. It has a few callback methods that are invoked on their corresponding events.

Service: Works in the background under the same Application process. It is implemented when you have to do some processing that doesn't have any UI associated with it.

Layby answered 15/5, 2015 at 10:44 Comment(4)
Service won't necessary run in the background unless you use IntentService. If you started a standart Service from the UiThread it will run on the UiThread.Landscape
@Landscape You are correct, but here we don't need deep definition. User just want to know the difference between them.Layby
Yes, but this not accurate, as Service won't run in a different process by default, but in the app process with the other components. Better to say that Service will run in the Background of the Thread that it live inside.Landscape
All the above three works within the application process. ASyncTask's preExecute() and postExecute() methods works on UIThread and doInBackground() & onProgress() works on background thread. Service works on Background thread and Thread also work on background thread. However Handler works on UI Thread.Layby
E
2

service is like activity long time consuming task but Async task allows us to perform long/background operations and show its result on the UI thread without having to manipulate threads.

Erupt answered 13/7, 2015 at 5:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.