Handler機(jī)制

我們經(jīng)常用Handler來(lái)更新UI,但是對(duì)Handler機(jī)制沒(méi)有一個(gè)系統(tǒng)的理解,現(xiàn)在做一個(gè)系統(tǒng)的解析。
我們先看一張圖:



對(duì),我們就是要理解Handler機(jī)制的三大將的關(guān)系,即Handler、Looper、Message

  • Looper
    Looper主要是prepare()和loop()兩個(gè)方法。
    (1)prepare()
    prepare() {
    if (sThreadLocal.get() != null) {
    throw new RuntimeException("Only one Looper may be created per thread");
    }
    sThreadLocal.set(new Looper(true));
    }
    sThreadLocal是一個(gè)ThreadLocal對(duì)象,可以在一個(gè)線程中存儲(chǔ)變量(副本)。從代碼可以看出,Looper.prepare()只能調(diào)用一次,否則報(bào)錯(cuò)。
    (2)loop()
    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; //拿到該looper實(shí)例中的mQueue(消息隊(duì)列)

        // 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  取出消息,如果沒(méi)有,則阻塞
            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  
            Printer logging = me.mLogging;  
            if (logging != null) {  
                logging.println(">>>>> Dispatching to " + msg.target + " " +  
                        msg.callback + ": " + msg.what);  
            }  
    
            msg.target.dispatchMessage(msg);  // 把消息交給msg的target的dispatchMessage方法去處理,Msg的target其實(shí)是handler對(duì)象
    
            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.recycle();  
        }  
    }  
    
    public static Looper myLooper() {
        return sThreadLocal.get();
    }
    

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

  • Handler
    我們看先看一下Handler的其中一個(gè)構(gòu)造函數(shù):
    public Handler(Callback callback, boolean async) {
    if (FIND_POTENTIAL_LEAKS) { // FIND_POTENTIAL_LEAKS 為 false;
    final Class 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(); // 獲取當(dāng)前線程(調(diào)用者)的Looper
        if (mLooper == null) { // 如果當(dāng)前線程沒(méi)有Looper,則拋異常
            throw new RuntimeException( 
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue; // 這里引用的MessageQueue是Looper()中創(chuàng)建的
        mCallback = callback;
        mAsynchronous = async;
    }
    

從這里我們可以看出,Handler通過(guò)Looper.myLooper()獲取到當(dāng)前線程的Looper對(duì)象,再通過(guò)mLooper.mQueue獲取到Looper的消息隊(duì)列,這樣Handler的實(shí)例與我們Looper實(shí)例中MessageQueue關(guān)聯(lián)上了。
我們看看怎么發(fā)消息的??磗endMessage()方法:
public final boolean sendMessage(Message msg) {
return sendMessageDelayed(msg, 0);
}
再看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);
}
再看enqueueMessage()方法:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
sendMessage()最終調(diào)用的是enqueueMessage()方法,我們看一下方法實(shí)體。enqueueMessage中首先為meg.target賦值為this,也就是把當(dāng)前的handler作為msg的target屬性。最終會(huì)調(diào)用queue的enqueueMessage的方法,也就是說(shuō)handler發(fā)出的消息,最終會(huì)保存到消息隊(duì)列中去。
之前已經(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è)方法:
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()方法,其實(shí)是一個(gè)空方法:
/**
* Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}
為什么是一個(gè)空方法呢?因?yàn)橄⒌淖罱K回調(diào)是由我們控制的,我們?cè)趧?chuàng)建handler的時(shí)候都是復(fù)寫(xiě)handleMessage方法,然后根據(jù)msg.what進(jìn)行消息處理。
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case value:
break;
default:
break;
}
};
};
總結(jié)一下
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ì)重寫(xiě)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方法解析

post方法并沒(méi)有新建線程,只是發(fā)送消息:

  public final boolean post(Runnable r)  {  
      return  sendMessageDelayed(getPostMessage(r), 0);  
  }  

  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)存。
sendMessageDelayed()方法和sendMessage()方法差不錯(cuò),原理相似,只是多了個(gè)時(shí)間參數(shù)。

以上是所有Handler機(jī)制的整個(gè)原理解析,我也是跟著大神的博客理解的,嘻嘻?。?/p>

最后編輯于
?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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