Handler通信
介绍
Handler:负责发送消息及处理消息
Looper:复制不断的从消息队列中取出消息,并且给发送本条消息的Handler
MessageQueue:负责存储消息
Message:消息本身,负责携带数据
1. Handler的构造方法
public Handler(Callback callback, boolean async) {
//......
//返回与当前线程关联的Looper对象
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
//返回Looper对象的消息队列
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
构造方法的过程中会做下几件事:
获取当前Handler实例所在线程的Looper对象:mLooper = Looper.myLooper()
如果Looper不为空,则获取Looper的消息队列,赋值给Handler的成员变量mQueue:mQueue = mLooper.mQueue
2. MessageQueue 消息队列
Handler.sendMessage -> sendMessageDelyed -> MessageQueue.enqueueMessage
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
synchronized (this) {
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
handler.sendMessage 其实只是把我们的 Message 加入了消息队列MessageQueue ,队列采用的是链表的方式,按照 when 也就是时间排序
为什么 MessageQueue 消息队列要采用链表的方式去存储我们 Message ?
链表和数组的区别?链表是增加删除快,数组是查询快
3. Loop 消息循环
子线程中使用 Handler 必须先调用 Looper.prepare(); 不然会报错,我们在主线程中并没有调用过 Looper.prepare(),为什么就不报错?
因为在我们应用启动的时候,ActivityThread 的入口函数 main() 方法中已经帮我们写了这行代码
Looper.prepareMainLooper();// 准备循环
sThreadLocal.set(new Looper(quitAllowed));
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
就是创建一个 Looper ,并且保证一个 Thread 线程中,只有一个 Looper 对象
Looper.loop(); //循环
public static void loop() {
// 获取线程的 Looper 对象
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
// 获取队列
final MessageQueue queue = me.mQueue;
for (;;) {
// 死循环不断的获取 消息队列中的消息
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
try {
// 通过 handler 去执行 Message 这个时候就调用了 handleMessage 方法
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
// 回收消息
msg.recycleUnchecked();
}
}
本文详细解析了Handler在Android中的核心作用,包括它的构造过程、MessageQueue的链表存储策略,以及Looper的循环机制。重点讨论了为何在未显式调用Looper.prepare()的情况下主线程不会报错,以及Looper如何确保每个线程的唯一性和消息处理的正确执行。
1533

被折叠的 条评论
为什么被折叠?



