0

I need to use background operation in android,so i need to know what are the differences between handler and AsyncTasks in Android?

Komali perera
  • 101
  • 1
  • 5
  • AsyncTasks basically used to perform time consuming operations such as fetching data from web.Handler used to communicate between asyntask & ui ..to update UI – Prachi Jan 20 '15 at 06:26
  • Take a look at this. Please search before asking questions. http://stackoverflow.com/questions/2523459/handler-vs-asynctask – Tommy Lee Jan 20 '15 at 06:27

3 Answers3

1

Handler and AsyncTasks are way to implement multithreading in android with UI/Event Thread. Handler is available since Android API level 1 & AsyncTask is available since API level 3.

What is Handler?

  1. Handler allows to add messages to the thread which creates it and It also enables you to schedule some runnable to execute at some time in future.
  2. The Handler is associated with the application’s main thread. It handles and schedules messages and runnables sent from background threads to the app main thread.
  3. If you are doing multiple repeated tasks, for example downloading multiple images which are to be displayed in ImageViews (like downloading thumbnails) upon download, use a task queue with Handler.
  4. There are two main uses for a Handler. First is to schedule messages and runnables to be executed as some point in the future; and second Is to enqueue an action to be performed on a different thread than your own. Scheduling messages is accomplished with the the methods like post(Runnable), postAtTime(Runnable, long), postDelayed(Runnable, long), sendEmptyMessage(int), sendMessage(Message), sendMessageAtTime(Message, long), and sendMessageDelayed(Message, long) methods.
  5. When a process is created for your application, its main thread is dedicated to running a message queue that takes care of managing the top-level application objects (activities, broadcast receivers, etc) and any windows they create.
  6. You can create your own threads, and communicate back with the main application thread through a Handler.

What is AsyncTask ?

  1. Async task enables you to implement multi threading without get hands dirty into threads. AsyncTask enables proper and easy use methods that allows performing background operations and passing the results back to the UI thread.

  2. If you are doing something isolated related to UI, for example downloading data to present in a list, go ahead and use AsyncTask. AsyncTasks should ideally be used for short operations (a few seconds at the most.)

  3. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

  4. In onPreExecute you can define code, which need to be executed before background processing starts.

  5. doInBackground have code which needs to be executed in background, here in doInBackground we can send results to multiple times to event thread by publishProgress() method, to notify background processing has been completed we can return results simply.

  6. onProgressUpdate() method receives progress updates from doInBackground method, which is published via publishProgress method, and this method can use this progress update to update event thread onPostExecute() method handles results returned by doInBackground

  7. The generic types used are Params, the type of the parameters sent to the task upon execution, Progress, the type of the progress units published during the background computation.

Result, the type of the result of the background computation.

  1. If an async task not using any types, then it can be marked as Void type.
  2. An running async task can be cancelled by calling cancel(boolean) method.
Zar E Ahmer
  • 32,807
  • 18
  • 222
  • 281
0

Simple and Clear Answer as below

AsynTask:

Its give a simple implementation of thread without knowing anything about java thread model, AsyncTask gives various callback respective to worker thread and main thread.

Use: for small waiting operation like

fetching some data from web services and display over layout. Database query. When you realise that running operation is never - ever get nested.

Handler

Its Also implementation java thread model, its allowing nesting you running operation like fetching multiple images from internet.

Its best fit for:

1 Its allow to message queuing. 2. Message scheduling. 3. Multiple long running operation.

Thread

Now its time to thread.

Thread is parent of both, AsyncTask is internally using thread, that's mean you can also create your own tread model like AsyncTask and Handler instance is associated with a single thread and that thread's message queue. It require a good knowledge of java Multi-Threading Implementation.

Uses:

You can do all those things which is doable by AsyncTask and Handler.

1'hafs
  • 519
  • 7
  • 24
0

Documentation Says

Handler

  • android.os.Handler

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue.

Each Handler instance is associated with a single thread and that thread's message queue.

