ι Copyright Notice: This article for Bo Master original article, without Bo Master permission not reproduced.
First look at the definition of handler:
/*** A Handler allows you to send and process {@linkMessage} and Runnable * objects associated with a thread ' s {@linkMessageQueue}. Each Handler * instance are associated with a single thread and that thread ' s message * queue. When you create a new Handler, it's bound to the thread/* Message queue of the the thread that's creating it-from that Point on, * it'll deliver messages and runnables to that message queue and execute * them as they come out of the MESSAG E queue. * * <p>there is both main uses for a Handler: (1) to schedule messages and * Runnables to being executed as some point In the future; and (2) to enqueue * The action to being performed on a different thread than your own. * ..... **/ Public classHandler {...}
From the source code in the definition of handler and comments, we know that handler is mainly used to send and process messages. Each instance of a handler is associated with a thread and the MessageQueue of that thread. Hadnler has 2 main functions: ① at some point in the future to send or process a message or runnable (POST method) ② in another thread to process messages (send method).
Then look at the construction method of handler:
PublicHandler () { This(NULL,false); } ... .. PublicHandler (Callback Callback,Booleanasync) { if(find_potential_leaks) {Finalclass<?extendsHandler> Klass =getclass (); if((Klass.isanonymousclass () | | klass.ismemberclass () | | klass.islocalclass ()) &&(Klass.getmodifiers ()& modifier.static) = = 0) {LOG.W (TAG,"The following Handler class should be static or leaks might occur:" +klass.getcanonicalname ()); }} mlooper=Looper.mylooper (); if(Mlooper = =NULL) { Throw NewRuntimeException ("Can ' t create handler inside thread that have not called looper.prepare ()"); } mqueue=Mlooper.mqueue; Mcallback=callback; Masynchronous=Async; } ...
By the construction method, if the current thread does not have Looper, if the handler object is created, it throws "can ' t create handler inside thread that have not called looper.prepare ()" Exception. Therefore, you must create a handler in a thread that has looper, otherwise the program throws an exception.
The work of handler mainly includes the sending and receiving process of the message. The sending of messages can be accomplished through a series of methods of Post and a series of methods of send. Here's a list of post methods:
Public Final BooleanPost (Runnable r) {returnSendmessagedelayed (Getpostmessage (R), 0); } Public Final BooleanPostattime (Runnable R,LongUptimemillis) { returnSendmessageattime (Getpostmessage (R), Uptimemillis); } Public Final BooleanPostattime (Runnable R, Object token,LongUptimemillis) { returnSendmessageattime (Getpostmessage (r, token), uptimemillis); } Public Final BooleanPostdelayed (Runnable R,LongDelaymillis) { returnsendmessagedelayed (Getpostmessage (R), Delaymillis); } Public Final BooleanPostatfrontofqueue (Runnable r) {returnSendmessageatfrontofqueue (Getpostmessage (R)); }
Through the source code, we can know that the post of a series of methods are ultimately through send a series of methods to achieve.
The following is a series of Send message Source:
Public Final BooleansendMessage (Message msg) {returnsendmessagedelayed (MSG, 0); } Public Final BooleanSendemptymessage (intWhat ) { returnsendemptymessagedelayed (What, 0); } Public Final BooleanSendmessagedelayed (Message msg,LongDelaymillis) { if(Delaymillis < 0) {Delaymillis= 0; } returnSendmessageattime (MSG, systemclock.uptimemillis () +Delaymillis); } Public BooleanSendmessageattime (Message msg,LongUptimemillis) {MessageQueue Queue=Mqueue; if(Queue = =NULL) {runtimeexception e=NewRuntimeException ( This+ "Sendmessageattime () called with no Mqueue"); LOG.W ("Looper", E.getmessage (), E); return false; } returnenqueuemessage (Queue, MSG, uptimemillis); }
It is known from the source that the process of handler sending a message is actually inserting a message into the message queue.
By how MessageQueue works and how Looper works we can tell that when a new message is inserted into the MessageQueue, the next method returns the message to Looper,looper and starts processing the message. However, the final looper is to process the message by calling handler's DispatchMessage method, that is, the message is eventually handed over to the handler for processing.
The following is the source of handler's DispatchMessage method, as follows:
Public voidDispatchMessage (Message msg) {if(Msg.callback! =NULL) {handlecallback (msg); } Else { if(Mcallback! =NULL) { if(Mcallback.handlemessage (msg)) {return; }} handlemessage (msg); } } Private Static voidhandlecallback (Message message) {Message.callback.run (); }
First, the callback of the message is determined to be null, and if not NULL, the Handlecallback method is called.
The message has attributes:/*package*/Runnable callback; Then, Message.callback is the runnable parameter passed by the handler post method. Combined with the source of the Handlecallback method, the Handlecallback method is actually to open a sub-thread, to deal with the Post method.
Look at the source of the DispatchMessage method, if the message callback is empty, then determine whether Mcallback is null, by the handler source code:
Final Callback mcallback; Public Interface Callback { publicboolean handlemessage (Message msg); } /** * Subclasses must implement this to receive messages. */ Public void handlemessage (Message msg) { }
The callback is an interface, and the Handlemessage method is defined. From this we can think of, when we need to obtain a handler instance, we can inherit handler, rewrite Handlemessage method, we can also implement the callback interface, and then implement the Handlemessage method in the interface.
Then look at the source code of the DispatchMessage method, if Mcallback is null, finally call the Handlemessage method to process the message.
In the development process, when processing messages with handler, we generally need to rewrite the Handlemessage method, and the logic of handling the message is written by us.
"Original" Source angle analysis Android message mechanism series (vi) how--handler works