android postDelayed實(shí)現(xiàn)

2015-01-18 12:00

在android中做延時(shí)處理一般用handler.postDelayed()和view.postDelayed(action,delay)來實(shí)現(xiàn)懊蒸,view.postDelayed也是通過handlder.postDelayed來實(shí)現(xiàn)的竿裂,不過有一些特殊處理的地方睛廊。

handler.postDelayed

handler處理延時(shí)邏輯是通過發(fā)送延時(shí)消息來處理的

//source
public final boolean postDelayed(Runnable r, long delayMillis){
     return sendMessageDelayed(getPostMessage(r), delayMillis);
}

sendMessageDelayed:

public final boolean sendMessageDelayed(Message msg, long delayMillis)
  {
      if (delayMillis < 0) {
          delayMillis = 0;
      }
      return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
  }

sendMessageAtTime:

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

將延時(shí)消息放入到消息隊(duì)列中。SystemClock.uptimeMillis()是開機(jī)到現(xiàn)在的時(shí)間(毫秒)拆讯,不包括睡眠的時(shí)間筛圆。不用System.currentTimeMillis()的原因是System.currentTimeMillis()的時(shí)間是可以被System.setCurrentTimeMillis修改的决摧,如果被修改了則發(fā)生難以想象的后果政基。

enqueueMessage調(diào)用MessageQueue.enqueueMessage(msg,uptimeMillis)

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

此處會(huì)將傳入的消息對(duì)象根據(jù)觸發(fā)時(shí)間(when)插入到message queue中。然后判斷是否要喚醒等待中的隊(duì)列胜蛉。
. 如果插在隊(duì)列中間挠进。說明該消息不需要馬上處理,不需要由這個(gè)消息來喚醒隊(duì)列誊册。
. 如果插在隊(duì)列頭部(或者when=0)领突,則表明要馬上處理這個(gè)消息。如果當(dāng)前隊(duì)列正在堵塞案怯,則需要喚醒它進(jìn)行處理君旦。
通過nativeWake方法喚醒隊(duì)列。

looper執(zhí)行MessageQueue中的消息:

for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            try {
                msg.target.dispatchMessage(msg);
            } finally {
                ...
            }

            msg.recycleUnchecked();
        }
    }

只是調(diào)用了MessageQueue.next()方法嘲碱〗鹂常可能會(huì)阻塞。

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

該方法會(huì)先調(diào)用nativePollOnce阻塞麦锯,然后進(jìn)入死循環(huán)捞魁。nativePollOnce()的作用類似與object.wait(),使用了native方法來對(duì)線程進(jìn)行精確時(shí)間的喚醒离咐,
如果head Message是有延遲而且延遲時(shí)間沒到的(now < msg.when),計(jì)算下時(shí)間間隔(nextPollTimeoutMillis),設(shè)置timeout為兩者之差宵蛀,進(jìn)入下一次循環(huán)昆著。
如果Message無延時(shí)或已到達(dá)執(zhí)行時(shí)間,則直接返回該Message.

如果當(dāng)前的Message阻塞住了MessageQueue(pendingIdleHandlerCount <= 0)术陶,把全局變量mBlocked改為true凑懂,在下一個(gè)Message放入隊(duì)時(shí)會(huì)判斷這個(gè)message的位置。如果在queue的頭部梧宫,則用nativeWake喚醒線程接谨。

總結(jié):[msg loop] -->調(diào)用MessageQueue.next(),若頭部的消息需要被執(zhí)行在返回該消息,send該消息之后繼續(xù)調(diào)用next方法獲取下一個(gè)消息塘匣,若頭部的不需要被執(zhí)行則阻塞住隊(duì)列脓豪,若有等待執(zhí)行的Message,計(jì)算一下剩余時(shí)間,繼續(xù)調(diào)用nativePollOnce()阻塞,無限循環(huán)到阻塞時(shí)間到或者下一次有Message進(jìn)隊(duì)忌卤。下個(gè)消息進(jìn)隊(duì)時(shí)若不需要延時(shí)在放在Queue的頭部扫夜,否則在放在Queue的中部。

view.postDelayed

view的延時(shí)也是調(diào)用了handler的postDelayed.

public boolean postDelayed(Runnable action, long delayMillis) {
       final AttachInfo attachInfo = mAttachInfo;
       if (attachInfo != null) {
           return attachInfo.mHandler.postDelayed(action, delayMillis);
       }

       // Postpone the runnable until we know on which thread it needs to run.
       // Assume that the runnable will be successfully placed after attach.
       getRunQueue().postDelayed(action, delayMillis);
       return true;
   }

若view的AttachInfo不為空驰徊,則調(diào)用AttachInfo中的handler的postDelayed笤闯。若AttachInfo為空,則先將action放入RunQueue中棍厂。RunQueue為HandlerActionQueue颗味,用來存放view沒有handler時(shí)的action。

執(zhí)行action:

public void executeActions(Handler handler) {
    synchronized (this) {
        final HandlerAction[] actions = mActions;
        for (int i = 0, count = mCount; i < count; i++) {
            final HandlerAction handlerAction = actions[i];
            handler.postDelayed(handlerAction.action, handlerAction.delay);
        }

        mActions = null;
        mCount = 0;
    }
}

還是需要傳入一個(gè)Handler牺弹,利用handler來執(zhí)行action浦马。當(dāng)view被關(guān)聯(lián)到window時(shí),會(huì)執(zhí)行該隊(duì)列中的Action.

AttachInfo是View的一個(gè)附加信息存儲(chǔ)類例驹,當(dāng)view被關(guān)聯(lián)到window時(shí)會(huì)被賦值捐韩。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市鹃锈,隨后出現(xiàn)的幾起案子荤胁,更是在濱河造成了極大的恐慌,老刑警劉巖屎债,帶你破解...
    沈念sama閱讀 211,348評(píng)論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件仅政,死亡現(xiàn)場離奇詭異,居然都是意外死亡盆驹,警方通過查閱死者的電腦和手機(jī)圆丹,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,122評(píng)論 2 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來躯喇,“玉大人辫封,你說我怎么就攤上這事硝枉。” “怎么了倦微?”我有些...
    開封第一講書人閱讀 156,936評(píng)論 0 347
  • 文/不壞的土叔 我叫張陵妻味,是天一觀的道長。 經(jīng)常有香客問我欣福,道長责球,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,427評(píng)論 1 283
  • 正文 為了忘掉前任拓劝,我火速辦了婚禮雏逾,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘郑临。我一直安慰自己栖博,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,467評(píng)論 6 385
  • 文/花漫 我一把揭開白布牧抵。 她就那樣靜靜地躺著笛匙,像睡著了一般。 火紅的嫁衣襯著肌膚如雪犀变。 梳的紋絲不亂的頭發(fā)上妹孙,一...
    開封第一講書人閱讀 49,785評(píng)論 1 290
  • 那天,我揣著相機(jī)與錄音获枝,去河邊找鬼蠢正。 笑死,一個(gè)胖子當(dāng)著我的面吹牛省店,可吹牛的內(nèi)容都是我干的嚣崭。 我是一名探鬼主播,決...
    沈念sama閱讀 38,931評(píng)論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼懦傍,長吁一口氣:“原來是場噩夢啊……” “哼雹舀!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起粗俱,我...
    開封第一講書人閱讀 37,696評(píng)論 0 266
  • 序言:老撾萬榮一對(duì)情侶失蹤说榆,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后寸认,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體签财,經(jīng)...
    沈念sama閱讀 44,141評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,483評(píng)論 2 327
  • 正文 我和宋清朗相戀三年偏塞,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了唱蒸。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,625評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡灸叼,死狀恐怖神汹,靈堂內(nèi)的尸體忽然破棺而出庆捺,到底是詐尸還是另有隱情,我是刑警寧澤慎冤,帶...
    沈念sama閱讀 34,291評(píng)論 4 329
  • 正文 年R本政府宣布疼燥,位于F島的核電站,受9級(jí)特大地震影響蚁堤,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜但狭,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,892評(píng)論 3 312
  • 文/蒙蒙 一披诗、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧立磁,春花似錦呈队、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,741評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至颅崩,卻和暖如春几于,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背沿后。 一陣腳步聲響...
    開封第一講書人閱讀 31,977評(píng)論 1 265
  • 我被黑心中介騙來泰國打工沿彭, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人尖滚。 一個(gè)月前我還...
    沈念sama閱讀 46,324評(píng)論 2 360
  • 正文 我出身青樓喉刘,卻偏偏與公主長得像,于是被迫代替她去往敵國和親漆弄。 傳聞我的和親對(duì)象是個(gè)殘疾皇子睦裳,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,492評(píng)論 2 348