Handler 的sendEmptyMessage(int what)和sendMessage(Message msg)有啥區別?

    做一個手機助手查看器,碰到裏面的Handler用sendEmptyMessage(int what)發消息,其實也可以用sendMessage(Message msg)的,但兩者到底有啥區別?GOOGLE一下,沒有看到什麼好的答案,倒是看到一個大三的傢伙有模有樣的分析起來了安卓類的源代碼,SHIT,此刻的我真是汗顏,不過老子說得好嘛---故師者,無長無優,聞道有先後而已。哦,記錯了,是韓愈說的。收到了啓發,也開始看起類的源代碼起來。

   其實兩者沒區別,請看下面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);
}

就是調用了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)的實現和上面一樣,請看:

/**
* 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中就是構建了一個Message,然後把這個Message的what設置成sendEmptyMessage方法中的What參數即可。

  一切恍然大悟!

  然後,在主線程中,Looper類的loop()通過 調用: msg.target.dispatchMessage(msg),調用Hanler類的dispatchMessage(Message msg)方法,從而在主線程中處理了這個Message.

  如果對Handler機制要深入瞭解的,請參考上面那位大三“老師”的博客文章:http://www.cnblogs.com/codingmyworld/archive/2011/09/14/2174255.html

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章