现在的位置: 首页 > 综合 > 正文

Handler.obtainMessage()

2013年09月15日 ⁄ 综合 ⁄ 共 1193字 ⁄ 字号 评论关闭

转自:http://www.cnblogs.com/android007/archive/2012/05/10/2494766.html
话说在工作中第一次接触android 的Handler 的时候,不知道怎么去关注性能。

记得当时这么写的:

Message msg = new Message()
msg.what = xxx;
msg.arg1  = xxx;
msg.arg2  = xxx;
handler.sendMessage(msg);

这样写也没有绝得不好,反正当时项目的功能实现了。(性能上还可以)

后来没事的时候看了看handler 的其他的方法,就看到了obtainMessage()这个方法.很奇怪,不知道为何还要出来的方法

本来上面的那段code 就能实现handler 的功能了,为什么还要出现他,后来百度google 一把,大家说 什么性能上有差别之

类的。。。。。结果可想而知(大部分的文章都是你抄我的我抄你的,技术就是这样出来的。。鄙视这种抄写别人博客文章而

不著名转载出处的人)。于是我就去看源码能否看到一些好的描述。

复制代码
Message msg = handler.obtainMessage();
msg.what = xxx;
msg.arg1  = xxx;
msg.arg2  = xxx;
msg.obj    = xxx;

.................... 
复制代码

看看这两段代码其实就是方法不一样 ,参数都一样。但是为何实现的效果一样还要分离出来这么多方法呢?

到源码去看个究竟吧!

先去看sendMessage()这个方法。。。。它调用的是Handler 中的sendMessage(Message msg)

源码 片段1  如下:

?
/**
     *
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);
    }

 再看handler.obtainMessage()源码 片段2 如下:

抱歉!评论已关闭.