Skip to content
Advertisement

How does a thread work with Handler in Android?

In the code section given below, I have run a thread on a button click. At first, the thread will set text to the textView, then it will sleep for 6 seconds. But, in reality on the button click, at first, the thread is sleeping for 6 seconds and then it is setting text to the textView. Now, why is this mismatch of statement execution flow happening?

JavaScript

Advertisement

Answer

Android main thread is built upon two core concepts Looper and Handler. It translates to a message loop related to the thread, and messages interactor. All the ui staff benefit on that. For instance used by you setText is nothing more then sending a new message to the looper, after some time the message is resolved by some handler. As you may guess firstly each message is enqueued.

If you look at your example through the prism of above, you see steps listed below.(All steps are taken on main thread / main looper)

JavaScript

According to above, you suspend thread before all the messages including setting text and enabling button are handled. The consequence of that is reversed order.

#UPDATE Then, how can I enqueue this sleep() method also?

JavaScript
Advertisement