Reputation: 298
Android offers Handler and loopers to send messages/run code directly on the UI thread from any background thread. If you look into the implementation of the mechanism, you will find that inside the loop()
method, there is an infinite loop running that waits/polls for the message.
My question is that, even after having an infinite loop in the thread, how is android able to keep the UI responsive and running rest of the code in the same thread?
Upvotes: 0
Views: 49
Reputation: 11121
The main thread of an Android app is responsible for the UI. It needs to handle all touch events and do all the drawing* at the same time.
The infinite loop in the main looper keeps the thread alive while it's waiting for some user interaction.
The only way to keep the UI responsive is to make sure that all the blocks of code that run on the main thread (via the message queue and the looper) finish their work quickly. This is the developer's responsibility.
It's not hard to block the main thread. If some callback that you implement takes more than 1/60 of a second to execute then the UI will degrade (animations will not run smoothly, clicks and scrolls will lag behind, etc).
If the main thread is blocked for more than a few seconds, the user will get the "application not responding" (ANR) dialog.
[*] All the drawing for software layers. For hardware accelerated layers, most of the drawing is done by the GPU.
Upvotes: 0