本文主要是介绍Anroid Handler,ThreadLocalMap,MessageQueue,Looper各类关系详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.总的关系
每个线程持有一个ThreadLocalMap对象,而ThreadLocalMap中包含了一个ThreadLocal<Looper>对象,ThreadLocal对象中存储了Looper对象,而Looper对象里又包含了MessageQueue队列,MessageQueue里是Message对象。Message对象的target属性指向了Handler对象。然后Handler在初始化的时候会通过当前线程的Looper获得一个MessageQueque。
2.Handler的初始化过程
可以看到Handler默认通过Looper获取了当前线程的MessageQueue
public Handler(Callback callback, boolean async) {if (FIND_POTENTIAL_LEAKS) {final Class<? extends Handler> klass = getClass();if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&(klass.getModifiers() & Modifier.STATIC) == 0) {Log.w(TAG, "The following Handler class should be static or leaks might occur: " +klass.getCanonicalName());}}mLooper = Looper.myLooper();if (mLooper == null) {throw new RuntimeException("Can't create handler inside thread that has not called Looper.prepare()");}mQueue = mLooper.mQueue;mCallback = callback;mAsynchronous = async;}
3.Handler发送Message
通过post或sendMessageDelayed或sendMessage或post提交的消息最终都会调用handler的sendMessageAtTime方法,方法的第二个参数是由SystemClock.uptimeMillis()+延迟的毫秒数组成,方法最后调用了enqueueMessage方法将消息放入队列
SystemClock.uptimeMillis()表示系统开机到当前的时间总数,单位是毫秒
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {MessageQueue queue = mQueue;if (queue == null) {RuntimeException e = new RuntimeException(this + " sendMessageAtTime() called with no mQueue");Log.w("Looper", e.getMessage(), e);return false;}return enqueueMessage(queue, msg, uptimeMillis);
}
在enqueueMessage中,我们看到它将消息的target指向当前Handler对象,然后调用了MessageQueue的enqueueMessage方法
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {msg.target = this;if (mAsynchronous) {msg.setAsynchronous(true);}return queue.enqueueMessage(msg, uptimeMillis);}
MessageQueue的数据结构,是一个单向链表,Message对象有个next字段保存列表中的下一个,MessageQueue中的mMessages保存链表的第一个元素。
这里看MessageQueue的enqueueMessage方法,当队列没有元素或消息的执行时间小于链表头部元素的执行时间,消息直接被插入到头部,否则按时间先后插入到队列中
boolean enqueueMessage(Message msg, long when) {...synchronized (this) {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.nextprev.next = msg;}...}return true;}
4.Handler接收Message
Message的接收可以从Lopper的loop方法看起,loop方法是一个死循环,它不断从当前线程的消息队列中取出消息调用MessageQueue的next方法, 并且执行消息对应Handler的dispatchMessage(msg)方法。
public static void loop() {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;// Make sure the identity of this thread is that of the local process,// and keep track of what that identity token actually is.Binder.clearCallingIdentity();final long ident = Binder.clearCallingIdentity();for (;;) {Message msg = queue.next(); // might block...try {msg.target.dispatchMessage(msg);end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();}...}
再看看Handler的dispatchMesage方法,这里的msg.callback是通过post方法提交的Runnable,如果是post方法提交的就会执行Runnable的run方法,如果没有设置callback就会调用我们重写的handleMessage方法。
public void dispatchMessage(Message msg) {if (msg.callback != null) {handleCallback(msg);} else {if (mCallback != null) {if (mCallback.handleMessage(msg)) {return;}}handleMessage(msg);}}
至此Message的发送和接收都清楚了
这篇关于Anroid Handler,ThreadLocalMap,MessageQueue,Looper各类关系详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!