Android異步消息處理機(jī)制 Handler、Looper、Message

感覺(jué)讓我受益很多的一句話: 好記性不如爛筆頭。

Handler、Looper、Message三者簡(jiǎn)介

Handler簡(jiǎn)介

Handler 為Android操作系統(tǒng)中的線程通信工具,它主要由兩個(gè)作用:

  • (1)、安排消息或Runnable 在某個(gè)主線程中某個(gè)地方執(zhí)行
  • (2)、安排一個(gè)動(dòng)作在另外的線程中執(zhí)行。

Looper簡(jiǎn)介

Looper類用來(lái)為線程開啟一個(gè)消息循環(huán),作用是可以循環(huán)的從消息隊(duì)列讀取消息,所以Looper實(shí)際上就是消息隊(duì)列+消息循環(huán)的封裝。每個(gè)線程只能對(duì)應(yīng)一個(gè)Looper,除主線程外,Android中的線程默認(rèn)是沒(méi)有開啟Looper的。

Message對(duì)象簡(jiǎn)介

Message對(duì)象攜帶數(shù)據(jù),通常它用arg1,arg2來(lái)傳遞消息,當(dāng)然它還可以有obj參數(shù),可以攜帶Bundle數(shù)據(jù)。它的特點(diǎn)是系統(tǒng)性能消耗非常少。

總體簡(jiǎn)介:

Handler 、 Looper 、Message 這三者都與Android異步消息處理線程相關(guān)的概念。那么什么叫異步消息處理線程呢?

異步消息處理線程啟動(dòng)后會(huì)進(jìn)入一個(gè)無(wú)限的循環(huán)體之中,每循環(huán)一次,從其內(nèi)部的消息隊(duì)列中取出一個(gè)消息,然后回調(diào)相應(yīng)的消息處理函數(shù),執(zhí)行完成一個(gè)消息后則繼續(xù)循環(huán)。若消息隊(duì)列為空,線程則會(huì)阻塞等待。

其實(shí)Looper負(fù)責(zé)的就是創(chuàng)建一個(gè)MessageQueue,然后進(jìn)入一個(gè)無(wú)限循環(huán)體不斷從該MessageQueue中讀取消息,而消息的創(chuàng)建者就是一個(gè)或多個(gè)Handler 。

下面則由我們一起進(jìn)入源碼,進(jìn)行簡(jiǎn)單的了解一下:

刨根問(wèn)底,深入源碼簡(jiǎn)單探究

1、Looper源碼查看

對(duì)于Looper主要是prepare()和loop()兩個(gè)方法。

(1)首先prepare()方法

 /** Initialize the current thread as a looper.
      * This gives you a chance to create handlers that then reference
      * this looper, before actually starting the loop. Be sure to call
      * {@link #loop()} after calling this method, and end it by calling
      * {@link #quit()}.
      */
    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));
    }

sThreadLocal是一個(gè)ThreadLocal對(duì)象,可以在一個(gè)線程中存儲(chǔ)變量??梢钥吹剑诘?2行,將一個(gè)Looper的實(shí)例放入了ThreadLocal,并且在放入之前行判斷了sThreadLocal是否為null,否則拋出異常。這也就說(shuō)明了Looper.prepare()方法不能被調(diào)用兩次,同時(shí)也保證了一個(gè)線程中只有一個(gè)Looper實(shí)例。

Looper的構(gòu)造方法

private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);

        mThread = Thread.currentThread();
    }

在構(gòu)造方法中,創(chuàng)建了一個(gè)MessageQueue(消息隊(duì)列)。MessageQueue變量已聲明為:final MessageQueue mQueue;

