handler原理

1、消息機制概述

1.消息機制的簡介

(1)Handler是什麼git

handler使Android給咱們提供的用來更新UI的一套機制,也是一套消息處理機制;咱們能夠用它發送處理消息。github

(2)Android爲何設計只能經過handler機制來更新ui?安全

最根本問題使解決多線程併發問題。假設一個activity由多個線程去更新UI,而且都沒有加鎖機制,那麼會形成更新界面錯亂。若是都加鎖則會形成性能降低;數據結構

(3)在子線程中,進行耗時操做,執行完操做後,發送消息,通知主線程更新UI。這即是消息機制的典型應用場景。咱們一般只會接觸到Handler和Message來完成消息機制,其實內部還有兩大助手來共同完成消息傳遞。多線程

 

2.消息機制的模型

消息機制主要包含:MessageQueue,Handler和Looper這三大部分,以及Message,下面咱們一一介紹。架構

Message:須要傳遞的消息,能夠傳遞數據;併發

MessageQueue:消息隊列,可是它的內部實現並非用的隊列,其實是經過一個單鏈表的數據結構來維護消息列表,由於單鏈表在插入和刪除上比較有優點。主要功能向消息池投遞消息(MessageQueue.enqueueMessage)和取走消息池的消息(MessageQueue.next);異步

Handler:消息輔助類,主要功能向消息池發送各類消息事件(Handler.sendMessage)和處理相應消息事件(Handler.handleMessage);async

Looper:不斷循環執行(Looper.loop),從MessageQueue中讀取消息,按分發機制將消息分發給目標處理者。ide

 

3.消息機制的架構

(1)消息機制的運行流程:在子線程執行完耗時操做,當Handler發送消息時,將會調用MessageQueue.enqueueMessage,向消息隊列中添加消息。當經過Looper.loop開啓循環後,會不斷地從線程池中讀取消息,即調用MessageQueue.next,而後調用目標Handler(即發送該消息的Handler)的dispatchMessage方法傳遞消息,而後返回到Handler所在線程,目標Handler收到消息,調用handleMessage方法,接收消息,處理消息。

(2)MessageQueue,Handler和Looper三者之間的關係:每一個線程中只能存在一個Looper,Looper是保存在ThreadLocal中的。主線程(UI線程)已經建立了一個Looper,因此在主線程中不須要再建立Looper,可是在其餘線程中須要建立Looper。每一個線程中能夠有多個Handler,即一個Looper能夠處理來自多個Handler的消息。 Looper中維護一個MessageQueue,來維護消息隊列,消息隊列中的Message能夠來自不一樣的Handler。

 

 

從中咱們能夠看出:
Looper有一個MessageQueue消息隊列;
MessageQueue有一組待處理的Message;
Message中記錄發送和處理消息的Handler;
Handler中有Looper和MessageQueue。

 

2、消息機制的源碼解析

1.Looper

 

UI線程的消息循環是在ActivityThread中的main()方法中建立的,該函數是Android應用程序的入口,代碼以下所示:

public static void main(String[] args) {
        //代碼省略
        Process.setArgV0("<pre-initialized>");

        Looper.prepareMainLooper();//建立Looper

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();//UI線程的Handler
        }
        //代碼省略
        Looper.loop();//執行消息循環

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

其中prepareMainLooper()方法會調用prepare(false)方法。

無參狀況下,默認調用prepare(true);表示的是這個Looper能夠退出,而對於false的狀況則表示當前Looper不能夠退出。。

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

這裏看出,不能重複建立Looper,只能建立一個。建立Looper,並保存在ThreadLocal。其中ThreadLocal是線程本地存儲區(Thread Local Storage,簡稱爲TLS),每一個線程都有本身的私有的本地存儲區域,不一樣線程之間彼此不能訪問對方的TLS區域。
開啓Looper

