public final boolean sendEmptyMessage(int what)
{
return sendEmptyMessageDelayed(what, 0);
}
再点进sendEmptyMessageDelayed(what, 0)
/**
* 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);
}
从sendEmptyMessageDelayed(int what, long delayMillis)方法中 可以看到what参数赋给了obtain出来的Message对象
再从obtainMessage(1,data)的源码中看
/**
*
* Same as {@link #obtainMessage()}, except that it also sets the what and obj members
* of the returned Message.
*
* @param what Value to assign to the returned Message.what field.
* @param obj Value to assign to the returned Message.obj field.
* @return A Message from the global message pool.
*/
public final Message obtainMessage(int what, Object obj)
{
return Message.obtain(this, what, obj);
}
/**
* Sends this Message to the Handler specified by {@link #getTarget}.
* Throws a null pointer exception if this field has not been set.
*/
public void sendToTarget() {
target.sendMessage(this);
}
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
第二個方法可以對所發送的訊息進行判斷,從而進行不同的處理。如果沒有分類處理的需求,發一個空訊息就夠了。
從源碼看
先是
sendEmptyMessage(int what)
sendEmptyMessage(int what)
再点进
sendEmptyMessageDelayed(what, 0)
从
sendEmptyMessageDelayed(int what, long delayMillis)
方法中可以看到what参数赋给了obtain出来的Message对象
再从
obtainMessage(1,data)
的源码中看方法返回
Message.obtain(this, what, obj)
,接着继续看obtain(this, what, obj)
方法里面Message也是通过obtain来获取的,不过这里还将obj对象赋给了Message。
sendToTarget()
的源码中的target是Handler,就是调用了sendMessage()
方法
rrreeesendEmptyMessage(int what)
和obtainMessage(int what, Object obj).sendToTarget()
rrreee再點進
sendEmptyMessageDelayed(what, 0)
從
sendEmptyMessageDelayed(int what, long delayMillis)
方法中可以看到what參數賦給了obtain出來的Message物件
再從
obtainMessage(1,data)
的原始碼看🎜 rrreee 🎜方法回傳Message.obtain(this, what, obj)
,接著繼續看obtain(this, what, obj)
🎜 rrreee 🎜方法裡面Message也是透過obtain來取得的,不過這裡還將obj物件賦給了Message。 🎜sendToTarget()
的原始碼中的target是Handler,就是呼叫了sendMessage()
方法🎜 rrreee rrreee🎜
sendEmptyMessage(int what)
和obtainMessage(int what, Object obj).sendToTarget()
🎜最大的差異就是沒有了Object這個物件🎜 🎜參考:🎜Handler 的sendEmptyMessage(int what)和sendMessage(Message msg)有啥差異? 🎜Handler sendMessage 與 obtainMessage (sendToTarget)比較🎜沒啥太大不同,第一個是發送空訊息,第二個是從訊息池取一個訊息發送。
沒什麼不同,只是提供了多樣的API給你用,怎麼用的習慣就怎麼用