when it come to handler,we will think of handler, looper, message.
handler:the processor of message,communicate with looper,push the new message into the MessageQueue or receive message send by Looper from MessageQueue
Looper:the processor or circulator of MessageQueue,a thread can product a Looper object,it manages the MessageQueue of this thread
MessageQueue:as the name suggest,it used to store the message witch put in by the thread.it follow the first in and first out principle
message:linked list data structure.it can be reused,in order to avoid wasting memory by creating a large of object
the function of handler
1) schedule message or runnable,receive message,hand out and process message
2) Executing tasks in different threads("to enqueue an action to be performed on a different thread than your own")
how to use
in development,we can't update UI in child thread,so we send the UI message that need to be updated to the handler,and overrid handleMessage() to deal with the UI operations.Message and handler two classes will be used,Message is responsible for loading message,marking messages with target and storing contents with obj;Handler is responsible for the hand out and processing of messages
to avoid memory leaks,we'd better do 2 things:
1) Call removeCallbacksAndMessages(null) in the onDestroy()
2) Set static inner class and weakreference
tips:
a:one thead can only bind one looper,but can have several handler
b:one looper can bind more than one handler
c:one handler can onely bind one looper
workflow of handler
The workflow of handler is executed in the order of message > message queen > loop > handler.
In general, create a handler in the main thread, will directly create the Loop, MessageQueue, and Handler objects in the main thread. The loop object is usually created through the prepare() method.when the looper object is created MessageQueue will be automatically created at the same time.In the worker thread, the handler sends the message through sendmessage() or post(), and in the send() method, enqueuemessage() is used to transmit the message to the message queue,Then looper will take out the message in the MessageQueue through the next () , and send message to the handler through dispatchmessage(). The handler will start processing the message after receiving the message. If the message is not available, the thread will be blocked until there is a message in the message queue.
Top comments (0)