public static void loop() {
    final Looper me = myLooper();  //獲取TLS存儲的Looper對象 
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    final MessageQueue queue = me.mQueue;  //1.獲取Looper對象中的消息隊列

    Binder.clearCallingIdentity();
    final long ident = Binder.clearCallingIdentity();

    for (;;) { //2.進入loop的主循環方法(即消息循環)
        Message msg = queue.next(); //3.可能會阻塞,由於next()方法可能會無限循環
        if (msg == null) { //消息爲空,則退出循環
            return;
        }

        Printer logging = me.mLogging;  //默認爲null,可經過setMessageLogging()方法來指定輸出,用於debug功能
        if (logging != null) {
            logging.println(">>>>> Dispatching to " + msg.target + " " +
                    msg.callback + ": " + msg.what);
        }
        msg.target.dispatchMessage(msg); //4.獲取msg的目標Handler,而後用於分發Message (處理消息)
        if (logging != null) {
            logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
        }

        final long newIdent = Binder.clearCallingIdentity();
        if (ident != newIdent) {
         
        }
        msg.recycleUnchecked(); 
    }
}

loop()實質上進入循環模式,不斷重複從消息隊列中逐個取出消息,最後處理消息的過程(以下描述),直到消息爲空時退出循環:

循環過程:

  • 讀取MessageQueue的下一條Message(關於next(),後面詳細介紹);
  • 把Message分發給相應的target。

當next()取出下一條消息時,隊列中已經沒有消息時,next()會無限循環,產生阻塞。等待MessageQueue中加入消息,而後從新喚醒。

Looper總結:經過Looper.prepare()來建立Looper對象(消息隊列封裝再Looper對象中),而且保存在sThreadLocal中,而後經過Looper.loop()來執行消息循環,這兩步一般是成對出現的

2.Handler

在子線程完成耗時操做後,若是須要更新ui,最經常使用的方法就是經過HAndler將一個消息post大盤UI線程中,而後再在Handler的handlerMessage方法中進行處理,須要注意的是,該Handler必須在主線程中建立。

 class MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            //更新UI
        }
    }

    MyHandler myHandler = new MyHandler();
    //開啓新線程
new Thread(){
            @Override
            public void run() {
                myHandler.sendEmptyMessage(123);
            }
        }.start();

 

每一個Handler都會關聯一個消息隊列,消息隊列被封裝在Looper中,而每一個Looper會關聯一個線程(Looper經過ThreadLocal封裝),最終就等於每一個消息隊列會關聯一個線程。Handler就是一個消息處理器,將消息投遞給消息隊列,而後再由對應的線程的從消息隊列中諸葛取出消息,而且執行。默認狀況下,消息隊列只有一個,即主線程的消息隊列。那麼Handler如何關聯消息隊列以及線程的呢?

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

public Handler(Callback callback, boolean async) {
   .................................
    //必須先執行Looper.prepare(),才能獲取Looper對象,不然爲null.
    mLooper = Looper.myLooper();  //從當前線程的TLS中獲取Looper對象
    if (mLooper == null) {
        throw new RuntimeException("");
    }
    mQueue = mLooper.mQueue; //消息隊列,來自Looper對象
    mCallback = callback;  //回調方法
    mAsynchronous = async; //設置消息是否爲異步處理方式
}

對於Handler的無參構造方法,經過Looper.myLooper()方法,默認採用當前線程TLS中的Looper對象,而且callback回調方法爲null,且消息爲同步處理方式。只要執行的Looper.prepare()方法,那麼即可以獲取有效的Looper對象。那麼Looper.myLooper()怎麼工做的:

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

//設置UI線程的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
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));
    }

 

從上述代碼能夠看出myLooper()是從sThreadLocal.get()獲取的。而存儲在prepare()方法完成。這樣一來不一樣線程就不能訪問對方的消息隊列。

再回到Handler中來,消息隊列經過Looper與線程關聯上,而Handler又與Looper關聯,所以Handler最終就和線程、線程的消息隊列關聯上了。這就解釋了」爲何要更新UI的Handler必須再主線程中建立?「。就是由於Handler要與主線程的消息隊列關聯上,這樣handlerMessage纔會再UI線程執行,此時更新UI纔是線程安全的。

3.發送消息

(1) Message

先看一下Message的源碼:

public final class Message implements Parcelable{
  public int what;
public int arg1;
public int arg2;
public Object obj;
public Messenger replyTo;
/*package*/ int flags;
/*package*/ long when;
 
/*package*/ Bundle data;
 
/*package*/ Handler target;//target處理
 
/*package*/ Runnable callback;//Runnable類型的callback
 
// sometimes we store linked lists of these things
/*package*/ Message next;//下一條消息,消息隊列是鏈式存儲
 
private static final Object sPoolSync = new Object();
private static Message sPool;
private static int sPoolSize = 0;
 
private static final int MAX_POOL_SIZE = 50;
 
private static boolean gCheckRecycle = true;  
}

 

  1. what:用戶定義消息代碼以便收件人能夠識別這是哪個Message。每一個Handler用它本身的名稱空間爲消息代碼,因此您不須要擔憂你的Handler與其餘handler衝突。
  2. arg一、arg2:若是隻是想向message內放一些整數值,可使用arg1和arg2來代替setData方法。
  3. obj:發送給接收器的任意對象。當使用Message對象在線程間傳遞消息時,若是它包含一個Parcelable的結構類(不是由應用程序實現的類),此字段必須爲非空(non-null)。其餘的數據傳輸則使用setData(Bundle)方法。注意Parcelable對象是從FROYO版本之後纔開始支持的。
  4. replyTo:指明此message發送到何處的可選Messenger對象。具體的使用方法由發送者和接受者決定。

 

ps:new Message和obtain的有什麼區別:https://blog.csdn.net/dfskhgalshgkajghljgh/article/details/52672115

 

發送消息有幾種方式,可是歸根結底都是調用了sendMessageAtTime()方法。

在子線程中經過Handler的post()方式或send()方式發送消息,最終都是調用了sendMessageAtTime()方法。

(2)post方法

public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }
public final boolean postAtTime(Runnable r, long uptimeMillis)
    {
        return sendMessageAtTime(getPostMessage(r), uptimeMillis);
    }
 public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)
    {
        return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
    }
 public final boolean postDelayed(Runnable r, long delayMillis)
    {
        return sendMessageDelayed(getPostMessage(r), delayMillis);
    }

在post(Runnable r)時,會將Runnable包裝成Message對象,而且將Runnable對象設置給Message對象的callback字段,最後將該Message對象插入到消息隊列

(3)send方法

 

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

就連子線程中調用Activity中的runOnUiThread()中更新UI,其實也是發送消息通知主線程更新UI,最終也會調用sendMessageAtTime()方法。

 public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
    }

若是當前的線程不等於UI線程(主線程),就去調用Handler的post()方法,最終會調用sendMessageAtTime()方法。不然就直接調用Runnable對象的run()方法。

下面咱們就來一探究竟,到底sendMessageAtTime()方法有什麼做用?
sendMessageAtTime()

 

 public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
       //其中mQueue是消息隊列,從Looper中獲取的
        MessageQueue queue = mQueue;
        if (queue == null) {
            RuntimeException e = new RuntimeException(
                    this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
            return false;
        }
        //調用enqueueMessage方法
        return enqueueMessage(queue, msg, uptimeMillis);
    }
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        //調用MessageQueue的enqueueMessage方法
        return queue.enqueueMessage(msg, uptimeMillis);
    }

