上边为谷歌推荐的Handler使用方法,通过以上代码 理解下Looper Handler MessageQueue相关代码
private static void prepare(boolean quitAllowed) { if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper(quitAllowed));//保证每个线程只有一个Looper对象 }Looper与MessageQueue绑定:
private Looper(boolean quitAllowed) { //每个Looper唯一对应一个MessageQueue 即一个线程对应一个Looper 一个MessageQueue mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }Looper自循环
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; Binder.clearCallingIdentity(); final long ident = Binder.clearCallingIdentity(); for (;;) {//无线循环 Message msg = queue.next(); // might block if (msg == null) { return; } msg.target.dispatchMessage(msg);//回调dispatchMessage方法 msg.recycleUnchecked(); } }下面是Handler将消息添加到MessageQunue的流程:
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"); msg.recycle(); return false; } msg.markInUse(); msg.when = when; Message p = mMessages; boolean needWake; if (p == null || when == 0 || when < p.when) { msg.next = p; mMessages = msg; needWake = mBlocked; } else { 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; prev.next = msg; // 最后一个p为null 将message插入到倒数第二个位置 } if (needWake) { nativeWake(mPtr); } } return true; }以上就是Looper Handler MessageQueue实现线程间通信的大致逻辑~
新闻热点
疑难解答