Android缓存优化之message

来源:互联网 发布:33周胎儿正常b超数据 编辑:程序博客网 时间:2024/05/29 21:37

在获取一个message对象的时候,使用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.

*/

从整个Messge池中返回一个新的Message实例,尽量使用它,因为它能避免分配新的对象,因为通过调用obtainMessage方法获取Message对象就能避免创建对象,从而减少内存的开销了。


obtainMessage的原型:

Message android.os.Handler.obtainMessage(int what, int arg1, int arg2, Object obj)

public final Message obtainMessage (int what, int arg1, int arg2, Object obj)
Since: API Level 1
Same as obtainMessage(), except that it also sets the what, obj, arg1,and arg2 values on the returned Message.
Parameters
what  Value to assign to the returned Message.what field.
arg1  Value to assign to the returned Message.arg1 field.
arg2  Value to assign to the returned Message.arg2 field.
obj  Value to assign to the returned Message.obj field.


通过handler.obtainMessage复用之前的message,如下:

    
0 0
原创粉丝点击