一、概述:html
你們都知道,在Android中,UI線程是不安全的,更新UI在UI線程中處理,其餘耗時工做都不能在該線程執行,相信你們在面試的時候也知道Handler是面試官很是喜歡問的一個問題。一樣我面試的也如此,每次面試前去複習不如寫一遍博客記錄下來更深入。面試
二、Handler的簡單使用:shell
private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); } };
上面這樣使用可能會引發內存泄露的風險,由於當使用內部類(匿名內部類)來建立Handler的時候,Handler隱式持有一個外部類對象(Activity)的引用,而Handler常伴有一個耗時的後臺線程操做,當在後臺線程訪問過程當中,Activity再也不使用了,那麼它就在特定狀況下會被GC回收,但因爲這時線程還沒有執行完,而該線程持有Handler的引用(否則它怎麼發消息給Handler?),這個Handler又持有Activity的引用,就致使該Activity沒法被回收(即內存泄露),直到網絡請求結束(例如圖片下載完畢)。(摘自:http://www.javashuo.com/article/p-snyrlirg-hg.html)。今天這篇不是寫該內容的解決方式,具體的解決方案就看這篇文章吧。安全
三、Looper消息循環:網絡
Handler的發送的消息發送到哪裏,由誰來承載,由誰來發出呢。異步
Handler發送的消息都發送到MessageQueue,而MessageQueue由Looper建立,進入一個無限循環不斷從該MessageQueue讀取消息並回調處理。
async
根據上面的描述,咱們先來看看Looper的源碼,對於Looper主要有prepare()和loop()兩個方法;ide
咱們常常會在當前線程調用Looper.prepare()和Looper.loop(),首先來看看prepare()方法:函數
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的有參構造函數,sThreadLocal是一個ThreadLocal對象,能夠在一個線程中存儲變量,咱們能夠看到sThreadLocal.set(new Looper(quitAllowed))函數往該對象中存儲了一個Looper對象,並在前面判斷該get()方法是否爲空,不爲空則拋出異常,該異常相信你們都見到過,在同一個線程內調用屢次prepare()方法,這就說明了Looper.prepare()方法不能被調用兩次,同時也保證了一個線程中僅有一個Looper對象。oop
下面咱們看Looper的構造方法:
private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
構造方法建立了一個MessageQueue(消息隊列),同時變量mThread指向當前線程;
好的,上面咱們看完了Looper.prepare()的源碼,咱們再來看看Looper.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(); // Allow overriding a threshold with a system prop. e.g. // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start' final int thresholdOverride = SystemProperties.getInt("log.looper." + Process.myUid() + "." + Thread.currentThread().getName() + ".slow", 0); boolean slowDeliveryDetected = false; 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; long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs; long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs; if (thresholdOverride > 0) { slowDispatchThresholdMs = thresholdOverride; slowDeliveryThresholdMs = thresholdOverride; } final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0); final boolean logSlowDispatch = (slowDispatchThresholdMs > 0); final boolean needStartTime = logSlowDelivery || logSlowDispatch; final boolean needEndTime = logSlowDispatch; if (traceTag != 0 && Trace.isTagEnabled(traceTag)) { Trace.traceBegin(traceTag, msg.target.getTraceName(msg)); } final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0; final long dispatchEnd; try { msg.target.dispatchMessage(msg); dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0; } finally { if (traceTag != 0) { Trace.traceEnd(traceTag); } } if (logSlowDelivery) { if (slowDeliveryDetected) { if ((dispatchStart - msg.when) <= 10) { Slog.w(TAG, "Drained"); slowDeliveryDetected = false; } } else { if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery", msg)) { // Once we write a slow delivery log, suppress until the queue drains. slowDeliveryDetected = true; } } } if (logSlowDispatch) { showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg); } 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(); } }
看源碼,咱們能夠看到Looper對象是經過myLooper()方法獲取的,該方法也就是上面prepare()方法中說過的sThreadLocal對象調用get()方法獲取到存入進去的Looper對象。繞不繞口繞不繞口我就問你,我都差點沒明白,看下面,就是如此簡單。
public static @Nullable Looper myLooper() { return sThreadLocal.get(); }
一、MessageQueue queue = me.mQueue獲取到該消息隊列;
二、在循環體for(;;)中進入咱們前面所說的無限循環;
三、Message msg = queue.next()獲取消息,沒有消息則返回;
四、msg.target.dispatchMessage(msg)把消息給msg.target處理,msg.tartget其實就是發送該msg的Handler對象,解析到Handler的時候就會看到;
總結:Looper兩個靜態方法,一個是prepare(),一個是loop(),prepare()方法主要是綁定當前線程,建立一個Looper對象,且當前線程惟一,同時也建立了一個MessageQueue(消息隊列);loop()方法主要是
循環消息隊列中的Message,並交給msg的target屬性處理。
四、Handler解析:
一般咱們使用Handler的時候都會new一個Handler對象,咱們來看看Handler的構造函數;
public Handler() { this(null, false); } 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 " + Thread.currentThread() + " that has not called Looper.prepare()"); } mQueue = mLooper.mQueue; mCallback = callback; mAsynchronous = async; }
一樣,調用的依然是有參構造函數,在if(mLooper == null)裏拋出的異常就是咱們常常能遇到的,如今看本質這個異常其實就是當前線程Looper對象爲null,咱們一般解決就是在該線程中調用Looper.prepare()
和Looper.loop()方法;mQueue = mLooper.mQueue獲取到Looper對象中的消息隊列,那麼咱們的Handler就跟MessageQueue消息隊列關聯上了。
OK,Handler咱們知道是如何構造的了,咱們看看咱們經常使用的sendMessage(Message msg)方法是如何工做的,ctrl+左鍵進去看看源碼:
public final boolean sendMessage(Message msg) { return sendMessageDelayed(msg, 0); }
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); }
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }
很明顯,是調用的這些方法。sendMessageAtTime(Message msg, long uptimeMillis)方法判斷了MessageQueue(消息隊列)對象是否null;重點來了,enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis)
中的msg.target = this,剛剛咱們提到的,將msg給msg.target屬性處理,咱們這裏能看到,msg.target指向了this,也就是咱們的Handler,因此前面說的,msg.target屬性其實就是當前消息的Handler對象,那麼前面的流程就是looper
循環處理MessageQueue(消息隊列),獲取到消息就給發送該消息的Handler對象的dispatchMessage()方法處理;
so,咱們來看看dispatchMessage()方法是如何處理的:
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,不爲null,則執行該回調,不然執行handleMessage(msg)方法,咱們使用sendMessage()方法的時候,是沒有給到callback的,那麼咱們就是調用handleMessage()方法,看看該方法實現了什麼:
/** * Subclasses must implement this to receive messages. */ public void handleMessage(Message msg) { }
handleMessage(Message msg)是一個空方法,沒錯,該方法是由咱們本身實現的,上面咱們建立的Handler對象實現了handlerMessage(Message msg)方法,就是調用的咱們本身實現的這個方法。
何時會調用handleCallback(Message msg)方法呢,其實handler.post(new Runnable{})就是回調的咱們這個方法,看看 post(Runnable run) 方法的源碼吧:
public final boolean post(Runnable r) { return sendMessageDelayed(getPostMessage(r), 0); } public final boolean sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); }
咱們能夠看到,post方法其實仍是調用了咱們前面所看到的sendMessageDelayed()方法,不一樣的是,咱們處理了一下傳進來的Runnable對象,咱們看看getPostMessage(r)方法:
private static Message getPostMessage(Runnable r) { Message m = Message.obtain(); m.callback = r; return m; }
這裏咱們建立了一個Message對象,該對象的callback屬性指向咱們傳進來的Runnable對象,so,前面咱們看到的判空部分,handleCallback(Message msg) 那麼就會執行,
private static void handleCallback(Message message) { message.callback.run(); }
因此,Runnable其實不是一個新的線程在工做,只是做爲一個回調實現;
總結:
整個異步消息處理流程其實並不複雜,明白他們之間的關係就很容易理解,我來畫個圖更好的理解下這整個流程:
Ok,大概就是這樣理解的,網上大佬們的解析也不少,借鑑了不少大佬的語言描述,感激涕零。這裏只是簡單記錄我對知識的理解,若有錯誤請指出。