做一個手機助手查看器,碰到里面的Handler用sendEmptyMessage(int what)發(fā)消息,其實也可以用sendMessage(Message msg)的,但兩者到底有啥區(qū)別?GOOGLE一下,沒有看到什么好的答案,倒是看到一個大三的家伙有模有樣的分析起來了安卓類的源代碼,SHIT,此刻的我真是汗顏,不過老子說得好嘛---故師者,無長無優(yōu),聞道有先后而已。哦,記錯了,是韓愈說的。收到了啟發(fā),也開始看起類的源代碼起來。
其實兩者沒區(qū)別,請看下面Handler的源代碼:
/**
* Sends a Message containing only the what value.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
public final boolean sendEmptyMessage(int what)
{
return sendEmptyMessageDelayed(what, 0);
}
就是調(diào)用了sendEmptyMessageDelayed()而已,下面看下這個方法:
/**
* Sends a Message containing only the what value, to be delivered
* after the specified amount of time elapses.
* @see #sendMessageDelayed(android.os.Message, long)
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
而sendMessage(Message msg)的實現(xiàn)和上面一樣,請看:
/**
* Pushes a message onto the end of the message queue after all pending messages
* before the current time. It will be received in {@link #handleMessage},
* in the thread attached to this handler.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
原來在sendEmptyMessageDelayed中就是構(gòu)建了一個Message,然后把這個Message的what設(shè)置成sendEmptyMessage方法中的What參數(shù)即可。
一切恍然大悟!
然后,在主線程中,Looper類的loop()通過 調(diào)用: msg.target.dispatchMessage(msg),調(diào)用Hanler類的dispatchMessage(Message msg)方法,從而在主線程中處理了這個Message.