handler、 looper 和messagequeue

前言

handler是android 開(kāi)發(fā)重要的組成部分贪嫂,主要用于在不同的線程中相互通信寺庄,使用場(chǎng)景最多的應(yīng)該就是在子線程中更新 UI。想要開(kāi)發(fā)android首先要熟知handler力崇。

幾個(gè)重要的概念

Handler:處理與發(fā)送消息(Message)
Message:消息的包裝類(lèi)
Looper:整個(gè) Handler 通信的核心斗塘,接受 Handler 發(fā)送的 Message,循環(huán)遍歷 MessageQueue 中的 Message亮靴,并發(fā)送至 Handler 處理
MessageQueue:保存 Message
LocalThread:存儲(chǔ) Looper 與 Looper所在線程的信息

一線程可以有幾個(gè)handler 幾個(gè)looper馍盟?

從如下源代碼中我們不難發(fā)現(xiàn),主線程創(chuàng)建完looper后會(huì)賦值給成員變量茧吊,每次創(chuàng)建也會(huì)檢測(cè)該變量的值是否存在贞岭,如果已創(chuàng)建則會(huì)拋出異常,子線程類(lèi)似搓侄,不過(guò)存儲(chǔ)的時(shí)候放在了sThreadLocal中瞄桨。

public static void prepare() {
        prepare(true);
    }

    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));
    }
   public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

Handler 如何與 Looper 關(guān)聯(lián)起來(lái)

Looper.myLooper() 方法將 Looper 對(duì)象賦值給當(dāng)前 Handler 中的 mLooper,在調(diào)用 mLooper.mQueue 將 Looper 中的 MessageQueue 賦值給 mQueue讶踪。

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;
}

looper.loop()為啥不會(huì)造成ANR

anr 是應(yīng)用在規(guī)定時(shí)間內(nèi)執(zhí)行啟動(dòng)服務(wù)芯侥,廣播,contentprovider乳讥,事件的時(shí)候指定時(shí)間未給以回應(yīng)(....DoneExecutinglock)筹麸。然后我們回到
loop的主要代碼如下,劃重點(diǎn)雏婶,輪訓(xùn)消息 queue.next()----> 隊(duì)列中有消息----> nativePollOnce(ptr, nextPollTimeoutMillis) ,如果隊(duì)列中無(wú)消息線程就會(huì)進(jìn)入休眠狀態(tài)物赶,再次受到消息enqueueMessage(Message msg, long when) ----->nativeWake() ---->繼續(xù)輪詢(xún)queue.next()

/**
 * Run the message queue in this thread. Be sure to call
 * {@link #quit()} to end the loop.
 */
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
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            return;
        }
        // This must be in a local variable, in case a UI event sets the logger
        final Printer logging = me.mLogging;
        if (logging != null) {
            logging.println(">>>>> Dispatching to " + msg.target + " " +
                    msg.callback + ": " + msg.what);
        }
        final long traceTag = me.mTraceTag;
        if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
            Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }
        try {
            msg.target.dispatchMessage(msg);
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        ......
        msg.recycleUnchecked();
    }
}

IdleHandler的觸發(fā)時(shí)間

當(dāng)輪訓(xùn)消息的結(jié)果為null或者當(dāng)前的時(shí)間now< message.when取出來(lái)所有的消息并回調(diào)IdleHandler 的queueIdle(),所以在activty 生命周期執(zhí)行完成之前 留晚,也就是我們經(jīng)常在OnCreat()中延遲執(zhí)行的代碼都可以換成idleHandler酵紫,以避免影響生命周期的調(diào)用。

 Message next() {
        // Return here if the message loop has already quit and been disposed.
        // This can happen if the application tries to restart a looper after quit
        // which is not supported.
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }

            nativePollOnce(ptr, nextPollTimeoutMillis);

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }

                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose();
                    return null;
                }

                // If first time idle, then get the number of idlers to run.
                // Idle handles only run if the queue is empty or if the first message
                // in the queue (possibly a barrier) is due to be handled in the future.
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }

                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }

            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            for (int i = 0; i < pendingIdleHandlerCount; i++) {
                final IdleHandler idler = mPendingIdleHandlers[i];
                mPendingIdleHandlers[i] = null; // release the reference to the handler

                boolean keep = false;
                try {
                    keep = idler.queueIdle();
                } catch (Throwable t) {
                    Log.wtf(TAG, "IdleHandler threw exception", t);
                }

                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;

            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            nextPollTimeoutMillis = 0;
        }
    }
boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }

        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.next
                prev.next = msg;
            }

            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末错维,一起剝皮案震驚了整個(gè)濱河市奖地,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌赋焕,老刑警劉巖参歹,帶你破解...
    沈念sama閱讀 218,204評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異隆判,居然都是意外死亡犬庇,警方通過(guò)查閱死者的電腦和手機(jī)僧界,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,091評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)臭挽,“玉大人捂襟,你說(shuō)我怎么就攤上這事』斗澹” “怎么了葬荷?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,548評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)纽帖。 經(jīng)常有香客問(wèn)我宠漩,道長(zhǎng),這世上最難降的妖魔是什么懊直? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,657評(píng)論 1 293
  • 正文 為了忘掉前任扒吁,我火速辦了婚禮,結(jié)果婚禮上吹截,老公的妹妹穿的比我還像新娘瘦陈。我一直安慰自己,他們只是感情好波俄,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,689評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布晨逝。 她就那樣靜靜地躺著,像睡著了一般懦铺。 火紅的嫁衣襯著肌膚如雪嗡害。 梳的紋絲不亂的頭發(fā)上揽浙,一...
    開(kāi)封第一講書(shū)人閱讀 51,554評(píng)論 1 305
  • 那天剧蚣,我揣著相機(jī)與錄音崇渗,去河邊找鬼。 笑死急前,一個(gè)胖子當(dāng)著我的面吹牛醒陆,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播裆针,決...
    沈念sama閱讀 40,302評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼刨摩,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了世吨?” 一聲冷哼從身側(cè)響起澡刹,我...
    開(kāi)封第一講書(shū)人閱讀 39,216評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎耘婚,沒(méi)想到半個(gè)月后罢浇,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,661評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,851評(píng)論 3 336
  • 正文 我和宋清朗相戀三年嚷闭,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了攒岛。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,977評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡凌受,死狀恐怖阵子,靈堂內(nèi)的尸體忽然破棺而出思杯,到底是詐尸還是另有隱情胜蛉,我是刑警寧澤,帶...
    沈念sama閱讀 35,697評(píng)論 5 347
  • 正文 年R本政府宣布色乾,位于F島的核電站誊册,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏暖璧。R本人自食惡果不足惜案怯,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,306評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望澎办。 院中可真熱鬧嘲碱,春花似錦、人聲如沸局蚀。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,898評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)琅绅。三九已至扶欣,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間千扶,已是汗流浹背料祠。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,019評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留澎羞,地道東北人髓绽。 一個(gè)月前我還...
    沈念sama閱讀 48,138評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像妆绞,于是被迫代替她去往敵國(guó)和親顺呕。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,927評(píng)論 2 355