Android消息机制之Message
位置:/frameworks/base/core/java/android/os/Message.java
Message 中常用的变量,callback(Runnable), target(Handler),what(int),obj(Object)
/*package*/ Handler target; /*package*/ Runnable callback; public int what; public Object obj; // sometimes we store linked lists of these things /*package*/ Message next; private static final Object sPoolSync = new Object(); private static Message sPool; private static int sPoolSize = 0; private static final int MAX_POOL_SIZE = 50; |
//构造方法
public Message() { } |
获取空Message(推荐使用)
public static Message obtain() { synchronized (sPoolSync) { //对一个变量进行加锁,进行同步控制 if (sPool != null) { //若不为空,则在消息池中取出空消息 m.flags = 0; // clear in-use flag sPoolSize--; return m; } } return new Message(); }
|
//
/** * 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); } |
//一些常用的Message的函数
public static Message obtain(Handler h, int what) { Message m = obtain(); m.target = h; m.what = what; return m; } /** * Same as {@link #obtain()}, but sets the values of the <em>target</em>, <em>what</em>, and <em>obj</em> * members. * @param h The <em>target</em> value to set. * @paramwhat The <em>what</em> value to set. * @paramobj The <em>object</em> method to set. * @return A Message object from the global pool. */ public static Message obtain(Handler h, int what, Object obj) { Message m = obtain(); m.target = h; m.what = what; m.obj = obj; return m; } |
补充:
1.尽管Message有public的默认构造方法,但是你应该通过Message.obtain()来从消息池中获得空消息对象,以节省资源。
2.如果你的message只需要携带简单的int信息,请优先使用Message.arg1和Message.arg2来传递信息,这比用Bundle更省内存
3.擅用message.what来标识信息,以便用不同方式处理message。