博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Handler 的sendEmptyMessage(int what)和sendMessage(Message msg)有啥区别?
阅读量:4608 次
发布时间:2019-06-09

本文共 2002 字,大约阅读时间需要 6 分钟。

    做一个手机助手查看器,碰到里面的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机制要深入了解的,请参考上面那位大三“老师”的博客文章:。

 

 

转载于:https://www.cnblogs.com/wangsanfeng/archive/2012/11/02/2751641.html

你可能感兴趣的文章
[Vue-rx] Stream an API using RxJS into a Vue.js Template
查看>>
解决VC几个编译问题的方法——好用
查看>>
SPOJ #11 Factorial
查看>>
City Upgrades
查看>>
“人少也能办大事”---K2 BPM老客户交流会
查看>>
关于七牛进行图片添加文字水印操作小计
查看>>
DataSource数据库的使用
查看>>
CentOS开启samba实现文件共享
查看>>
MSSQL使用sqlbulkcopy批量插入数据
查看>>
证明一个数能被3整除,当且仅当它的各位数的和能被3整除
查看>>
2018秋寒假作业4—PTA编程总结1
查看>>
android自适应屏幕
查看>>
2019-北航面向对象-电梯作业总结
查看>>
SqlHelper
查看>>
初识算法、数据结构
查看>>
Luogu4069 SDOI2016 游戏 树链剖分、李超线段树
查看>>
Java的内部类真的那么难以理解?
查看>>
一文搞懂Java环境,轻松实现Hello World!
查看>>
hash实现锚点平滑滚动定位
查看>>
也谈智能手机游戏开发中的分辨率自适应问题
查看>>