一、Message
Message创建方式有两种,一种是new Message(),开销较大,另外一种是Message.obtain(),使用回收但是没有被释放的message对象,减少开销,有点类似Adapter中的ConvertView与ViewHolder,一般使用Message msg = Handler.obtain(),事实上也是调用Message.Obtain().
Handler.class
/**
* 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);
}
Message.class
/**
* 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;
sPoolSize--;
return m;
}
}
return new Message();
}
通过recycle回收的Message对象
Message.class
/**
* Return a Message instance to the global pool. You MUST NOT touch
* the Message after calling this function -- it has effectively been
* freed.
*/
public void recycle() {
clearForRecycle();
synchronized (sPoolSync) {
i