Message.obtain() 和Handler.obtainMessage()的区别

xiaoxiao2021-02-28  42

Message.obtain() 和Handler.obtainMessage()的区别

性能更优越

尽管Message的构造器是公开的,但是获取Message对象的最好方法是调用Message.obtain()或者Handler.obtainMessage(), 这样是从一个可回收对象池中获取Message对象。

这两种方式都比直接new一个Message对象在性能上更优越.

具体表现在这里从一个池子里返回一个Message实例对象,避免通过new创建过多的对象.

/** * 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 Handler mHandler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case 1: textShowTV.setText("展示中..."); break; } }; }; Message mess = Message.obtain(); mess.what =1; //mHandler.obtainMessage(1)与上两行的代码一样,可以参考源码查看 // Message mess = mHandler.obtainMessage(1); mHandler.sendMessage(mess);

两种的结果是一样的源码中有如下展示:

Handler类中也是调用Message类中的方法

/** * Same as {@link #obtainMessage()}, except that it also sets the what member of the returned Message. * * @param what Value to assign to the returned Message.what field. * @return A Message from the global message pool. */ public final Message obtainMessage(int what) { return Message.obtain(this, what); }

Hander中removeMessages方法

1、这个方法使用的前提是之前调用过sendEmptyMessageDelayed(0, time),意思是延迟time执行handler中msg.what=0的方法;

2、在延迟时间未到的前提下,执行removeMessages(0),则上面的handler中msg.what=0的方法取消执行;

3、在延迟时间已到,handler中msg.what=0的方法已执行,再执行removeMessages(0),不起作用。

4、该方法会将handler对应message队列里的消息清空,通过msg.what来找到对应的message。

5、当队列中没有message则handler会不工作,但并不是handler会停止,当队列中有新的message进来后,会继续处理执行。

转载请注明原文地址: https://www.6miu.com/read-79274.html

最新回复(0)