sendEmptymessage 和sendMessage的区别

无意中一次碰到Handler用sendEmptyMessage(int what)发消息,后面有一次面试也被问到,那么和sendMessage()两者有啥区别?追根溯源来看看handler类的源代码。

其实两者没区别,请看下面Handler的源代码,先看sendEmptyMessage:

/**
* 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.
看到这里明白了,其实这两个方法是一样一样的,一个传Message类型的msg,一个传int类型的what,传what的,最终会转为msg。

  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值