When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.

Scheduling messages is accomplished with the post, postAtTime(Runnable, long), postDelayed, sendEmptyMessage, sendMessage, sendMessageAtTime, and sendMessageDelayed methods.

The post versions allow you to enqueue Runnable objects to be called by the message queue when they are received; the sendMessage versions allow you to enqueue a Message object containing a bundle of data that will be processed by the Handler's handleMessage method (requiring that you implement a subclass of Handler).

When posting or sending to a Handler, you can either allow the item to be processed as soon as the message queue is ready to do so, or specify a delay before it gets processed or absolute time for it to be processed.

The latter two allow you to implement timeouts, ticks, and other timing-based behavior.

When a process is created for your application, its main thread is dedicated to running a message queue that takes care of managing the top-level application objects (activities, broadcast receivers, etc) and any windows they create.

You can create your own threads, and communicate back with the main application thread through a Handler.

This is done by calling the same post or sendMessage methods as before, but from your new thread.

The given Runnable or Message will then be scheduled in the Handler's message queue and processed when appropriate.


AsyncTask

  • android.os.AsyncTask

AsyncTask enables proper and easy use of the UI thread.

This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework.

AsyncTasks should ideally be used for short operations (a few seconds at the most.)

If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread.

An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

Usage

AsyncTask must be subclassed to be used.

The subclass will override at least one method (doInBackground), and most often will override a second one (onPostExecute.)

Here is an example of subclassing:

 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

Once created, a task is executed very simply:

new DownloadFilesTask().execute(url1, url2, url3);

AsyncTask's generic types

The three types used by an asynchronous task are the following:

Params, the type of the parameters sent to the task upon execution. Progress, the type of the progress units published during the background computation. Result, the type of the result of the background computation. Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:

private class MyTask extends AsyncTask { ... }

The 4 steps

When an asynchronous task is executed, the task goes through 4 steps:

onPreExecute(), invoked on the UI thread immediately after the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.

doInBackground, invoked on the background thread immediately after onPreExecute() finishes executing.

This step is used to perform background computation that can take a long time.

The parameters of the asynchronous task are passed to this step.

The result of the computation must be returned by this step and will be passed back to the last step.

This step can also use publishProgress to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate step.

onProgressUpdate, invoked on the UI thread after a call to publishProgress. The timing of the execution is undefined.

This method is used to display any form of progress in the user interface while the background computation is still executing.

For instance, it can be used to animate a progress bar or show logs in a text field.

onPostExecute, invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

Cancelling a task

A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true.

After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns.

To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)

Threading rules There are a few threading rules that must be followed for this class to work properly:

The AsyncTask class must be loaded on the UI thread. This is done automatically as of android.os.Build.VERSION_CODES.JELLY_BEAN.

The task instance must be created on the UI thread.

execute must be invoked on the UI thread.

Do not call onPreExecute(), onPostExecute, doInBackground, onProgressUpdate manually.

The task can be executed only once (an exception will be thrown if a second execution is attempted.)

Memory observability

AsyncTask guarantees that all callback calls are synchronized in such a way that the following operations are safe without explicit synchronizations.

Set member fields in the constructor or onPreExecute, and refer to them in doInBackground.

Set member fields in doInBackground, and refer to them in onProgressUpdate and onPostExecute.

Order of execution

When first introduced, AsyncTasks were executed serially on a single background thread. Starting with android.os.Build.VERSION_CODES.DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel.

Starting with android.os.Build.VERSION_CODES.HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.

If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.

Don Chakkappan
  • 7,157
  • 5
  • 43
  • 57
  • Instead of copying the docs, why didnt you just post the links instead? Lol, you even copied and pasted the `Developer Guides, For more information...`. – Biu Jan 20 '15 at 07:03
  • @Biu Thanks for the comment . Its not just copy & paste . I made some editing . Have you noticed it? . I just want to put an answer from authorized sources. – Don Chakkappan Jan 20 '15 at 07:05