Handler源碼分析

Handler是Android中消息傳遞機制,可以將工作線程所創(chuàng)建的消息傳遞到主線程中去處理懦傍,進行UI更新或者其他需要在主線程進行處理的工作÷樱總的來說粗俱,就是線程之間的通訊。

Handler原理解析

了解Handler原理之前虚吟,我們需要先了解幾個相關(guān)的類

  • Hander (主要作用發(fā)送和處理消息和Runnable)
  • Message (線程間消息傳遞的載體)
  • MessageQueue(消息隊列寸认,存放消息)
  • Looper (循環(huán)讀取消息隊列,發(fā)送到指定Handler處理)

Handler的基本使用

//在主線程創(chuàng)建一個Handler對象
//并重載handleMessage方法
Handler mHandler = new Handler(){
    @Override
    public void handleMessage(Message){
        //需要在mHandler的線程處理的業(yè)務(wù)邏輯
        //可以根據(jù)Message的參數(shù)處理相應(yīng)業(yè)務(wù)串慰,例如UI更新
        textView.setText("通過sendMessage更新UI")
    }
}

//然后在子線程中發(fā)送消息
//通過sendMessage方法發(fā)送
new Thread(new Runnable(){
    @Override
    public void run(){
        //主線的Handler
        Message message = new Message();
        message.what = 1;
        message.obj = "可以傳遞對象偏塞,這里是傳遞字符串對象";
        //通過sendMessage發(fā)送消息對象
        mHandler.sendMessage(message)
    }
}).start();

//或者可以傳遞一個Runnable對象
new Thread(new Runnable(){
    @Override
    public void run(){
        mHandler.post(new Runnable(){
            @Override
            public void run(){
                //需要在mHandler的線程處理的業(yè)務(wù)邏輯
                //如更新UI
                textView.setText("通過post更新UI")
            }
        })
    }
})

除了上面2種方法,Handler發(fā)送消息很多種

//發(fā)送Runnable
post(Runnable)
postAtTime(Runnable,long)
postAtTime(Runnable,Object,long)
postDelayed(Runnable,long)
postDelayed(Runnable,Object,long)
//發(fā)送Message
sendMessage(Message)
sendMessageDelayed(Message,long)
sendMessageAtTime(Message,long)
sendMessageAtFrontOfQueue(Message)
sendEmptyMessage(int)
sendEmptyMessageDelayed(int,long)
sendEmptyMessageAtTime(int,long)

//我們先分析比較簡單的sendMessage和post
public final boolean sendMessage(Message msg){
    return sendMessageDelayed(msg, 0);
}
//調(diào)用成員方法sendMessageDelayed邦鲫,延時為0
public final boolean sendMessageDelayed(Message msg, long delayMillis){
    if (delayMillis < 0) {
        delayMillis = 0;
    }
    //所以插入消息隊列的時候就是(當前時間+0)
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
//uptimeMellis就是消息傳遞到Handler的時間
public boolean sendMessageAtTime(Message msg, long uptimeMillis){
    MessageQueue queue = mQueue;
    //省略部分代碼...
    //最終通過enqueueMessage把消息插入到消息隊列
    return enqueueMessage(queue, msg, uptimeMillis);
}

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    //把當前Handler對象引用保存在Message.target灸叼,后續(xù)通過這個target來傳遞到指定Handler去處理消息
    msg.target = this;
    //設(shè)置Message是否異步Message
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    //插入到消息隊列
    return queue.enqueueMessage(msg, uptimeMillis);
}

