Android Handler消息派發(fā)機(jī)制源碼分析
注:這里只是說一下sendmessage的一個過程,post就類似的
如果我們需要發(fā)送消息,會調(diào)用sendMessage方法
public final boolean sendMessage(Message msg) { return sendMessageDelayed(msg, 0); }
這個方法會調(diào)用如下的這個方法
public final boolean sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); }
接下來設(shè)定延遲時間,然后繼續(xù)調(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); }
這里獲得了消息隊(duì)列,檢查隊(duì)列是否存在,然后返回enqueMessage的方法的執(zhí)行結(jié)果,這個結(jié)果是說明消息能否進(jìn)入隊(duì)列的一個布爾值
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }
這里是對消息進(jìn)行入隊(duì)處理,下面就是在MessageQueue中對消息進(jìn)行入隊(duì)
boolean enqueueMessage(Message msg, long when) { 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) { IllegalStateException e = new IllegalStateException( msg.target + " sending message to a Handler on a dead thread"); Log.w(TAG, e.getMessage(), e); msg.recycle(); return false; } msg.markInUse(); msg.when = when; 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; 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; }
就是對傳遞過來的消息進(jìn)行一些封裝然后放到隊(duì)列中,至此我們的sendMessage處理完畢,返回的結(jié)果是進(jìn)隊(duì)是否成功的布爾值,那么究竟消息之后是如何被處理的呢?
我們可以看到在Handler構(gòu)造的時候記錄了一個Looper對象,也記錄了一個回掉函數(shù)
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 that has not called Looper.prepare()"); } mQueue = mLooper.mQueue; mCallback = callback; mAsynchronous = async; }
這里的myLooper方法返回的是當(dāng)前線程關(guān)聯(lián)的一個Looper對象
public static @Nullable Looper myLooper() { return sThreadLocal.get(); }
當(dāng)Looper實(shí)例化了以后會執(zhí)行自己的prepare方法然后執(zhí)行l(wèi)oop方法,loop方法就是不斷的讀取消息隊(duì)列中的消息然后執(zhí)行相應(yīng)的操作的方法,因?yàn)槭窃谄渌€程中執(zhí)行的循環(huán)所以不會影響其他線程
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(); 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 Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } msg.target.dispatchMessage(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(); } }
在循環(huán)中如果讀取到了消息,就會執(zhí)行dispatchMessage方法,然后分派完消息之后再執(zhí)行一次recycleUnchecked方法來重用這個Message,我們看到dispatchMessage方法
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
這里看到直接執(zhí)行了一個handlerMessage方法,這個方法是一個回調(diào)方法,我們是必須實(shí)現(xiàn)的,否則Handler什么都不會做,為什么呢?還記得剛剛說構(gòu)造Handler的時候我們記錄了一個CallBack的回掉嗎?Handler中的這個handlerMessage方法是一個空方法,如果我們重寫了這個方法,在回調(diào)的時候就會執(zhí)行我們先寫下的代碼,也就是接收到消息之后要做什么。
public interface Callback { public boolean handleMessage(Message msg); } public void handleMessage(Message msg) { }
這里簡單說下整個過程:
當(dāng)我們實(shí)例化一個Handler的子類并重寫handleMessage方法之后,這個時候系統(tǒng)已經(jīng)幫我們做了幾個事情
1.實(shí)例化了一個消息隊(duì)列MessageQueue
2.實(shí)例化了一個關(guān)聯(lián)的Looper對象,并讓Looper不斷的讀取消息隊(duì)列
3.把我們重寫的handleMessage方法記錄為我們需要回調(diào)的方法
當(dāng)我們執(zhí)行Handler的sendMessage方法的時候,系統(tǒng)會把我們傳過去的Message對象添加到消息隊(duì)列,這個時候如果Looper讀取到了消息,就會把消息派發(fā)出去,然后回調(diào)handleMessage方法,執(zhí)行我們設(shè)定的代碼。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android實(shí)現(xiàn)水波紋效果實(shí)例代碼
大家好,本篇文章主要講的是Android實(shí)現(xiàn)水波紋效果實(shí)例代碼,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下2022-02-02Android Studio 如何刪除/新建一個module(圖文教程詳解)
這篇文章主要介紹了Android Studio 如何刪除/新建一個module,此方法也會將該module從你的硬盤中刪除,如果直接右鍵會發(fā)現(xiàn)沒有delete選項(xiàng),本文通過圖文并茂的形式給大家介紹的非常詳細(xì),需要的朋友參考下吧2020-03-03Android利用CircleImageView實(shí)現(xiàn)圓形頭像的方法
這篇文章主要介紹了Android利用CircleImageView實(shí)現(xiàn)圓形頭像的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-10-10Android界面 NotificationManager使用Bitmap做圖標(biāo)
Android界面 NotificationManager使用Bitmap做圖標(biāo),如何實(shí)現(xiàn)呢,本文將介紹解決方法,需要的朋友可以參考下2012-12-12android-使用環(huán)信SDK開發(fā)即時通信功能(附源碼下載)
本篇文章主要介紹了android-使用環(huán)信SDK開發(fā)即時通信功能,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。2016-12-12手機(jī)/移動前端開發(fā)需要注意的20個要點(diǎn)
本文主要介紹了手機(jī)/移動前端開發(fā)需要注意的20個要點(diǎn),具有很好的參考價值。下面跟著小編一起來看下吧2017-03-03