(2)然后看loop()方法:


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

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

     /**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
      public static @Nullable Looper myLooper() {
          return sThreadLocal.get();
   }

myLooper()方法直接返回了sThreadLocal存儲(chǔ)的Looper實(shí)例,如果me為null則拋出異常,也就是說(shuō)looper方法必須在prepare方法之后運(yùn)行。

第8行:拿到該looper實(shí)例中的mQueue(消息隊(duì)列)

for (;;){}方法:就進(jìn)入了我們所說(shuō)的無(wú)限循環(huán)。

Message msg = queue.next();取出一條消息,如果沒(méi)有消息則阻塞。

取出消息之后:使用調(diào)用msg.target.dispatchMessage(msg);把消息交給msg的target的dispatchMessage方法去處理。Msg的target是什么呢?其實(shí)就是handler對(duì)象。

msg.recycleUnchecked();釋放消息占據(jù)的資源。

Looper主要作用:

  • 1、 與當(dāng)前線程綁定,保證一個(gè)線程只會(huì)有一個(gè)Looper實(shí)例,同時(shí)一個(gè)Looper實(shí)例也只有一個(gè)MessageQueue。
  • 2、 loop()方法,不斷從MessageQueue中去取消息,交給消息的target屬性的dispatchMessage去處理。

下面----->>>>Handler登場(chǎng)了。

2、Handler源碼賞析

使用Handler之前,我們都是初始化一個(gè)實(shí)例,比如用于更新UI線程,我們會(huì)在聲明的時(shí)候直接初始化,或者在onCreate中初始化Handler實(shí)例。所以我們首先看Handler的構(gòu)造方法,看其如何與MessageQueue聯(lián)系上的,它在子線程中發(fā)送的消息(一般發(fā)送消息都在非UI線程)怎么發(fā)送到MessageQueue中的。


     /**
     * Use the {@link Looper} for the current thread with the specified callback interface
     * and set whether the handler should be asynchronous.
     *
     * Handlers are synchronous by default unless this constructor is used to make
     * one that is strictly asynchronous.
     *
     * Asynchronous messages represent interrupts or events that do not require global ordering
     * with respect to synchronous messages.  Asynchronous messages are not subject to
     * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
     *
     * @param callback The callback interface in which to handle messages, or null.
     * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
     * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
     *
     * @hide
     */
    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;
    }

通過(guò)Looper.myLooper()獲取了當(dāng)前線程保存的Looper實(shí)例,

然后在mQueue = mLooper.mQueue;又獲取了這個(gè)Looper實(shí)例中保存的MessageQueue(消息隊(duì)列),這樣就保證了handler的實(shí)例與我們Looper實(shí)例中MessageQueue關(guān)聯(lián)上了。

然后看我們最常用的sendMessage方法:

    /*此段將注釋去掉,太多,看方法名我們也能大致的了解*/

    public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }

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

   
    public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageAtTime(msg, uptimeMillis);
    }

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

最后的最后都去調(diào)用了sendMessageAtTime,在此方法內(nèi)部有直接獲取該Handler的中的Looper的MessageQueue然后調(diào)用了enqueueMessage方法,方法如下:

    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

首先為msg.target賦值為this,也就是把當(dāng)前的handler作為msg的target屬性。最終會(huì)調(diào)用queue的enqueueMessage的方法,也就是說(shuō)handler發(fā)出的消息,最終會(huì)保存到消息隊(duì)列中去。

現(xiàn)在已經(jīng)很清楚了Looper會(huì)調(diào)用prepare()和loop()方法,在當(dāng)前執(zhí)行的線程中保存一個(gè)Looper實(shí)例,

這個(gè)實(shí)例會(huì)保存一個(gè)MessageQueue對(duì)象,然后當(dāng)前線程進(jìn)入一個(gè)無(wú)限循環(huán)中去,不斷從MessageQueue中讀取Handler發(fā)來(lái)的消息。

