获得Message对象的三种方式
1.new Message()
2.Message.obtain()
3.handler.obtainMessage()
1.new Message();
这个方法没什么好多说的就是new一个对象
2.Message.obtain();
点进去看源码:
/**
* Return a new Message instance from the global pool. Allows us to
* avoid allocating new objects in many cases.
*/
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
看注释可知道,从消息池中返回一个新的实例,避免我们创建更多的实例对象,那么这个消息池是什么呢?我们找一下:
private static Message sPool;
private static final int MAX_POOL_SIZE = 50;
消息池最多能够保存50个消息,这里类似于线程池,同时根据源码我们也可以知道obtain()方法是线程安全的。所以通过这种方法创建Message对象可以避免创建新的Message对象,达到节省内存的作用。(ps:handler处理完消息,消息队列会自动recycle()释放消息,有时候我们在使用的时候会报该消息还在使用,这是因为这个消息还未处理,我们又发送了这个消息,这时我们只需要重新创建一个消息。)
3.handler.obtainMessage();
/**
* 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.
*/
public final Message obtainMessage()
{
return Message.obtain(this);
}
/**
* Same as {@link #obtain()}, but sets the values for both <em>target</em> and
* <em>what</em> members on the Message.
* @param h Value to assign to the <em>target</em> member.
* @param what Value to assign to the <em>what</em> member.
* @return A Message object from the global pool.
*/
public static Message obtain(Handler h, int what) {
Message m = obtain();//调用了obtain方法
m.target = h;
m.what = what;
return m;
}
从注释可以知道,这个函数会将handler对象赋值给message.taget,如果不想要这种便利,可以调用Message.obtain()函数,个人比较倾向于使用handler.obtainMessage();
总结:
1.new Message()没有任何技术含量
2.Message.obtain(),从消息池中复用Message对象,节省内存,而且现成安全
3.handler.obtainMessage()会将handler赋值给message.target,提供便利
在使用的过程中,使用Message.obtain(),或者handler.obtainmessage()