sendMessage()这个方法调用的是Handler中的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);
}
而handler.obtainMessage()源码见下:
/**
* Returns a new <a target=_blank href="mailto:{@link">{@link</a> android.os.Message Message} from the global message pool.
* More efficient than creating and allocating new instances.
* The retrieved message has its handler set to this instance
* (Message.target == this).
* If you don't want that facility, just call Message.obtain() instead.
*/
public final Message obtainMessage() {
return Message.obtain(this);
}
上面这两段都是Handler里面的方法,不过在第一段中我们可以看到Message是我们作为参数传过去的,而第二段则是Message帮我们处理,它调用obtain(Handler h)方法,之后我们还要调用Message中sendToTarget()这个方法。
看一下Message.obtain(Hanlder h)的源码:
/**
* Same as {@link #obtain()}, but sets the value for the <em>target</em> member on the Message return
* ed.
* @param h Handler to assign to the returned Message object's <em>target</em> member.
* @return A Message object from the global pool.
*/
public static Message obtain(Handler h) {
Message m = obtain();
m.target = h;
return m;
}
再看 sendToTarget() 源码:
/**
* 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);
}
这里的target就是handler,sendToTarget()又在调用handler的sendMessage方法了。因此sendToTarget()的本质也是调用Handler的sendMessage方法。
其实细心的同学已经看到了,注意看源码的注释:
/**
* Returns a new {@link android.os.Message Message} from the global message pool. More efficient than
* creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this).
* If you don't want that facility, just call Message.obtain() instead.
*/
这里我们的Message已经不是自己创建的了,而是从MessagePool拿的,省去了创建对象申请内存的开销,因此无需重新申请,效率较高。到这里大家应该都明白了,所以以后使用的时候尽量使用 Message msg = handler.obtainMessage();的形式创建Message,不要自己New Message。至于message产生之后你使用obtainMessage或者是sendMessage效率影响并不大。同时我们也要注意以后谈论性能的时候要找准位置,譬如这里性能的问题不是在调用obtainMessage和sendMessage的方法上,而是调用他们之前对象的创建问题上。
本文转自网络博客小茜的博文 http://zuizui0122.blog.163.com/blog/static/18816618920137195294662