Why?
Let's describe it in detail.
Situation:
I use ui handler to execute a runnable. Also, this ui handler execute and remove some message tasks.
However, sometimes the runnable doesn't be executed.
How come?
Because this ui handler remove the message which message.what is 0,
and handler will remove all the messages which message.what is 0.
The runnable also be removed from the message queue.
For example:
For example:
int UPDATE_PIC = 0;
......
Message msg = new Message();
msg.what = UPDATE_PIC ;
.....
Handler.sendMessage(msg);
Handler.post(new Runnable()....);
.....
.....
Handler.removeMessages(UPDATE_PIC);
Let's look deeper into the Android framework.
We'll see that setting a runnable to handler and the handler calls getPostMessage(Runnable r) .
Message will find a message instance which is used before and recycled in the message pool, if there is one.
Otherwise, just create new one.
Then, handler use the message to wrap this runnable.
Message will find a message instance which is used before and recycled in the message pool, if there is one.
Otherwise, just create new one.
Then, handler use the message to wrap this runnable.
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
Let's check the what variable in Message class.
Class Message {public int what;..... void recycleUnchecked() { // Mark the message as in use while it remains in the recycled object pool. // Clear out all other details. flags = FLAG_IN_USE;what = 0;arg1 = 0; arg2 = 0; ..... } }
The default value of primitive type int in Java is zero.
Also, even the message is recycled, the what variable is reset to zero.
After handler gets a message from pool or a new one, it doesn't set the what variable.
Thus, all the what variable wrapped by message class is zero.
If someone removes the message with what = 0, all the messages with what = 0 and runnables will be removed.
In conclusion, Do not use 0 value as the value of what variable in message instance.
沒有留言:
張貼留言