Difference between Service, Async Task & Thread?

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?

  • AppWidgetManager getAppWidgetIds returning old Widget ids
  • Communicating between a fragment and an activity - best practices
  • Android library project uses declare-styleable — how to compile?
  • Android-Is it possible to add a clickable link into a string resource
  • How to display a Toast inside a Handler/thread?
  • I can't install/launch Android Studio for Windows 7 64 bit
  • Related posts:

    Rounded corners android image buttons
    Android usb host api and USB storage
    Android square imageview
    Warning: Do not place Android context classes in static fields; this is a memory leak (and also brea...
    How to invoke the ActionBar's ContextMenu-like behavior?
    Changing the content of framelayout on button click
  • Android: How to Know if any application is already installed in android device using adb?
  • Which type of url should use in android for sending request to server?
  • Programmatically enter secret code like *#*#4636#*#* on Android
  • How to import/export Android string resource to Excel for localization?
  • iScroll 4 not working with form <select> element iPhone Safari and Android browser
  • Adding external library in Android studio 0.3.6
  • 7 Solutions collect form web for “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 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.

    This is the easiest answer for your question

    Thread

    is an unit of execution who run “parallel” to the Main Thread is important to point you can’t update a UI component from the main thread here.

    AsyncTask

    is for a short Task because is tied to the host activity for example if you create a AsyncTask who going to pull data from a server (DON’T DO THIS) when you rotate the phone and the activity is recreated again the AsyncTask is recreate also

    Service

    solve the above problem because it live separate from the activity that invoke him 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 IntedService it create the worker thread automatically for you). Service is like an activity without UI,
    is good for long task

    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.

    Thread

    A thread is a concurrent unit of execution. It has its own call stack. There are two methods to implement threads in applications.

    One is providing a new class that extends Thread and overriding its run() method.
    The other is providing a new Thread instance with a Runnable object during its creation.
    A thread can be executed by calling its “start” method. You can set the “Priority” of a thread by calling its “setPriority(int)” method.

    A thread can be used if you have no affect in the UI part. For example, you are calling some web service or download some data, and after download, you are displaying it to your screen. Then you need to use a Handler with a Thread and this will make your application complicated to handle all the responses from Threads.

    A Handler allows you to send and process Message and Runnable objects associated with a thread’s MessageQueue. Each thread has each message queue. (Like a To do List), and the thread will take each message and process it until the message queue is empty. So, when the Handler communicates, it just gives a message to the caller thread and it will wait to process.

    If you use Java threads then you need to handle the following requirements in your own code:

    • Synchronization with the main thread if you post back results to the
      user interface No default for canceling the thread No default thread
      pooling No default for handling configuration changes in Android

    AsyncTask

    AsyncTask enables proper and easy use of the UI thread. This class allows performing background operations and publishing results on the UI thread without having to manipulate threads and/or handlers. An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread.

    AsyncTask will go through the following 4 stages:

    onPreExecute()

    Invoked on the UI thread before the task is executed

    doInbackground(Params..)

    Invoked on the background thread immediately after onPreExecute() finishes executing.

    onProgressUpdate(Progress..)

    Invoked on the UI thread after a call to publishProgress(Progress…).

    onPostExecute(Result)

    Invoked on the UI thread after the background computation finishes.
    Why should you use AsyncTask?

    Easy to use for a UI Thread. (So, use it when the caller thread is a UI thread).
    No need to manipulate Handlers.

    Service
    A Service is a context similar to Activity but has no GUI.

    Important: A service doesn’t run in a new thread!

    Read about Service and also check out How to always run a service in the background

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

    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 works like thread but can handle the UI as well.

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

    Service: Is a background process. It is employed when you have to do some processing that doesn’t have any UI associated with it.

    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.

    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.