//MessageQueue.java#enqueueMessage
boolean enqueueMessage(Message msg, long when) {
    //省略部分代碼...
    synchronized (this) {
        //省略部分代碼...
        msg.markInUse();//標記Message為使用中
        msg.when = when;//執(zhí)行時間
        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;
            //遍歷消息隊列神汹,尋找插入Message的位置
            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;
}
//sendMessage基本流程就如上所示
//sendMessage -> sendMessageDelayed -> sendMessageAtTime -> enqueueMessage

//接著看post流程
public final boolean post(Runnable r){
   return  sendMessageDelayed(getPostMessage(r), 0);
}
//調(diào)用getPostMessage把Runnable封裝為Message
private static Message getPostMessage(Runnable r) {
    Message m = Message.obtain();
    m.callback = r;
    return m;
}
//最后流程還是sendMessage流程一致

通過上面的代碼,了解了Handler如何發(fā)送消息的方法古今,那么線程之間消息是如何傳遞的呢屁魏?

為什么在其他線程通過Hander發(fā)送消息后,會到Handler線程進行處理捉腥?
首先先看創(chuàng)建Hander實例時候處理

Handler mHandler = new Handler()//創(chuàng)建了Handler實例

//Handler.java
public Handler() {
    this(null, false);
}
    
public Handler(Callback callback, boolean async) {
    ...
    mLooper = Looper.myLooper();
    if (mLooper == null) {
        throw new RuntimeException("Can't create handler inside thread "
        + Thread.currentThread()
        + " that has not called Looper.prepare()");
    }
    mQueue = mLooper.mQueue;
    ...
}
//Handler構(gòu)造方法主要工作:
//獲取Looper對象
//從Looper對象獲取mQueue(消息隊列)

Looper對象獲取

//Looper.java

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
public static @Nullable Looper myLooper() {
    //通過ThreadLocal.get獲取Looper對象
    return sThreadLocal.get();
}

ThreadLoal變量氓拼,線程局部變量,簡單理解為線程私有變量抵碟,這里就不展開描述桃漾;

myLooper方法中通過sThreadLocal.get()獲取Looper,那Looper是在什么時候set進去的拟逮?通過sThreadLocal.set關(guān)鍵字搜索呈队,在Looper的prepare方法內(nèi)找到

//一般線程初始化Looper
public static void prepare() {
    prepare(true);
}

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

//真正初始化Looper方法
private static void prepare(boolean quitAllowed) {
    if (sThreadLocal.get() != null) {
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    //創(chuàng)建Looper對象,并將set到ThreadLocal
    sThreadLocal.set(new Looper(quitAllowed));
}

//Looper構(gòu)造方法
private Looper(boolean quitAllowed) {
    //創(chuàng)建MessageQueue
    mQueue = new MessageQueue(quitAllowed);
    //記錄線程ID
    mThread = Thread.currentThread();
}

所以要創(chuàng)建Handler對象唱歧,必定要先調(diào)用Looper對象的prepare或者prepareMainLooper方法,否則在Handler構(gòu)造方法就會跑出異常粒竖,因為Looper.myLooper返回的對象為null

public Handler(Callback callback, boolean async) {
    ···
    mLooper = Looper.myLooper();
    if (mLooper == null) {
        //獲取到Looper對象為空颅崩,拋出異常
        //報錯說明未調(diào)用Looper.prepare()
        throw new RuntimeException(
            "Can't create handler inside thread " + Thread.currentThread()
                    + " that has not called Looper.prepare()");
    }
    mQueue = mLooper.mQueue;
    ···
}

那Looper.prepare方法在什么時候調(diào)用?了解過Android源碼的可能知道蕊苗,在ActivityThread的main方法中沿后,調(diào)用了Looper.prepareMainLooper,而且當前線程也就是我們所說的主線程

ActivityThread.java

public static void main(String[] args) {
    ···
    //初始化Looper對象
    Looper.prepareMainLooper();
    ···
    //開始循環(huán)讀取消息
    Looper.loop();
    ···
}

既然我們要循環(huán)從消息隊列獲取消息進行發(fā)送朽砰,那就可能到開啟循環(huán)尖滚,Looper.loop方法的作用就是循環(huán)從消息隊列讀取消息并且發(fā)送。通過源碼看看Looper.loop方法是如何循環(huán)讀取消息

Looper.java
public static void loop() {
    //獲取當前線程的Looper對象
    final Looper me = myLooper();
    ···
    //獲取Looper的消息隊列
    final MessageQueue queue = me.mQueue;
    ···
    //開始循環(huán)獲取消息
    for (;;) {
        //獲取消息隊列瞧柔,可能會阻塞
        Message msg = queue.next(); // might block
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            return;
        }
        ···
        try {
            //分發(fā)到指定Handler去處理消息
            //msg.target就是前面sendMessage中設(shè)置的Handler引用
            msg.target.dispatchMessage(msg);
            ···
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        ···
        //回收Message對象
        msg.recycleUnchecked();
    }
}

知道了Message如何分發(fā)到指定Handler漆弄,跟蹤dispatchMessage看看最后如何傳遞到Hander的handleMessage方法

//Handler.java#dispatchMessage
public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        //判斷Runnable對象存在
        handleCallback(msg);
    } else {
        //可以在構(gòu)造方法傳入Callback,作用和handlerMessage一樣
        //一般都直接重寫handleMessage方法
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        //最終調(diào)用handlerMessage造锅,把消息傳遞到我們實例話的Handler對象撼唾,一般我們都會重寫handleMessage方法
        handleMessage(msg);
    }
}

總結(jié)

Handler消息傳遞機制使用之前,需要先初始化Looper綁定當前線程哥蔚,再循環(huán)從消息隊列獲取消息分發(fā)到指定的Handler去處理倒谷,以上只分析了Handerl機制的一般用法,還有其他如異步消息糙箍,IdleHandlder的用法還未涉及渤愁,后續(xù)逐步進行分析

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末豺谈,一起剝皮案震驚了整個濱河市梅肤,隨后出現(xiàn)的幾起案子掏颊,更是在濱河造成了極大的恐慌,老刑警劉巖柜砾,帶你破解...
    沈念sama閱讀 218,525評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異毒费,居然都是意外死亡界弧,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評論 3 395
  • 文/潘曉璐 我一進店門办桨,熙熙樓的掌柜王于貴愁眉苦臉地迎上來筹淫,“玉大人,你說我怎么就攤上這事呢撞∷鸾” “怎么了?”我有些...
    開封第一講書人閱讀 164,862評論 0 354
  • 文/不壞的土叔 我叫張陵殊霞,是天一觀的道長摧阅。 經(jīng)常有香客問我,道長绷蹲,這世上最難降的妖魔是什么棒卷? 我笑而不...
    開封第一講書人閱讀 58,728評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮祝钢,結(jié)果婚禮上比规,老公的妹妹穿的比我還像新娘。我一直安慰自己拦英,他們只是感情好蜒什,可當我...
    茶點故事閱讀 67,743評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著疤估,像睡著了一般灾常。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上铃拇,一...
    開封第一講書人閱讀 51,590評論 1 305
  • 那天钞瀑,我揣著相機與錄音,去河邊找鬼锚贱。 笑死仔戈,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的拧廊。 我是一名探鬼主播监徘,決...
    沈念sama閱讀 40,330評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼吧碾!你這毒婦竟也來了凰盔?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,244評論 0 276
  • 序言:老撾萬榮一對情侶失蹤倦春,失蹤者是張志新(化名)和其女友劉穎户敬,沒想到半個月后落剪,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,693評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡尿庐,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,885評論 3 336
  • 正文 我和宋清朗相戀三年忠怖,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片抄瑟。...
    茶點故事閱讀 40,001評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡凡泣,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出皮假,到底是詐尸還是另有隱情鞋拟,我是刑警寧澤,帶...
    沈念sama閱讀 35,723評論 5 346
  • 正文 年R本政府宣布惹资,位于F島的核電站贺纲,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏褪测。R本人自食惡果不足惜猴誊,卻給世界環(huán)境...
    茶點故事閱讀 41,343評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望侮措。 院中可真熱鬧稠肘,春花似錦、人聲如沸萝毛。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽笆包。三九已至,卻和暖如春略荡,著一層夾襖步出監(jiān)牢的瞬間庵佣,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評論 1 270
  • 我被黑心中介騙來泰國打工汛兜, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留巴粪,地道東北人。 一個月前我還...
    沈念sama閱讀 48,191評論 3 370
  • 正文 我出身青樓粥谬,卻偏偏與公主長得像肛根,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子漏策,可洞房花燭夜當晚...
    茶點故事閱讀 44,955評論 2 355

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