能夠看到sendMessageAtTime()`方法的做用很簡單,就是調用MessageQueue的enqueueMessage()方法,往消息隊列中添加一個消息。
下面來看enqueueMessage()方法的具體執行邏輯。
enqueueMessage()

 

boolean enqueueMessage(Message msg, long when) {
    // 每個Message必須有一個target
    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) {  //正在退出時,回收msg,加入到消息池
            msg.recycle();
            return false;
        }
        msg.markInUse();
        msg.when = when;
        Message p = mMessages;
        boolean needWake;
        if (p == null || when == 0 || when < p.when) {
            //p爲null(表明MessageQueue沒有消息) 或者msg的觸發時間是隊列中最先的, 則進入該該分支
            msg.next = p;
            mMessages = msg;
            needWake = mBlocked; 
        } else {
            //將消息按時間順序插入到MessageQueue。通常地,不須要喚醒事件隊列,除非
            //消息隊頭存在barrier,而且同時Message是隊列中最先的異步消息。
            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;
            prev.next = msg;
        }
        if (needWake) {
            nativeWake(mPtr);
        }
    }
    return true;
}

MessageQueue是按照Message觸發時間的前後順序排列的,隊頭的消息是將要最先觸發的消息。當有消息須要加入消息隊列時,會從隊列頭開始遍歷,直到找到消息應該插入的合適位置,以保證全部消息的時間順序。

4.獲取消息

當發送了消息後,在MessageQueue維護了消息隊列,而後在Looper中經過loop()方法,不斷地獲取消息。上面對loop()方法進行了介紹,其中最重要的是調用了queue.next()方法,經過該方法來提取下一條信息。下面咱們來看一下next()方法的具體流程。
next()

Message next() {
    final long ptr = mPtr;
    if (ptr == 0) { //當消息循環已經退出,則直接返回
        return null;
    }
    int pendingIdleHandlerCount = -1; // 循環迭代的首次爲-1
    int nextPollTimeoutMillis = 0;
    for (;;) {
        if (nextPollTimeoutMillis != 0) {
            Binder.flushPendingCommands();
        }
        //阻塞操做,當等待nextPollTimeoutMillis時長,或者消息隊列被喚醒,都會返回
        nativePollOnce(ptr, nextPollTimeoutMillis);
        synchronized (this) {
            final long now = SystemClock.uptimeMillis();
            Message prevMsg = null;
            Message msg = mMessages;
            if (msg != null && msg.target == null) {
                //當消息Handler爲空時,查詢MessageQueue中的下一條異步消息msg,爲空則退出循環。
                do {
                    prevMsg = msg;
                    msg = msg.next;
                } while (msg != null && !msg.isAsynchronous());
            }
            if (msg != null) {
                if (now < msg.when) {
                    //當異步消息觸發時間大於當前時間,則設置下一次輪詢的超時時長
                    nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                } else {
                    // 獲取一條消息,並返回
                    mBlocked = false;
                    if (prevMsg != null) {
                        prevMsg.next = msg.next;
                    } else {
                        mMessages = msg.next;
                    }
                    msg.next = null;
                    //設置消息的使用狀態,即flags |= FLAG_IN_USE
                    msg.markInUse();
                    return msg;   //成功地獲取MessageQueue中的下一條即將要執行的消息
                }
            } else {
                //沒有消息
                nextPollTimeoutMillis = -1;
            }
         //消息正在退出,返回null
            if (mQuitting) {
                dispose();
                return null;
            }
            ...............................
    }
}

nativePollOnce是阻塞操做,其中nextPollTimeoutMillis表明下一個消息到來前,還須要等待的時長;當nextPollTimeoutMillis = -1時,表示消息隊列中無消息,會一直等待下去。
能夠看出next()方法根據消息的觸發時間,獲取下一條須要執行的消息,隊列中消息爲空時,則會進行阻塞操做。

5.分發消息

在loop()方法中,獲取到下一條消息後,執行msg.target.dispatchMessage(msg),來分發消息到目標Handler對象。
下面就來具體看下dispatchMessage(msg)方法的執行流程。

從源碼中能夠看出,target是Handler類型,實際上就是轉了一圈,經過Handler將消息投遞給消息隊列,消息隊列又傳給Handler來處理,繼續看:

/**
     * 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); } }
private static void handleCallback(Message message) {
        message.callback.run();
    }

分發消息流程:

從上述程序能夠看出,dispatchMessage只是一個分發的方法
當Message的msg.callback不爲空時,則回調方法msg.callback.run();
當Handler的mCallback不爲空時,則回調方法mCallback.handleMessage(msg)
最後調用Handler自身的回調方法handleMessage(),該方法默認爲空,Handler子類經過覆寫該方法來完成具體的邏輯。

threadHandler = new Handler(handlerThread.getLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                //dosomething...
                return true;//1.true則不走handler的handleMessage;false則走
            }
        }) {
            @Override
            public void handleMessage(Message msg) {
                Log.d("handlerThreadActivity", handlerThread.getName() + "");
            }
        };

 

消息分發的優先級:
Message的回調方法:message.callback.run(),優先級最高;
Handler中Callback的回調方法:Handler.mCallback.handleMessage(msg),優先級僅次於1;
Handler的默認方法:Handler.handleMessage(msg),優先級最低。

對於不少狀況下,消息分發後的處理方法是第3種狀況,即Handler.handleMessage(),通常地每每經過覆寫該方法從而實現本身的業務邏輯。

 

3、總結

以上即是消息機制的原理,以及從源碼角度來解析消息機制的運行過程。能夠簡單地用下圖來理解。

相關文章
相關標籤/搜索