提起Handler,就要提起Message、MessageQueue以及Looper。搞清楚这四者之间的关系,Android开发中的Handler消息处理机制就算掌握了个大概了。
一、Message
Message:包含描述和任意数据对象的消息,用于发送给Handler。
//获取Message实例的方式
Message msg1 = Message.obtain();
//或
Message msg2 = Handler.obtainMessage();
public final class Message implements Parcelable {
public int what;
public int arg1;
public int arg2;
public Object obj;
…
}
Message类中有这几个成员变量描述消息,其中what是消息码,为了让接收者能知道消息是关于什么的。arg1和arg2用于发送一些integer类型的值。obj用于传输任意类型的值。
二、MessageQueue
MessageQueue:顾名思义,消息队列。内部存储着一组消息。对外提供了插入和删除的操作。MessageQueue内部是以单链表的数据结构来存储消息列表的。
获取MessageQueue实例使用Looper.myQueue()方法。
三、Looper
Looper:主要用于给一个线程轮询消息的。线程默认没有Looper,在创建Handler对象前,我们需要为线程创建Looper。
使用Looper.prepare()方法创建Looper,使用Looper.loop()方法运行消息队列。
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
不过在ActivityThread的main方法中,初始化了Looper。这就是为什么我们在主线程中不需要创建Looper的原因。
最后四者之间的关系图: