Difference between Service, Async Task & Thread?

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.


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.


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