Difference between Service, Async Task & Thread?
Solution 1
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.
Solution 2
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
Solution 3
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.
Solution 4
In short, Service for time consuming tasks
, AsyncTask for short-lived tasks
, Thread is a standard java construction
for threads.
Solution 5
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.
Related videos on Youtube
SpunkerBaba
Updated on January 28, 2022Comments
-
SpunkerBaba over 2 years
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?
-
RBT over 5 yearsIt seems there is one more thing with which people can get confused often - Loaders. Related thread - Asynctask vs Thread vs Services vs Loader
-
-
SpunkerBaba almost 14 yearsThanks 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?
-
Pentium10 almost 14 yearsYou need to use both. You create a Service and inside that you use AsyncTask.
-
SpunkerBaba over 13 yearsAdd 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.
-
njzk2 about 12 years@Pentium10 : instead of Service+AsyncTask, you often can use an IntentService
-
CCJ about 11 yearsAlso 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.
-
Faizan Mubasher over 10 years@CCJ 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 :D
-
Beep.exe about 10 yearsAsyncTasks 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.
-
Pir Fahim Shah about 10 yearsIf 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 me
-
yshahak over 7 years
Service
won't necessary run in the background unless you useIntentService
. If you started a standartService
from the UiThread it will run on the UiThread. -
Rahul Raina over 7 years@yshahak You are correct, but here we don't need deep definition. User just want to know the difference between them.
-
yshahak over 7 yearsYes, 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 thatService
will run in the Background of the Thread that it live inside. -
Rahul Raina over 7 yearsAll 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.
-
CopsOnRoad over 6 yearsAyncTask wouldn't be recreated on rotating the device because it is not in sync with the Activity lifecycle methods.
-
Alejandro Serret over 6 yearsyou 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.