上邊為谷歌推薦的Handler使用方法,通過以上代碼 理解下Looper Handler MessageQueue相關(guān)代碼
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唯一對應(yīng)一個MessageQueue 即一個線程對應(yīng)一個Looper 一個MessageQueue mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }Looper自循環(huán)
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 (;;) {//無線循環(huán) Message msg = queue.next(); // might block if (msg == null) { return; } msg.target.dispatchMessage(msg);//回調(diào)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插入到倒數(shù)第二個位置 } if (needWake) { nativeWake(mPtr); } } return true; }以上就是Looper Handler MessageQueue實(shí)現(xiàn)線程間通信的大致邏輯~
新聞熱點(diǎn)
疑難解答