然后再回調(diào)創(chuàng)建這個(gè)消息的handler中的dispathMessage方法,下面我們趕快去看一看這個(gè)方法:

    /**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

調(diào)用了handleMessage方法,下面我們?nèi)タ催@個(gè)方法:

 
    /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
    }

這個(gè)方法是不是很熟悉?。?/strong>

上段熟悉的代碼塊:

    Handler mHandler=new Handler(){
     @Override
      public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what){
            case 1:
            Log.e("看源碼長(zhǎng)知識(shí)","前面標(biāo)識(shí)老大哥說(shuō)得對(duì)!");
                break;
            default:
            Log.e("看源碼長(zhǎng)知識(shí)","我就什么也不做");
                break;
              }
         }
    };

創(chuàng)建Handler要重寫的那個(gè)方法,自己處理事件和更新UI的那個(gè)方法?;腥淮笪颍。?!

讓我們首先總結(jié)一下這個(gè)流程

  • 1、首先Looper.prepare()在本線程中保存一個(gè)Looper實(shí)例,然后該實(shí)例中保存一個(gè)MessageQueue對(duì)象;因?yàn)長(zhǎng)ooper.prepare()在一個(gè)線程中只能調(diào)用一次,所以MessageQueue在一個(gè)線程中只會(huì)存在一個(gè)。
  • 2、Looper.loop()會(huì)讓當(dāng)前線程進(jìn)入一個(gè)無(wú)限循環(huán),不端從MessageQueue的實(shí)例中讀取消息,然后回調(diào)msg.target.dispatchMessage(msg)方法。
  • 3、Handler的構(gòu)造方法,會(huì)首先得到當(dāng)前線程中保存的Looper實(shí)例,進(jìn)而與Looper實(shí)例中的MessageQueue關(guān)聯(lián)。
  • 4、Handler的sendMessage方法,會(huì)給msg的target賦值為handler自身,然后加入MessageQueue中。
  • 5、在構(gòu)造Handler實(shí)例時(shí),我們會(huì)重寫handleMessage方法,也就是msg.target.dispatchMessage(msg)最終調(diào)用的方法。
  • 總結(jié)完成,大家可能還會(huì)問(wèn),那么在Activity中,我們并沒(méi)有顯示的調(diào)用Looper.prepare()和Looper.loop()方法,為啥Handler可以成功創(chuàng)建呢,這是因?yàn)樵贏ctivity的啟動(dòng)代碼中,已經(jīng)在當(dāng)前UI線程調(diào)用了Looper.prepare()和Looper.loop()方法。

增添Handler post方法解析

Handler的post方法創(chuàng)建的線程和UI線程有什么關(guān)系?

有時(shí)候?yàn)榱朔奖?,我們?huì)直接寫如下代碼:

mHandler.post(new Runnable()  
        {  
            @Override  
            public void run()  
            {  
                Log.e("TAG", Thread.currentThread().getName());  
                mTxt.setText("yoxi");  
            }  
        });  

然后run方法中可以寫更新UI的代碼,其實(shí)這個(gè)Runnable并沒(méi)有創(chuàng)建什么線程,而是發(fā)送了一條消息,下面看源碼:

    /**
     * Causes the Runnable r to be added to the message queue.
     * The runnable will be run on the thread to which this handler is 
     * attached. 
     *  
     * @param r The Runnable that will be executed.
     * 
     * @return Returns true if the Runnable was successfully placed in to the 
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.
     */
    public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }

getPostMessage(r)源碼

   private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }

可以看到,在getPostMessage中,得到了一個(gè)Message對(duì)象,然后將我們創(chuàng)建的Runable對(duì)象作為callback屬性,賦值給了此message.

注:產(chǎn)生一個(gè)Message對(duì)象,可以new ,也可以使用Message.obtain()方法;

兩者都可以,但是更建議使用obtain方法,因?yàn)镸essage內(nèi)部維護(hù)了一個(gè)Message池用于Message的復(fù)用,避免使用new 重新分配內(nèi)存。

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

最終和handler.sendMessage一樣,調(diào)用了sendMessageAtTime,然后調(diào)用了enqueueMessage方法,給msg.target賦值為handler,最終加入MessagQueue.

可以看到,這里msg的callback和target都有值,那么會(huì)執(zhí)行哪個(gè)呢?

其實(shí)上面已經(jīng)貼過(guò)代碼,就是dispatchMessage方法:

 
    /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
    }
    
    /**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

如果msg.callback不為null,則執(zhí)行callback回調(diào),也就是我們的Runnable對(duì)象。

好了,關(guān)于Looper , Handler , Message 這三者關(guān)系上面已經(jīng)敘述的非常清楚了。

洋神的圖

后話,小小的提醒

其實(shí)Handler不僅可以更新UI,你完全可以在一個(gè)子線程中去創(chuàng)建一個(gè)Handler,然后使用這個(gè)handler實(shí)例在任何其他線程中發(fā)送消息,最終處理消息的代碼都會(huì)在你創(chuàng)建Handler實(shí)例的線程中運(yùn)行。

    new Thread()  
        {  
            private Handler handler;  
            public void run()  
            {  
  
                Looper.prepare();  //這句話必須要加
                  
                handler = new Handler()  
                {  
                    public void handleMessage(android.os.Message msg)  
                    {  
                        Log.e("三生三世十里桃花",Thread.currentThread().getName());  
                    };  
                };

Android不僅給我們提供了異步消息處理機(jī)制讓我們更好的完成UI的更新,其實(shí)也為我們提供了異步消息處理機(jī)制代碼的參考,不僅能夠知道原理,最好還可以將此設(shè)計(jì)用到其他的非Android項(xiàng)目中去.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容