Looper , Handler and MessageQueue (I)
In this part, I’d like to explain these concepts in a store which make it easier to understand.
All of this concepts are related to a special thread — Message loop thread.
Message loop thread is a special thread. Because it works by using a message queue. Main thread is a message loop thread.
The message queue is a list of messaged dispatched by the Looper. Messages are not added directly to the queue. Instead, it is added by the handler.
Looper: A looper is an object to manage a thread message queue. A quite straightforward name. It loops the message queue and pick up some tasks. Then send the task to handler to processing the message.
Hander: A Handler allows you to post and process tasks(two types: Message and Runnable ). By default, A handler will be automatically attached to the thread who created it.
The work process in a story.
(I got this idea from the book <Android programming — the big nerd ranch guide>)
HandlerThread is a shoe store(any store you like). Handler and Looper are two workers here. They work together, but have clear duties.
Handler is good at talking. So he stand in front of the store to get all of the tasks(Messages or Runnable). For every task, Handler will attach a notes which describes the customers requirements. Sometimes, the task is easy, just make one word — shining. Then his collegue will know how to do it (This is the Message). But some customers are really picky. Customers will list the steps to repair the shoes. This kind of task is the runnable which encapsulate the details to finish the work.
Looper is experienced at repairing the shoes. He has a special shoe shelf to put all of the shoes which is the Message queue. All tasks are put there. If Handler get the task, he will put the task on the message queue. He will not talk to the looper directly, because this will interupt looper’s work.
Usullay, a HandlerThread store already have a Looper. But they need to hire the Handler, one or more. If we see the handler stand in this store, by default, we think the Handler belongs to this store. (If we create a instance in current thread, by default, it is attached to this thread. )
HanderThread will open every morning. Remeber to call HandlerThread.start() to open the store.
They will close the store every afternoon after all works done. Remeber to close the store by calling HandlerThread.quit(). Or the workers will stay in store doing nothing but you have to pay them.
How to communicate with other thread?
If the Looper repaired the shoes, they need to return it to the customer. Fortunately, the customer left their contact information. But the customer themslves are busy with making money. They hired their handler to fetch their shoes.
That is, creat the handler in another thread, say the Main thread. Pass it to the current thread. Post the finished messages back to the main thread. Then everything is done.