---
title: " android源码解析--Message"
author: "2129286"
date: "2014-05-10T11:13:54Z"
tags: []
categories: ["移动开发"]
slug: "android-message"
draft: false
lastmod: "2014-05-10T11:13:54Z"
id: 2064576
url: "https://2129286.iteye.com/blog/2064576"
---

看下类定义：

 

**\[java]** [view plain](http://blog.csdn.net/lilu_leo/article/details/8169884 "view plain")[copy](http://blog.csdn.net/lilu_leo/article/details/8169884 "copy")

1. Defines a message containing a description and arbitrary data object that can be sent to a Handler. This object contains two extra int fields and an extra object field that allow you to not do allocations in many cases.
2. While the constructor of Message is public, the best way to get one of these is to call Message.obtain() or one of the Handler.obtainMessage() methods, which will pull them from a pool of recycled objects.

 

 

定义一个包含任意类型的描述数据对象，此对象可以发送给Handler。对象包含两个额外的int字段和一个额外的对象字段，这样可以使得在很多情况下不用做分配工作。尽管Message的构造器是公开的，但是获取Message对象的最好方法是调用Message.obtain()或者Handler.obtainMessage(), 这样是从一个可回收对象池中获取Message对象。

 

**\[java]** [view plain](http://blog.csdn.net/lilu_leo/article/details/8169884 "view plain")[copy](http://blog.csdn.net/lilu_leo/article/details/8169884 "copy")

1. public final class Message implements Parcelable

Message类是个final类，就是说不能被继承，同时Message类实现了Parcelable接口，我们知道android提供了一种新的类型：Parcel。本类被用作封装数据的容器，封装后的数据可以通过Intent或IPC传递。 除了基本类型以外，只有实现了Parcelable接口的类才能被放入Parcel中。

 

看一下全局变量：

 

**\[java]** [view plain](http://blog.csdn.net/lilu_leo/article/details/8169884 "view plain")[copy](http://blog.csdn.net/lilu_leo/article/details/8169884 "copy")

01. /\**
02. * User-defined message code so that the recipient can identify
03. * what this message is about. Each {@link Handler} has its own name-space
04. * for message codes, so you do not need to worry about yours conflicting
05. * with other handlers.
06. \*/
07. public int what;
08. /\**
09. * arg1 and arg2 are lower-cost alternatives to using
10. * {@link #setData(Bundle) setData()} if you only need to store a
11. * few integer values.
12. \*/
13. public int arg1;
14. /\**
15. * arg1 and arg2 are lower-cost alternatives to using
16. * {@link #setData(Bundle) setData()} if you only need to store a
17. * few integer values.
18. \*/
19. public int arg2;
20. /\**
21. * An arbitrary object to send to the recipient.  When using
22. * {@link Messenger} to send the message across processes this can only
23. * be non-null if it contains a Parcelable of a framework class (not one
24. * implemented by the application).   For other data transfer use
25. * {@link #setData}.
26. \*
27. * &lt;p&gt;Note that Parcelable objects here are not supported prior to
28. * the {@link android.os.Build.VERSION\_CODES#FROYO} release.
29. \*/
30. public Object obj;
31. /\**
32. * Optional Messenger where replies to this message can be sent.  The
33. * semantics of exactly how this is used are up to the sender and
34. * receiver.
35. \*/
36. public Messenger replyTo;
37. /\** If set message is in use \*/
38. /\*package\*/ static final int FLAG\_IN\_USE = 1;
39. /\** Flags reserved for future use (All are reserved for now) \*/
40. /\*package\*/ static final int FLAGS\_RESERVED = ~FLAG\_IN\_USE;
41. /\** Flags to clear in the copyFrom method \*/
42. /\*package\*/ static final int FLAGS\_TO\_CLEAR\_ON\_COPY\_FROM = FLAGS\_RESERVED | FLAG\_IN\_USE;
43. /\*package\*/ int flags;
44. /\*package\*/ long when;
45. /\*package\*/ Bundle data;
46. /\*package\*/ Handler target;
47. /\*package\*/ Runnable callback;
48. // sometimes we store linked lists of these things
49. /\*package\*/ Message next;
50. private static final Object sPoolSync = new Object();
51. private static Message sPool;
52. private static int sPoolSize = 0;
53. private static final int MAX\_POOL\_SIZE = 10;

 

1. what：用户定义消息代码以便收件人可以识别这是哪一个Message。每个Handler用它自己的名称空间为消息代码,所以您不需要担心你的Handler与其他handler冲突。
2. arg1、arg2：如果只是想向message内放一些整数值，可以使用arg1和arg2来代替setData方法。
3. obj：发送给接收器的任意对象。当使用Message对象在线程间传递消息时，如果它包含一个Parcelable的结构类（不是由应用程序实现的类），此字段必须为非空（non-null）。其他的数据传输则使用setData(Bundle)方法。注意Parcelable对象是从FROYO版本以后才开始支持的。
4. replyTo：指明此message发送到何处的可选Messenger对象。具体的使用方法由发送者和接受者决定。
5. FLAG\_IN\_USE：判断Message是否在使用（ default 包内可见）
6. FLAGS\_RESERVED：留个将来使用？？
7. FLAGS\_TO\_CLEAR\_ON\_COPY\_FROM：明确在copyFrom方法
8. 其他参数都比较简单，不详述

 

下面看obtain方法：

 

**\[java]** [view plain](http://blog.csdn.net/lilu_leo/article/details/8169884 "view plain")[copy](http://blog.csdn.net/lilu_leo/article/details/8169884 "copy")

01. /\**
02. * Return a new Message instance from the global pool. Allows us to
03. * avoid allocating new objects in many cases.
04. \*/
05. public static Message obtain() {
06. synchronized (sPoolSync) {
07. if (sPool != null) {
08. Message m = sPool;
09. sPool = m.next;
10. m.next = null;
11. sPoolSize--;
12. return m;
13. }
14. }
15. return new Message();
16. }

从全局池中返回一个新的Message实例。在大多数情况下这样可以避免分配新的对象。

 

在看它一系列的重载方法：

 

**\[java]** [view plain](http://blog.csdn.net/lilu_leo/article/details/8169884 "view plain")[copy](http://blog.csdn.net/lilu_leo/article/details/8169884 "copy")

01. /\**
02. * Same as {@link #obtain(Handler)}, but assigns a callback Runnable on
03. * the Message that is returned.
04. * @param h  Handler to assign to the returned Message object's &lt;em&gt;target&lt;/em&gt; member.
05. * @param callback Runnable that will execute when the message is handled.
06. * @return A Message object from the global pool.
07. \*/
08. public static Message obtain(Handler h, Runnable callback) {
09. Message m = obtain();
10. m.target = h;
11. m.callback = callback;
12. return m;
13. }
14. /\**
15. * Same as {@link #obtain()}, but sets the values for both &lt;em&gt;target&lt;/em&gt; and
16. * &lt;em&gt;what&lt;/em&gt; members on the Message.
17. * @param h  Value to assign to the &lt;em&gt;target&lt;/em&gt; member.
18. * @param what  Value to assign to the &lt;em&gt;what&lt;/em&gt; member.
19. * @return A Message object from the global pool.
20. \*/
21. public static Message obtain(Handler h, int what) {
22. Message m = obtain();
23. m.target = h;
24. m.what = what;
25. return m;
26. }
27. /\**
28. * Same as {@link #obtain()}, but sets the values of the &lt;em&gt;target&lt;/em&gt;, &lt;em&gt;what&lt;/em&gt;, and &lt;em&gt;obj&lt;/em&gt;
29. * members.
30. * @param h  The &lt;em&gt;target&lt;/em&gt; value to set.
31. * @param what  The &lt;em&gt;what&lt;/em&gt; value to set.
32. * @param obj  The &lt;em&gt;object&lt;/em&gt; method to set.
33. * @return  A Message object from the global pool.
34. \*/
35. public static Message obtain(Handler h, int what, Object obj) {
36. Message m = obtain();
37. m.target = h;
38. m.what = what;
39. m.obj = obj;
40. return m;
41. }
42. /\**
43. * Same as {@link #obtain()}, but sets the values of the &lt;em&gt;target&lt;/em&gt;, &lt;em&gt;what&lt;/em&gt;,
44. * &lt;em&gt;arg1&lt;/em&gt;, and &lt;em&gt;arg2&lt;/em&gt; members.
45. \*
46. * @param h  The &lt;em&gt;target&lt;/em&gt; value to set.
47. * @param what  The &lt;em&gt;what&lt;/em&gt; value to set.
48. * @param arg1  The &lt;em&gt;arg1&lt;/em&gt; value to set.
49. * @param arg2  The &lt;em&gt;arg2&lt;/em&gt; value to set.
50. * @return  A Message object from the global pool.
51. \*/
52. public static Message obtain(Handler h, int what, int arg1, int arg2) {
53. Message m = obtain();
54. m.target = h;
55. m.what = what;
56. m.arg1 = arg1;
57. m.arg2 = arg2;
58. return m;
59. }
60. /\**
61. * Same as {@link #obtain()}, but sets the values of the &lt;em&gt;target&lt;/em&gt;, &lt;em&gt;what&lt;/em&gt;,
62. * &lt;em&gt;arg1&lt;/em&gt;, &lt;em&gt;arg2&lt;/em&gt;, and &lt;em&gt;obj&lt;/em&gt; members.
63. \*
64. * @param h  The &lt;em&gt;target&lt;/em&gt; value to set.
65. * @param what  The &lt;em&gt;what&lt;/em&gt; value to set.
66. * @param arg1  The &lt;em&gt;arg1&lt;/em&gt; value to set.
67. * @param arg2  The &lt;em&gt;arg2&lt;/em&gt; value to set.
68. * @param obj  The &lt;em&gt;obj&lt;/em&gt; value to set.
69. * @return  A Message object from the global pool.
70. \*/
71. public static Message obtain(Handler h, int what,
72. int arg1, int arg2, Object obj) {
73. Message m = obtain();
74. m.target = h;
75. m.what = what;
76. m.arg1 = arg1;
77. m.arg2 = arg2;
78. m.obj = obj;
79. return m;
80. }

都是先调用obtain()方法，然后把获取的Message实例加上各种参数。

 

 

**\[java]** [view plain](http://blog.csdn.net/lilu_leo/article/details/8169884 "view plain")[copy](http://blog.csdn.net/lilu_leo/article/details/8169884 "copy")

01. /\**
02. * Return a Message instance to the global pool.  You MUST NOT touch
03. * the Message after calling this function -- it has effectively been
04. * freed.
05. \*/
06. public void recycle() {
07. clearForRecycle();
08. synchronized (sPoolSync) {
09. if (sPoolSize &lt; MAX\_POOL\_SIZE) {
10. next = sPool;
11. sPool = this;
12. sPoolSize++;
13. }
14. }
15. }

向全局池中返回一个Message实例。一定不能在调用此函数后再使用Message——它会立即被释放。

 

 

**\[java]** [view plain](http://blog.csdn.net/lilu_leo/article/details/8169884 "view plain")[copy](http://blog.csdn.net/lilu_leo/article/details/8169884 "copy")

01. /\**
02. * Make this message like o.  Performs a shallow copy of the data field.
03. * Does not copy the linked list fields, nor the timestamp or
04. * target/callback of the original message.
05. \*/
06. public void copyFrom(Message o) {
07. this.flags = o.flags & ~FLAGS\_TO\_CLEAR\_ON\_COPY\_FROM;
08. this.what = o.what;
09. this.arg1 = o.arg1;
10. this.arg2 = o.arg2;
11. this.obj = o.obj;
12. this.replyTo = o.replyTo;
13. if (o.data != null) {
14. this.data = (Bundle) o.data.clone();
15. } else {
16. this.data = null;
17. }
18. }

使此message跟参数o相似。浅拷贝数据域。不拷贝源message的链表字段，时间戳和目标/回调。

 

 

**\[java]** [view plain](http://blog.csdn.net/lilu_leo/article/details/8169884 "view plain")[copy](http://blog.csdn.net/lilu_leo/article/details/8169884 "copy")

1. /\**
2. * Return the targeted delivery time of this message, in milliseconds.
3. \*/
4. public long getWhen() {
5. return when;
6. }

 

设置一个任意数据值的Bundle对象。如果可以，使用arg1和arg2域发送一些整型值以减少消耗。

参考

         getData()

         peekData()

返回此消息的传输时间，以毫秒为单位。

 

**\[java]** [view plain](http://blog.csdn.net/lilu_leo/article/details/8169884 "view plain")[copy](http://blog.csdn.net/lilu_leo/article/details/8169884 "copy")

1. public void setTarget(Handler target) {
2. this.target = target;
3. }

设置目标handler（接收其消息的Handler）。

 

 

**\[java]** [view plain](http://blog.csdn.net/lilu_leo/article/details/8169884 "view plain")[copy](http://blog.csdn.net/lilu_leo/article/details/8169884 "copy")

01. /\**
02. * Retrieve the a {@link android.os.Handler Handler} implementation that
03. * will receive this message. The object must implement
04. * {@link android.os.Handler#handleMessage(android.os.Message)
05. * Handler.handleMessage()}. Each Handler has its own name-space for
06. * message codes, so you do not need to
07. * worry about yours conflicting with other handlers.
08. \*/
09. public Handler getTarget() {
10. return target;
11. }

获取将接收此消息的Handler对象。此对象必须要实现Handler.handleMessage()方法。每个handler各自包含自己的消息代码，所以不用担心自定义的消息跟其他handlers有冲突。

 

 

**\[java]** [view plain](http://blog.csdn.net/lilu_leo/article/details/8169884 "view plain")[copy](http://blog.csdn.net/lilu_leo/article/details/8169884 "copy")

01. /\**
02. * Retrieve callback object that will execute when this message is handled.
03. * This object must implement Runnable. This is called by
04. * the &lt;em&gt;target&lt;/em&gt; {@link Handler} that is receiving this Message to
05. * dispatch it.  If
06. * not set, the message will be dispatched to the receiving Handler's
07. * {@link Handler#handleMessage(Message Handler.handleMessage())}.
08. \*/
09. public Runnable getCallback() {
10. return callback;
11. }

获取回调对象，此对象会在message处理时执行。此对象必须实现Runnable接口。回调由接收此消息并分发的目标handler调用。如果没有设置回调，此消息会分发到接收handler的handleMessage(Message)。

 

 

**\[java]** [view plain](http://blog.csdn.net/lilu_leo/article/details/8169884 "view plain")[copy](http://blog.csdn.net/lilu_leo/article/details/8169884 "copy")

01. /\**
02. * Obtains a Bundle of arbitrary data associated with this
03. * event, lazily creating it if necessary. Set this value by calling
04. * {@link #setData(Bundle)}.  Note that when transferring data across
05. * processes via {@link Messenger}, you will need to set your ClassLoader
06. * on the Bundle via {@link Bundle#setClassLoader(ClassLoader)
07. * Bundle.setClassLoader()} so that it can instantiate your objects when
08. * you retrieve them.
09. * @see #peekData()
10. * @see #setData(Bundle)
11. \*/
12. public Bundle getData() {
13. if (data == null) {
14. data = new Bundle();
15. }
16. return data;
17. }

 

 

获取附加在此事件上的任意数据的Bundle对象，需要时延迟创建。通过调用setData(Bundle)来设置Bundle的值。需要注意的是，如果通过Messenger对象在进程间传递数据时，需要调用Bundle类的Bundle.setClassLoader()方法来设置ClassLoader，这样当接收到消息时可以实例化Bundle里的对象。

         参考

                  peekData()

                  setData(Bundle)

**\[java]** [view plain](http://blog.csdn.net/lilu_leo/article/details/8169884 "view plain")[copy](http://blog.csdn.net/lilu_leo/article/details/8169884 "copy")

01. /\**
02. * Like getData(), but does not lazily create the Bundle.  A null
03. * is returned if the Bundle does not already exist.  See
04. * {@link #getData} for further information on this.
05. * @see #getData()
06. * @see #setData(Bundle)
07. \*/
08. public Bundle peekData() {
09. return data;
10. }

 

与getData()相似，但是并不延迟创建Bundle。如果Bundle对象不存在返回null。更多信息见getData()。

         参考

                   getData()

                   setData(Bundle)

**\[java]** [view plain](http://blog.csdn.net/lilu_leo/article/details/8169884 "view plain")[copy](http://blog.csdn.net/lilu_leo/article/details/8169884 "copy")

1. /\**
2. * Sets a Bundle of arbitrary data values. Use arg1 and arg1 members
3. * as a lower cost way to send a few simple integer values, if you can.
4. * @see #getData()
5. * @see #peekData()
6. \*/
7. public void setData(Bundle data) {
8. this.data = data;
9. }

 

设置一个任意数据值的Bundle对象。如果可以，使用arg1和arg2域发送一些整型值以减少消耗。

参考

         getData()

         peekData()

**\[java]** [view plain](http://blog.csdn.net/lilu_leo/article/details/8169884 "view plain")[copy](http://blog.csdn.net/lilu_leo/article/details/8169884 "copy")

1. /\**
2. * Sends this Message to the Handler specified by {@link #getTarget}.
3. * Throws a null pointer exception if this field has not been set.
4. \*/
5. public void sendToTarget() {
6. target.sendMessage(this);
7. }

向Handler发送此消息，getTarget()方法可以获取此Handler。如果这个字段没有设置会抛出个空指针异常。

 

**\[java]** [view plain](http://blog.csdn.net/lilu_leo/article/details/8169884 "view plain")[copy](http://blog.csdn.net/lilu_leo/article/details/8169884 "copy")

01. void clearForRecycle() {
02. flags = 0;
03. what = 0;
04. arg1 = 0;
05. arg2 = 0;
06. obj = null;
07. replyTo = null;
08. when = 0;
09. target = null;
10. callback = null;
11. data = null;
12. }

default方法，包内可见，清空所有数据。

 

 

**\[java]** [view plain](http://blog.csdn.net/lilu_leo/article/details/8169884 "view plain")[copy](http://blog.csdn.net/lilu_leo/article/details/8169884 "copy")

1. /\*package\*/ boolean isInUse() {
2. return ((flags & FLAG\_IN\_USE) == FLAG\_IN\_USE);
3. }
4. /\*package\*/ void markInUse() {
5. flags |= FLAG\_IN\_USE;
6. }

获取Message是否在使用和标记为使用。

 

构造方法：

 

**\[java]** [view plain](http://blog.csdn.net/lilu_leo/article/details/8169884 "view plain")[copy](http://blog.csdn.net/lilu_leo/article/details/8169884 "copy")

1. /\** Constructor (but the preferred way to get a Message is to call {@link #obtain() Message.obtain()}).
2. \*/
3. public Message() {
4. }

跟推荐使用Message.obtain()方法。

 

toString方法：

 

**\[java]** [view plain](http://blog.csdn.net/lilu_leo/article/details/8169884 "view plain")[copy](http://blog.csdn.net/lilu_leo/article/details/8169884 "copy")

01. public String toString() {
02. return toString(SystemClock.uptimeMillis());
03. }
04. String toString(long now) {
05. StringBuilder   b = new StringBuilder();
06. b.append("{ what=");
07. b.append(what);
08. b.append(" when=");
09. TimeUtils.formatDuration(when-now, b);
10. if (arg1 != 0) {
11. b.append(" arg1=");
12. b.append(arg1);
13. }
14. if (arg2 != 0) {
15. b.append(" arg2=");
16. b.append(arg2);
17. }
18. if (obj != null) {
19. b.append(" obj=");
20. b.append(obj);
21. }
22. b.append(" }");
23. return b.toString();
24. }

 

**\[java]** [view plain](http://blog.csdn.net/lilu_leo/article/details/8169884 "view plain")[copy](http://blog.csdn.net/lilu_leo/article/details/8169884 "copy")

01. public static final Parcelable.Creator&lt;Message&gt; CREATOR
02. = new Parcelable.Creator&lt;Message&gt;() {
03. public Message createFromParcel(Parcel source) {
04. Message msg = Message.obtain();
05. msg.readFromParcel(source);
06. return msg;
07. }
08. public Message\[] newArray(int size) {
09. return new Message\[size];
10. }
11. };

什么作用？

 

 

**\[java]** [view plain](http://blog.csdn.net/lilu_leo/article/details/8169884 "view plain")[copy](http://blog.csdn.net/lilu_leo/article/details/8169884 "copy")

1. public int describeContents() {
2. return 0;
3. }

 

 

描述了包含在Parcelable对象排列信息中的特殊对象的类型。

返回值

         一个标志位，表明Parcelable对象特殊对象类型集合的排列。

**\[java]** [view plain](http://blog.csdn.net/lilu_leo/article/details/8169884 "view plain")[copy](http://blog.csdn.net/lilu_leo/article/details/8169884 "copy")

01. public void writeToParcel(Parcel dest, int flags) {
02. if (callback != null) {
03. throw new RuntimeException(
04. "Can't marshal callbacks across processes.");
05. }
06. dest.writeInt(what);
07. dest.writeInt(arg1);
08. dest.writeInt(arg2);
09. if (obj != null) {
10. try {
11. Parcelable p = (Parcelable)obj;
12. dest.writeInt(1);
13. dest.writeParcelable(p, flags);
14. } catch (ClassCastException e) {
15. throw new RuntimeException(
16. "Can't marshal non-Parcelable objects across processes.");
17. }
18. } else {
19. dest.writeInt(0);
20. }
21. dest.writeLong(when);
22. dest.writeBundle(data);
23. Messenger.writeMessengerOrNullToParcel(replyTo, dest);
24. }
25. private final void readFromParcel(Parcel source) {
26. what = source.readInt();
27. arg1 = source.readInt();
28. arg2 = source.readInt();
29. if (source.readInt() != 0) {
30. obj = source.readParcelable(getClass().getClassLoader());
31. }
32. when = source.readLong();
33. data = source.readBundle();
34. replyTo = Messenger.readMessengerOrNullFromParcel(source);
35. }

将类的数据写入外部提供的Parcel中和从Parcel中读取数据。