Android非同步訊息機制
目錄介紹
- 1.Handler的常見的使用方式
- 2.如何在子執行緒中定義Handler
- 3.主執行緒如何自動呼叫Looper.prepare()
- 4.Looper.prepare()方法原始碼分析
- 5.Looper中用什麼儲存訊息
- 6.Handler傳送訊息如何運作
- 7.Looper.loop()方法原始碼分析
- 8.runOnUiThread如何實現子執行緒更新UI
- 9.Handler的post方法和view的post方法
- 10.得出部分結論
好訊息
- 部落格筆記大彙總【16年3月到至今】,包括Java基礎及深入知識點,Android技術部落格,Python學習筆記等等,還包括平時開發中遇到的bug彙總,當然也在工作之餘收集了大量的面試題,長期更新維護並且修正,持續完善……開源的檔案是markdown格式的!同時也開源了生活部落格,從12年起,積累共計47篇[近20萬字],轉載請註明出處,謝謝!
- 連結地址:https://github.com/yangchong211/YCBlogs
- 如果覺得好,可以star一下,謝謝!當然也歡迎提出建議,萬事起於忽微,量變引起質變!
-
- 如何在子執行緒中定義Handler,主執行緒如何自動呼叫Looper.prepare(),Looper.prepare()方法原始碼分析,Looper中用什麼儲存訊息,Looper.loop()方法原始碼分析,runOnUiThread如何實現子執行緒更新UI等等
-
- 為什麼不允許在子執行緒中訪問UI,Handler訊息機制作用,避免子執行緒手動建立looper,ActivityThread原始碼分析,ActivityThread原始碼分析,Looper死迴圈為什麼不會導致應用卡死,會消耗大量資源嗎?
1.Handler的常見的使用方式
-
handler機制大家都比較熟悉呢。在子執行緒中傳送訊息,主執行緒接受到訊息並且處理邏輯。如下所示
- 一般handler的使用方式都是在主執行緒中定義Handler,然後在子執行緒中呼叫mHandler.sendXx()方法,這裡有一個疑問可以在子執行緒中定義Handler嗎?
public class MainActivity extends AppCompatActivity { private TextView tv ; /** * 在主執行緒中定義Handler,並實現對應的handleMessage方法 */ public static Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 101) { Log.i("MainActivity", "接收到handler訊息..."); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); tv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread() { @Override public void run() { // 在子執行緒中傳送非同步訊息 mHandler.sendEmptyMessage(1); } }.start(); } }); } }
2.如何在子執行緒中定義Handler
-
直接在子執行緒中建立handler,看看會出現什麼情況?
- 執行後可以得出在子執行緒中定義Handler物件出錯,難道Handler物件的定義或者是初始化只能在主執行緒中?其實不是這樣的,錯誤資訊中提示的已經很明顯了,在初始化Handler物件之前需要呼叫Looper.prepare()方法
tv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread() { @Override public void run() { Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 1) { Log.i(TAG, "在子執行緒中定義Handler,接收並處理訊息"); } } }; } }.start(); } });
-
如何正確執行。在這裡問一個問題,在子執行緒中可以吐司嗎?答案是可以的,只不過又條件,詳細可以看這篇文章02.Toast原始碼深度分析
- 這樣程式已經不會報錯,那麼這說明初始化Handler物件的時候我們是需要呼叫Looper.prepare()的,那麼主執行緒中為什麼可以直接初始化Handler呢?難道是主執行緒建立handler物件的時候,會自動呼叫Looper.prepare()方法的嗎?
tv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread() { @Override public void run() { Looper.prepare(); Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 1) { Log.i(TAG, "在子執行緒中定義Handler,接收並處理訊息"); } } }; Looper.loop(); } }.start(); } });
3.主執行緒如何自動呼叫Looper.prepare()
-
首先直接可以看在App初始化的時候會執行ActivityThread的main方法中的程式碼,如下所示
- 可以看到Looper.prepare()方法在這裡呼叫,所以在主執行緒中可以直接初始化Handler了。
public static void main(String[] args) { //省略部分程式碼 Looper.prepareMainLooper(); ActivityThread thread = new ActivityThread(); thread.attach(false); if (sMainThreadHandler == null) { sMainThreadHandler = thread.getHandler(); } if (false) { Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread")); } Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); }
-
並且可以看到還呼叫了:Looper.loop()方法,可以知道一個Handler的標準寫法其實是這樣的
Looper.prepare(); Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 101) { Log.i(TAG, "在子執行緒中定義Handler,並接收到訊息"); } } }; Looper.loop();
4.Looper.prepare()方法原始碼分析
-
原始碼如下所示
- 可以看到Looper中有一個ThreadLocal成員變數,熟悉JDK的同學應該知道,當使用ThreadLocal維護變數時,ThreadLocal為每個使用該變數的執行緒提供獨立的變數副本,所以每一個執行緒都可以獨立地改變自己的副本,而不會影響其它執行緒所對應的副本。
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.prepare()能否呼叫兩次或者多次
- 如果執行,則會報錯,並提示prepare中的Excetion資訊。由此可以得出在每個執行緒中Looper.prepare()能且只能呼叫一次
//這裡Looper.prepare()方法呼叫了兩次 Looper.prepare(); Looper.prepare(); Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 1) { Log.i(TAG, "在子執行緒中定義Handler,並接收到訊息。。。"); } } }; Looper.loop();
5.Looper中用什麼儲存訊息
-
先看一下下面得原始碼
- 看Looper物件的構造方法,可以看到在其構造方法中初始化了一個MessageQueue物件。MessageQueue也稱之為訊息佇列,特點是先進先出,底層實現是單連結串列資料結構
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)); } private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
-
得出結論
- Looper.prepare()方法初始話了一個Looper物件並關聯在一個MessageQueue物件,並且一個執行緒中只有一個Looper物件,只有一個MessageQueue物件。
6.Handler傳送訊息如何運作
-
首先看看構造方法
- 可以看出在Handler的構造方法中,主要初始化了一下變數,並判斷Handler物件的初始化不應再內部類,靜態類,匿名類中,並且儲存了當前執行緒中的Looper物件。
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; }
-
看handler.sendMessage(msg)方法
- 關於下面得原始碼,是步步追蹤,看enqueueMessage這個方法,原來msg.target就是Handler物件本身;而這裡的queue物件就是我們的Handler內部維護的Looper物件關聯的MessageQueue物件。
handler.sendMessage(message); //追蹤到這一步 public final boolean sendMessage(Message msg){ return sendMessageDelayed(msg, 0); } 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); }
-
看MessageQueue物件的enqueueMessage方法
- 看到這裡MessageQueue並沒有使用列表將所有的Message儲存起來,而是使用Message.next儲存下一個Message,從而按照時間將所有的Message排序
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; }
7.Looper.loop()方法原始碼分析
-
看看裡面得原始碼,如下所示
- 看到Looper.loop()方法裡起了一個死迴圈,不斷的判斷MessageQueue中的訊息是否為空,如果為空則直接return掉,然後執行queue.next()方法
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; 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 final Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs; final long traceTag = me.mTraceTag; if (traceTag != 0 && Trace.isTagEnabled(traceTag)) { Trace.traceBegin(traceTag, msg.target.getTraceName(msg)); } final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); final long end; try { msg.target.dispatchMessage(msg); end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); } finally { if (traceTag != 0) { Trace.traceEnd(traceTag); } } if (slowDispatchThresholdMs > 0) { final long time = end - start; if (time > slowDispatchThresholdMs) { Slog.w(TAG, "Dispatch took " + time + "ms on " + Thread.currentThread().getName() + ", h=" + msg.target + " cb=" + msg.callback + " msg=" + msg.what); } } 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(); } }
-
看queue.next()方法原始碼
- 大概的實現邏輯就是Message的出棧操作,裡面可能對執行緒,併發控制做了一些限制等。獲取到棧頂的Message物件之後開始執行:msg.target.dispatchMessage(msg)
Message next() { // Return here if the message loop has already quit and been disposed. // This can happen if the application tries to restart a looper after quit // which is not supported. final long ptr = mPtr; if (ptr == 0) { return null; } int pendingIdleHandlerCount = -1; // -1 only during first iteration int nextPollTimeoutMillis = 0; for (;;) { if (nextPollTimeoutMillis != 0) { Binder.flushPendingCommands(); } nativePollOnce(ptr, nextPollTimeoutMillis); synchronized (this) { // Try to retrieve the next message. Return if found. final long now = SystemClock.uptimeMillis(); Message prevMsg = null; Message msg = mMessages; if (msg != null && msg.target == null) { // Stalled by a barrier. Find the next asynchronous message in the queue. do { prevMsg = msg; msg = msg.next; } while (msg != null && !msg.isAsynchronous()); } if (msg != null) { if (now < msg.when) { // Next message is not ready. Set a timeout to wake up when it is ready. nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE); } else { // Got a message. mBlocked = false; if (prevMsg != null) { prevMsg.next = msg.next; } else { mMessages = msg.next; } msg.next = null; if (DEBUG) Log.v(TAG, "Returning message: " + msg); msg.markInUse(); return msg; } } else { // No more messages. nextPollTimeoutMillis = -1; } // Process the quit message now that all pending messages have been handled. if (mQuitting) { dispose(); return null; } // If first time idle, then get the number of idlers to run. // Idle handles only run if the queue is empty or if the first message // in the queue (possibly a barrier) is due to be handled in the future. if (pendingIdleHandlerCount < 0 && (mMessages == null || now < mMessages.when)) { pendingIdleHandlerCount = mIdleHandlers.size(); } if (pendingIdleHandlerCount <= 0) { // No idle handlers to run. Loop and wait some more. mBlocked = true; continue; } if (mPendingIdleHandlers == null) { mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)]; } mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers); } // Run the idle handlers. // We only ever reach this code block during the first iteration. for (int i = 0; i < pendingIdleHandlerCount; i++) { final IdleHandler idler = mPendingIdleHandlers[i]; mPendingIdleHandlers[i] = null; // release the reference to the handler boolean keep = false; try { keep = idler.queueIdle(); } catch (Throwable t) { Log.wtf(TAG, "IdleHandler threw exception", t); } if (!keep) { synchronized (this) { mIdleHandlers.remove(idler); } } } // Reset the idle handler count to 0 so we do not run them again. pendingIdleHandlerCount = 0; // While calling an idle handler, a new message could have been delivered // so go back and look again for a pending message without waiting. nextPollTimeoutMillis = 0; } }
-
那麼msg.target是什麼呢?通過追蹤可以知道就是定義的Handler物件,然後檢視一下Handler類的dispatchMessage方法:
- 可以看到,如果我們設定了callback(Runnable物件)的話,則會直接呼叫handleCallback方法
- 在初始化Handler的時候設定了callback(Runnable)物件,則直接呼叫run方法。
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(); }
8.runOnUiThread如何實現子執行緒更新UI
-
看看原始碼,如下所示
- 如果msg.callback為空的話,會直接呼叫我們的mCallback.handleMessage(msg),即handler的handlerMessage方法。由於Handler物件是在主執行緒中建立的,所以handler的handlerMessage方法的執行也會在主執行緒中。
- 在runOnUiThread程式首先會判斷當前執行緒是否是UI執行緒,如果是就直接執行,如果不是則post,這時其實質還是使用的Handler機制來處理執行緒與UI通訊。
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } } @Override public final void runOnUiThread(Runnable action) { if (Thread.currentThread() != mUiThread) { mHandler.post(action); } else { action.run(); } }
9.Handler的post方法和view的post方法
-
Handler的post方法實現很簡單,如下所示
mHandler.post(new Runnable() { @Override public void run() { } }); public final boolean post(Runnable r){ return sendMessageDelayed(getPostMessage(r), 0); }
-
view的post方法也很簡單,如下所示
- 可以發現其呼叫的就是activity中預設儲存的handler物件的post方法
public boolean post(Runnable action) { final AttachInfo attachInfo = mAttachInfo; if (attachInfo != null) { return attachInfo.mHandler.post(action); } ViewRootImpl.getRunQueue().post(action); return true; } public void post(Runnable action) { postDelayed(action, 0); } public void postDelayed(Runnable action, long delayMillis) { final HandlerAction handlerAction = new HandlerAction(action, delayMillis); synchronized (this) { if (mActions == null) { mActions = new HandlerAction[4]; } mActions = GrowingArrayUtils.append(mActions, mCount, handlerAction); mCount++; } }
10.得出部分結論
-
得出得結論如下所示
- 1.主執行緒中定義Handler物件,ActivityThread的main方法中會自動建立一個looper,並且與其繫結。如果是子執行緒中直接建立handler物件,則需要手動建立looper。不過手動建立不太友好,需要手動呼叫quit方法結束looper。這個後面再說
- 2.一個執行緒中只存在一個Looper物件,只存在一個MessageQueue物件,可以存在N個Handler物件,Handler物件內部關聯了本執行緒中唯一的Looper物件,Looper物件內部關聯著唯一的一個MessageQueue物件。
- 3.MessageQueue訊息佇列不是通過列表儲存訊息(Message)列表的,而是通過Message物件的next屬性關聯下一個Message從而實現列表的功能,同時所有的訊息都是按時間排序的。
關於其他內容介紹
01.關於部落格彙總連結
02.關於我的部落格
- 我的個人站點:www.yczbj.org,www.ycbjie.cn
- github:https://github.com/yangchong211
- 知乎:https://www.zhihu.com/people/yang-chong-69-24/pins/posts
- 簡書:http://www.jianshu.com/u/b7b2c6ed9284
- csdn:http://my.csdn.net/m0_37700275
- 喜馬拉雅聽書:http://www.ximalaya.com/zhubo/71989305/
- 開源中國:https://my.oschina.net/zbj1618/blog
- 泡在網上的日子:http://www.jcodecraeer.com/member/content_list.php?channelid=1
- 郵箱:yangchong211@163.com
- 阿里雲部落格:https://yq.aliyun.com/users/article?spm=5176.100- 239.headeruserinfo.3.dT4bcV
- segmentfault頭條:https://segmentfault.com/u/xiangjianyu/articles
相關文章
- Android中的非同步訊息處理機制Android非同步
- 深入理解Android非同步訊息處理機制Android非同步
- Android原始碼解析之一 非同步訊息機制Android原始碼非同步
- Android訊息機制Message訊息池Android
- android訊息機制—HandlerAndroid
- 理解 Android 訊息機制Android
- Android訊息機制HandlerAndroid
- Android 之訊息機制Android
- Android的訊息機制Android
- android之 Android訊息機制Android
- Android訊息傳遞之Handler訊息機制Android
- Android訊息機制Handler用法Android
- Android 訊息機制詳解Android
- Android訊息機制(七) RxjavaAndroidRxJava
- OC訊息機制,訊息轉發機制
- [Android進階]Android訊息機制Android
- Android Handler 訊息機制詳述Android
- Android的Handler訊息機制 解析Android
- 深入理解Android訊息機制Android
- Android訊息機制原始碼分析Android原始碼
- 訊息機制
- Android 訊息機制詳解(Android P)Android
- Android非同步訊息處理機制詳解及原始碼分析Android非同步原始碼
- Service初探與非同步訊息處理機制非同步
- 全面剖析Android訊息機制原始碼Android原始碼
- 深入理解 Android 訊息機制原理Android
- 深入探索Android訊息機制之HandlerAndroid
- 淺析Android中的訊息機制Android
- Android程式間通訊–訊息機制及IPC機制實現薦Android
- iOS訊息機制iOS
- SAP訊息機制
- Android 訊息機制:Handler、MessageQueue 和 LooperAndroidOOP
- 由外到內——剖析Android訊息機制Android
- Android-Handler訊息機制實現原理Android
- 原始碼分析:Android訊息處理機制原始碼Android
- Android應用程式訊息處理機制Android
- 06.Android之訊息機制問題Android
- Android進階;Handler訊息機制詳解Android