Handler vs AsyncTask vs Thread OR Handler vs AsyncTask OR AsyncTask vs Thread OR Handler vs Thread confuse? It can be your next interview question so let’s start a study about it.
AsyncTask and Handler are written in Java (internally they use a Thread
), so everything you can do with Handler
or AsyncTask
, you can achieve this using a Thread
too.
Android Handler
Handler is background threads that provide you to communicate with the UI. Updating a progress bar for instance should be done via.Handler
Using Handlers you have the advantage of,MessagingQueues
so if you want to schedule messages or update multiple UI elements or have repeating tasks.
Andriod AsyncTask
AsyncTask are similar, in fact, they make use of Handler, but don’t run in the UI thread, so it’s good for fetching data, for instance fetching web services. Later you can interact with the UI.
Here is an example of AsyncTask – Android AsyncTask example with a progress bar in kotlin
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.
Some uses for small waiting operations like the following:
- Fetching some data from web services and display over the layout.
- Database query.
- When you realize that running operation will never, ever be nested.
Thread in Android
Thread, however, can’t interact with the UI, provide more “basic” threading.
If you use Java threads you have 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
What can Handler and AsyncTask really help you with?
The most obvious reason is communication between the caller thread and the worker thread. (Caller Thread: A thread which calls the Worker Thread to perform some task. A Caller Thread does not necessarily have to be the UI thread). Of course, you can communicate between two threads in other ways, but there are many disadvantages (and dangers) due to thread safety issues.
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.