1、sendEmptyMessage与sendMessage的区别:
sendMessage()允许你处理Message对象(Message里可以包含数据,)。
sendEmptyMessage(int what)只能放数据。其中参数what作用:就类似于ID,处理消息的时候用于区分你send一个0和1,处理的时候就要判断了if(msg.what == 0){}else if(msg.what == 1){}。
其实两者没区别,请看下面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);
}
/**
* 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);
}
一切恍然大悟!
然后,在主线程中,Looper类的loop()通过 调用: msg.target.dispatchMessage(msg),调用Hanler类的dispatchMessage(Message msg)方法,从而在主线程中处理了这个Message.
2、sendMessageAtTime()与sendEmptyMessageDelay()的区别: