Thursday 25 September 2014

What Handler and AsyncTask really help you with in Android?

If you see source code of AsyncTask and Handler, you will see their code purely in Java. (of course, there some exceptions, but that is not an important point).

What does it mean ? It means no magic in AsyncTask or Handler. They just make your job easier as a developer.

For example: If Program A calls method A(), method A() would run in a different thread with Program A.You can easily test by:

Thread t = Thread.currentThread();   
 int id = t.getId();

And why you should use new thread ? You can google for it. Many many reasons.

So, what is the difference ?

AsyncTask and Handler are written in Java (internally use a Thread), so everything you can do with Handler or AsyncTask, you can achieve using a Thread too.

What Handler and AsyncTask really help you with?

The most obvious reason is communication between caller thread and worker thread. (Caller Thread: A thread which calls the Worker Thread to perform some task.A Caller Thread may not be the UI Thread always).
 And, of course, you can communicate between two thread by other ways, but there are many disadvantages, for eg: Main thread isn’t thread-safe (in most of time), in other words, DANGEROUS.

That is why you should use Handler and AsyncTask. They do most of the work for you, you just need to know what methods to override.

Difference Handler and AsyncTask: Use AsyncTask when Caller thread is a UI Thread. This is what android document says:

    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

I want to emphasize on two points:

1) Easy use of the UI thread (so, use when caller thread is UI Thread).

2) No need to manipulate handlers. (means: You can use Handler instead of AsyncTask, but AsyncTask is an easier option).

There are many things in this post I haven’t said yet, for example: what is UI Thread, of why it easier. You must know some method behind each kind and use it, you will completely understand why..

@: when you read Android document, you will see:

    Handler allows you to send and process Message and Runnable objects associated with a thread’s Message-queue

They may seem strange at first.Just understand that, each thread has each message queue. (like a To do List), and thread will take each message and do it until message queue empty.
 (Ah, maybe like you finish your work and go to bed). So, when Handler communicates, it just gives a message to caller thread and it will wait to process. (sophiscate ? but you just know that,
Handler can communicate with caller thread in safe-way)

No comments: