Android消息機(jī)制--Handler Looper Message

Handler Messsage基本功能介紹

Handler Message是安卓系統(tǒng)提供不同線程間通訊的一種機(jī)制。其中handler負(fù)責(zé)發(fā)送消息纽门,處理消息,Message 負(fù)責(zé)攜帶數(shù)據(jù),MessageQueue負(fù)責(zé)存儲(chǔ)消息,以隊(duì)列的形式對(duì)外提供插入和刪除操作悔叽。Looper負(fù)責(zé)循環(huán)從MessageQueue取消息。

源碼解析

  首先看一下handler發(fā)送消息的幾種用法
// post有兩種方法
  public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }

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

//sendEmptyMessage有兩種方法
  public final boolean sendEmptyMessage(int what)
    {
        return sendEmptyMessageDelayed(what, 0);
    }

    public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageDelayed(msg, delayMillis);
    }

//sendMessage有兩種方法
    public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }

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

根據(jù)上述代碼得知爵嗅,以上前五種方法最后都會(huì)調(diào)用sendMessageDelayed(msg,delayMillis);所以這幾種方法在本質(zhì)上并沒(méi)有區(qū)別娇澎,只不過(guò)使用方式有所區(qū)別。

   接下來(lái)我們看一下Looper是怎么創(chuàng)建的
微信截圖_20200316112718.png

通過(guò)流程圖得知睹晒,在主線程的main方法里調(diào)用了Looper.prepareMainLooper方法


    public static void main(String[] args) {
       ...

        //創(chuàng)建Looper對(duì)象
        Looper.prepareMainLooper(); 
...
        //循環(huán)取消息
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

    public static void prepareMainLooper() {
         //一個(gè)靜態(tài)內(nèi)部類創(chuàng)建Looper 保證單個(gè)線程Looper唯一性
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

  private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        //將創(chuàng)建的Looper對(duì)象方法threadLocal Map對(duì)象里趟庄,map的key是UI線程
        sThreadLocal.set(new Looper(quitAllowed));
    }

   private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

prepareMainLooper()方法調(diào)用了prepare()方法,prepare方法通過(guò)new Looper()創(chuàng)建了Looper對(duì)象并放在了threadLocal里面伪很。

 然后我們看一下new Handler() 做了哪些事情呢戚啥?
handler.png

由上圖得知,我們?cè)趎ew Handler構(gòu)造方法里锉试,分別獲取了mLooper對(duì)象和MessageQueue對(duì)象猫十,這兩個(gè)對(duì)象也就是ActivityThread 中mian方法所創(chuàng)建的,這也就是為什么子線程不能直接new handler()呆盖。

   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());
            }
        }
  //因?yàn)橹骶€程已經(jīng)創(chuàng)建了looper拖云,所以這里可以直接獲取到,而子線程是不能直接獲取的
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
//獲取消息隊(duì)列应又,一個(gè)消息隊(duì)列綁定一個(gè)Looper對(duì)象
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

  public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

  然后我們看一下handler內(nèi)部是如何發(fā)送消息的?
存消息.png

由上圖得知宙项,handler在sendMessage()之后,msg最終存到了MessageQueue里面株扛,MessageQueue里面有一個(gè)mMessages全局變量尤筐,傳過(guò)來(lái)的Msg賦值給了這個(gè)變量。

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

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

    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.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賦值
                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;
    }

最后handler是如何取消息的呢洞就?
取.png

在ActivityThread的main方法里面除了有一個(gè)Looper.prepareMainLooper()還有個(gè)Looper.loop方法叔磷,這是一個(gè)輪詢方法,無(wú)限循環(huán)的從MessageQueue里面取消息奖磁,并通過(guò)handler里面的dispatchMessage()方法將msg返回。(這里值得注意的是這個(gè)loop方法雖然是死循環(huán)繁疤,但是并不會(huì)造成ANR是因?yàn)檫@里調(diào)用了ndk里面的JNI方法咖为,使主線程釋放CPU資源進(jìn)入休眠狀態(tài))

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

        // Allow overriding a threshold with a system prop. e.g.
        // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
        final int thresholdOverride =
                SystemProperties.getInt("log.looper."
                        + Process.myUid() + "."
                        + Thread.currentThread().getName()
                        + ".slow", 0);

        boolean slowDeliveryDetected = false;

        for (;;) {
//從MessageQueue里面取msg
            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;
            long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
            long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
            if (thresholdOverride > 0) {
                slowDispatchThresholdMs = thresholdOverride;
                slowDeliveryThresholdMs = thresholdOverride;
            }
            final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
            final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);

            final boolean needStartTime = logSlowDelivery || logSlowDispatch;
            final boolean needEndTime = logSlowDispatch;

            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }

            final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
            final long dispatchEnd;
            try {
                msg.target.dispatchMessage(msg);
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (logSlowDelivery) {
                if (slowDeliveryDetected) {
                    if ((dispatchStart - msg.when) <= 10) {
                        Slog.w(TAG, "Drained");
                        slowDeliveryDetected = false;
                    }
                } else {
                    if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
                            msg)) {
                        // Once we write a slow delivery log, suppress until the queue drains.
                        slowDeliveryDetected = true;
                    }
                }
            }
            if (logSlowDispatch) {
                showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
            }

            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }

            // Make sure that during the course of dispatching the
            // identity of the thread wasn't corrupted.
            final long newIdent = Binder.clearCallingIdentity();
            if (ident != newIdent) {
                Log.wtf(TAG, "Thread identity changed from 0x"
                        + Long.toHexString(ident) + " to 0x"
                        + Long.toHexString(newIdent) + " while dispatching to "
                        + msg.target.getClass().getName() + " "
                        + msg.callback + " what=" + msg.what);
            }

            msg.recycleUnchecked();
        }
    }

//通過(guò)dispatchMessage方法將msg傳出去
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
//對(duì)應(yīng)handler.post()方法
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

另外補(bǔ)充一下常見(jiàn)面試問(wèn)題:
1.Handler是如何實(shí)現(xiàn)線程切換的?
答:其實(shí)就是這個(gè)消息發(fā)送的過(guò)程稠腊,我們?cè)诓煌木€程發(fā)送消息躁染,線程之間的資源是共享的。也就是任何變量在任何線程都可以修改架忌,只要做并發(fā)操作就好了吞彤。插入隊(duì)列就是加鎖的synchronized,Handler中我們使用的是同一個(gè)MessageQueue對(duì)象,同一時(shí)間只能一個(gè)線程對(duì)消息進(jìn)行入隊(duì)操作饰恕。handler在子線程通過(guò)sendMessage將消息存儲(chǔ)到隊(duì)列中后挠羔,主線程的Looper還在一直循環(huán)loop()處理。這樣主線程就能拿到子線程存儲(chǔ)的Message對(duì)象埋嵌,也就完成了線程的切換破加。

  1. handler 是如何實(shí)現(xiàn)延時(shí)發(fā)送消息的?
    答:MessageQueue中enqueueMessage方法主要負(fù)責(zé)將從handler發(fā)送過(guò)來(lái)的message根據(jù)when的大小來(lái)添加到單向鏈表中雹嗦,when的數(shù)據(jù)越大在鏈表中的位置越靠后范舀,delay消息會(huì)一直阻塞線程,直到延遲走完了罪,或者下一個(gè)消息到來(lái)锭环。

至此我們對(duì)handle message整個(gè)流程有了一個(gè)完整的分析,相信以后再使用handler的時(shí)候會(huì)有一個(gè)更清晰的認(rèn)識(shí)泊藕。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末辅辩,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子吱七,更是在濱河造成了極大的恐慌汽久,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,884評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件踊餐,死亡現(xiàn)場(chǎng)離奇詭異景醇,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)吝岭,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,347評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門三痰,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人窜管,你說(shuō)我怎么就攤上這事散劫。” “怎么了幕帆?”我有些...
    開(kāi)封第一講書人閱讀 157,435評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵获搏,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我失乾,道長(zhǎng)常熙,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書人閱讀 56,509評(píng)論 1 284
  • 正文 為了忘掉前任碱茁,我火速辦了婚禮裸卫,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘纽竣。我一直安慰自己墓贿,他們只是感情好茧泪,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,611評(píng)論 6 386
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著聋袋,像睡著了一般队伟。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上舱馅,一...
    開(kāi)封第一講書人閱讀 49,837評(píng)論 1 290
  • 那天缰泡,我揣著相機(jī)與錄音,去河邊找鬼代嗤。 笑死棘钞,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的干毅。 我是一名探鬼主播宜猜,決...
    沈念sama閱讀 38,987評(píng)論 3 408
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼硝逢!你這毒婦竟也來(lái)了姨拥?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書人閱讀 37,730評(píng)論 0 267
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤渠鸽,失蹤者是張志新(化名)和其女友劉穎叫乌,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體徽缚,經(jīng)...
    沈念sama閱讀 44,194評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡憨奸,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,525評(píng)論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了凿试。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片排宰。...
    茶點(diǎn)故事閱讀 38,664評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖那婉,靈堂內(nèi)的尸體忽然破棺而出板甘,到底是詐尸還是另有隱情,我是刑警寧澤详炬,帶...
    沈念sama閱讀 34,334評(píng)論 4 330
  • 正文 年R本政府宣布盐类,位于F島的核電站,受9級(jí)特大地震影響呛谜,放射性物質(zhì)發(fā)生泄漏在跳。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,944評(píng)論 3 313
  • 文/蒙蒙 一呻率、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧呻引,春花似錦礼仗、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 30,764評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)韭脊。三九已至,卻和暖如春单旁,著一層夾襖步出監(jiān)牢的瞬間沪羔,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 31,997評(píng)論 1 266
  • 我被黑心中介騙來(lái)泰國(guó)打工象浑, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留蔫饰,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,389評(píng)論 2 360
  • 正文 我出身青樓愉豺,卻偏偏與公主長(zhǎng)得像篓吁,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子蚪拦,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,554評(píng)論 2 349

推薦閱讀更多精彩內(nèi)容