借用别人的图如下:
1.Message
线程间通信就是在传递消息,Message就是消息的载体。常用的有四个字段:
arg1 , arg2 , what ,obj 。源代码如下:
/**
* User-defined message code so that the recipient can identify
* what this message is about. Each {@link Handler} has its own name-space
* for message codes, so you do not need to worry about yours conflicting
* with other handlers.
*/
public int what;
/**
* arg1 and arg2 are lower-cost alternatives to using
* {@link #setData(Bundle) setData()} if you only need to store a
* few integer values.
*/
public int arg1;
/**
* arg1 and arg2 are lower-cost alternatives to using
* {@link #setData(Bundle) setData()} if you only need to store a
* few integer values.
*/
public int arg2;
/**
* An arbitrary object to send to the recipient. When using
* {@link Messenger} to send the message across processes this can only
* be non-null if it contains a Parcelable of a framework class (not one
* implemented by the application). For other data transfer use
* {@link #setData}.
*
* <p>Note that Parcelable objects here are not supported prior to
* the {@link android.os.Build.VERSION_CODES#FROYO} release.
*/
public Object obj;
其中obj可以携带Object对象,其余三个可以携带整形数据。
2.MessageQueue
MessageQueue是消息队列,他主要用于存放所有通过Handler发送的消息(就是每个Message),这部分消息会一直存在于消息队列中,等待被处理。每个线程中只会有一个MessageQueue对象。
3.Looper
每个线程通过Handler发送的消息都保存在MessageQueue中,Looper通过调用loop()方法,就会进入到一个无限循环当中,然后每当发现MessageQueue中存在一条消息,就会将它取出,并传递到Handler的HandleMessage()方法中。每个线程中只会有一个Looper对象。
4.Handler
他主要用于发送和处理消息,一般使用senfMessage()方法,还有其他的sendXXX的方法,最终都是调用了sendMessageAtTime()方法,除了sendMessageAtFrontOfQueue()方法,只要实现了Looper的线程构建Handler类,那么这个Handler实例就获取该Looper线程MessageQueue实例的引用,Handler 在sendMessage()的时候就通过这个引用往消息队列里插入新消息。