Handler消息機(jī)制(個(gè)人學(xué)習(xí)筆記)


涉及到的對(duì)象:
  • Handler
  • Message
  • MessageQueue
  • Looper

Message

一般用法

Message msg = Message.obtain();//存在復(fù)用機(jī)制,性能好,推薦使用
Message msg = new Message();

Message.obtain()方法:

public static Message obtain() {
    synchronized (sPoolSync) {
        if (sPool != null) {
            //這里其實(shí)是通過使用享元模式,來起到對(duì)象復(fù)用的,數(shù)據(jù)結(jié)構(gòu)采用的單鏈表
            Message m = sPool;
            sPool = m.next;
            m.next = null;
            m.flags = 0; // clear in-use flag
            sPoolSize--;
            return m;
        }
    }
    return new Message();
}

Handler

一般用法:

Handler handler = new Handler(){
    public void handleMessage(Message msg) {
        
    }
};

class MyHandler extends Handler{
    public void handleMessage(Message msg) {
        
    }
}

看其構(gòu)造方法:

 public Handler() {
    this(null, false);
 }

 public Handler(Callback callback, boolean async) {
    ...省略無(wú)用代碼
    //得到當(dāng)前線程的looper對(duì)象
    mLooper = Looper.myLooper();
    //如果當(dāng)前線程沒有l(wèi)ooper對(duì)象 則會(huì)報(bào)異常
    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;
}

一般使用sendMessage方法發(fā)送消息,其最終調(diào)用的是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()方法
在Message入隊(duì)操作中,Message對(duì)象持有了當(dāng)前Handler對(duì)象

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    //這個(gè)target現(xiàn)在就是當(dāng)前的Handler
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

Looper

Looper.myLooper()方法:

/**
 * Return the Looper object associated with the current thread.  Returns
 * null if the calling thread is not associated with a Looper.
 */
public static Looper myLooper() {
    //使用TreadLocal對(duì)象來將Looper對(duì)象和創(chuàng)建Handler的線程綁定
    //取得時(shí)候從當(dāng)前線程中獲取。
    return sThreadLocal.get(); 
}

有取出就有放入,看Looper.prepare():

private static void prepare(boolean quitAllowed) {
    if (sThreadLocal.get() != null) {
        //同一個(gè)線程智能創(chuàng)建一個(gè)Looper對(duì)象
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    //創(chuàng)建Looper對(duì)象和當(dāng)前線程綁定,new Looper()時(shí)便會(huì)創(chuàng)建一個(gè)MessageQueue消息隊(duì)列
    sThreadLocal.set(new Looper(quitAllowed));
}

再看下方,有一個(gè)prepareMainLooper(),顧名思義就是創(chuàng)建主線程的Looper(主線程是默認(rèn)就存在一個(gè)Looper對(duì)象,其他線程初始時(shí)是沒有Looper對(duì)象,需要自己建立)

 public static void prepareMainLooper() {
    prepare(false);
    synchronized (Looper.class) {
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already been prepared.");
        }
        sMainLooper = myLooper();
    }
}

為什么主線程默認(rèn)就有一個(gè)Looper對(duì)象呢,這里就要追溯到我們應(yīng)用啟動(dòng)的入口,ActivityThead里的main方法了(這個(gè)類SDK中是沒有的,需要到系統(tǒng)源碼中去找)。

public static final void main(String [] args){
    //...省略無(wú)用代碼
    Looper.prepareMainLooper();
    if(sMainThreadHandler == null){
        sMainTheadHandler = new Handler();
    }
    //開啟死循環(huán)檢測(cè)消息 這句是確保我們的程序一直運(yùn)行,不會(huì)退出
    Looper.loop();//
    //這里多寫一句,當(dāng)我們主線程的Looper被奇奇怪怪的事情給退出了(結(jié)束循環(huán)),那么我們的程序也就退出了。
    if(Process.supportsProcesses){
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }
    //thread是ActivityThread
    thread.detach();
}

這時(shí),主線程中就創(chuàng)建了Looper對(duì)象。

再看Looper.loop()方法:

//在此方法中,循環(huán)檢測(cè)消息
public static final void loop(){
   Looper me = myLooper();
   //此時(shí)可能會(huì)產(chǎn)生阻塞(隊(duì)列里沒消息)
   //產(chǎn)生疑問:假設(shè)這里是主線程,產(chǎn)生阻塞卻不會(huì)觸發(fā)ANR,搜索發(fā)現(xiàn)這和Linux系統(tǒng)里使用管道(pipe)來進(jìn)行進(jìn)程間通信有關(guān)。
   MessageQueue queue = me.mQueue;
   while(true){
       Message msg = queue.next();
       if(msg != null){
            //...省略一些判空檢測(cè)
            //Message對(duì)象里會(huì)持有一個(gè)Handler引用,target就是我們的Handler
            //調(diào)用Handler的dispatchMessage處理消息
            msg.target.dispatchMessage(msg);
            msg.recycle();//回收消息對(duì)象
       }
   }
}
  • 管道通信:Linux中的一種進(jìn)程間通信方式,使用了特殊的文件,有兩個(gè)文件描述符(一個(gè)是讀取,一個(gè)是寫入)
  • 一般應(yīng)用場(chǎng)景:主進(jìn)程拿著讀取描述符等待讀取,沒有內(nèi)容時(shí)就會(huì)阻塞,另一個(gè)進(jìn)程拿著寫入描述符取寫數(shù)據(jù),此時(shí)會(huì)喚醒主進(jìn)程,主進(jìn)程拿著讀取符讀取到內(nèi)容,繼續(xù)執(zhí)行。
  • Handler應(yīng)用場(chǎng)景:Looper調(diào)用loop方法會(huì)產(chǎn)生阻塞,等待消息的到來(此時(shí)會(huì)主線程會(huì)讓出cpu,等待被喚醒)。一旦被喚醒,就會(huì)將消息取出,交給Handler來處理。(也就是說程序啟動(dòng),無(wú)時(shí)無(wú)刻伴隨著睡眠喚醒,只要你有操作,什么觸摸,點(diǎn)擊,滑動(dòng),所以不會(huì)出現(xiàn)卡頓,這也解釋了,當(dāng)你在主線程執(zhí)行耗時(shí)操作,很長(zhǎng)時(shí)間looper都沒有收到消息,也就是沒有被喚醒,便會(huì)出現(xiàn)ANR異常,我是這么理解的)

最后再看Handler的dispatchMessage方法:

/**
 * Handle system messages here.
 */
public void dispatchMessage(Message msg) {
    //如果你給Message對(duì)象設(shè)置了回調(diào) 則優(yōu)先調(diào)用
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        //否則查看Handler對(duì)象里的回調(diào),也就是執(zhí)行handler.post之類的方法
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        //當(dāng)以上都不滿足 則調(diào)用Hanlder類里的抽象方法 也就是我們一般重寫的
        handleMessage(msg);
    }
}

至此Handler消息機(jī)制已經(jīng)到了尾聲,中間略過了消息入隊(duì)的相關(guān)操作,這些操作是在MessageQueue中完成了。有興趣的小伙伴可以去研究下。

下一篇,我們看一看AsyncTask是怎么工作的。

最后編輯于
?著作權(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)容