Recently discovered a puzzling problem, when using Handler.post (Runnable) This interface, Runnable sometimes not run, very strange, and later found that because the call to Handler.removemessage (), what parameter passed 0 , resulting in the runnable message is removed, below to see the source code.
1 classMyHandlerextendsHandler {2 @Override3 Public voidhandlemessage (Message msg) {4 Switch(msg.what) {5 CaseMsg_do_some:6LOG.I ("Zhoukewen", "what = = 0 ...");7 Break;8 }9 }Ten } One AHandler h =NewMyHandler (); - - Final intMsg_do_some = 0; the - Public voidOnstartclick (view view) { - - h.sendemptymessage (msg_do_some); +H.post (NewRunnable () { - @Override + Public voidrun () { ALOG.I ("Zhoukewen", "runnable .....")); at } - }); - h.removemessages (msg_do_some); -}
Scenario probably, the developer may want to delete What=msg_do_some msg, but when sg_do_some happens to be equal to 0 o'clock, will carry runnable with the MSG is also deleted, we look at the post source code:
See Handler.java first.
Public Final Boolean Post (Runnable r) { return sendmessagedelayed (Getpostmessage (R), 0); } Private Final Message Getpostmessage (Runnable r) { = message.obtain (); = R; return m; }
See Message.obtain again ()
Public intwhat ; Public StaticMessage obtain () {synchronized(spoolsync) {if(SPool! =NULL) {Message m=SPool; SPool=M.next; M.next=NULL; Spoolsize--; returnm; } } return NewMessage (); }
As you can see, post (Runnable) is actually creating a message, as seen from the code, that the message is either fetched from the spool pool or new, and if new comes out, its member variable is naturally initialized to 0. If obtained from the spool, spool in the message is after recycle () to use, we look at the source:
Public voidRecycle () {clearforrecycle (); synchronized(spoolsync) {if(Spoolsize <max_pool_size) {Next=SPool; SPool= This; Spoolsize++; } } } /* Package*/ voidclearforrecycle () {flags= 0; What= 0; Arg1= 0; Arg2= 0; Obj=NULL; ReplyTo=NULL; when= 0; Target=NULL; Callback=NULL; Data=NULL; }
Sure enough, it's set to 0. So, Handler.post (Runnable) is actually generating a message of what is 0, and when remove, it will delete all the message of what is 0, that is, Runnable's message was deleted, So it leads to the weird problems I've seen before.
Android handler a note for using message