How to use handler in Android App Development
Why use Handler?
There are so many executions in the android applications such as network connections, UI drawing, logic calculations, etc.
They are done simultaneously by using threads.
You can think of a thread as a worker.
Obviously, more workers, more effectiveness.
But it can cause a serious problem; deadlock.
In the ideal case, workers do their job exclusively. but the application is much more complex than you think. Sometimes, it has to be done in sequence and workers compete with the public data. It can lead to deadlock; the situation system is not responded to.
This could happen in the android applications so developers made a rule to prevent it.
It is the “UI handling must be done in main thread” rule.
It means that only one thread(main thread) can manipulate UI including showing pop up, changing the status of the button, inputting text to the box.
What do you think is the most important thing in app development?
In my opinion, good UX(user experience) is the one. It is useless if the user doesn’t use it because of its bad UX.
This could happen when many threads try UI handling. Moreover, the Android UI kit is not thread-safe.
Then, how can another thread hand over the data for UI update to the main thread?
This is why we have to use a handler. It can deliver the data from other threads to the main thread.
Using the handler, we can solve the deadlock problem and make the application a better user experience.
How handler works
Thread1 indicates the main thread where UI handling has proceeded.
In thread 2, the calculated data should be delivered to thread 1 for UI update.
The handler must be defined on the main thread.
After thread 2 finishes the calculation, the result is sent to the handler.
sendMessage() function is called at this time. The message is sent to the message queue in the main thread.
Looper gets the message data one by one from the queue and sends it to the handler again. This process is required because the message data is handled by the handler.
In the handleMessage() function, the handler gets the data from the message and updates the UI.
The important part is that handler is defined on the main thread and UI update is done in the main thread.
Examples
I will show you 3types of handler usage examples.