Android Handler原理

来源:https://www.cnblogs.com/android-rui/archive/2018/08/17/9468017.html
-Advertisement-
Play Games

Android線程間的通信是使用消息機制來實現的。線程通過Looper建立自己的消息迴圈, 對應MessageQueue。 MessageQueue是FIFO的消息隊列。Looper負責從MessageQueue中取出消息,並且分發到消息指定的目標Handler對象,由Handler對象對Messa ...


       Android線程間的通信是使用消息機制來實現的。線程通過Looper建立自己的消息迴圈, 對應MessageQueue。 MessageQueue是FIFO的消息隊列。Looper負責從MessageQueue中取出消息,並且分發到消息指定的目標Handler對象,由Handler對象對Message進行處理。

      

 

每個app都有自己對應的MessageQueue.

每個線程有且最多只能有一個Looper對象,它是一個ThreadLocal
一個線程對應一個Looper(消息迴圈),一個MessageQueue(消息隊列)
Looper對象的創建是通過prepare函數,而且每一個Looper對象會和一個線程關聯.
Looper對象創建時會創建一個MessageQueue,主線程預設會創建一個Looper從而有MessageQueue,其他線程預設是沒有 MessageQueue的不能接收Message,如果需要接收Message則需要通過prepare函數創建一個MessageQueue。
Looper內部有一個消息隊列,loop()方法調用後線程開始不斷從隊列中取出消息執行
Loop函數從MessageQueue中從前往後取出Message,然後通過Handler的dispatchMessage函數進行消息的處理(可見消息的處理是Handler負責的),消息處理完了以後通過Message對象的recycle函數放到Message Pool中,以便下次使用,通過Pool的處理提供了一定的記憶體管理從而加速消息對象的獲取
Looper使一個線程變成Looper線程。
Looper是線程用來運行消息迴圈的。線程本身是沒有消息迴圈的,需要線上程中調用prepare函數,然後調用loop去處理消息。

 

 

 

 

  

主要是下麵四隻文件:

frameworks\base\core\java\android\os\Looper.java
frameworks\base\core\java\android\os\Handler.java
frameworks\base\core\java\android\os\MessageQueue.java
frameworks\base\core\java\android\os\Message.java

/frameworks/base/core/java/android/os/Handler.java

192 public Handler(Callback callback, boolean async) {
193 if (FIND_POTENTIAL_LEAKS) {
194 final Class<? extends Handler> klass = getClass();
195 if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
196 (klass.getModifiers() & Modifier.STATIC) == 0) {
197 Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
198 klass.getCanonicalName());
199 }
200 }
201
202 mLooper = Looper.myLooper();
203 if (mLooper == null) {
204 throw new RuntimeException(
205 "Can't create handler inside thread that has not called Looper.prepare()");
206 }
207 mQueue = mLooper.mQueue;
208 mCallback = callback;
209 mAsynchronous = async;
210 }

 

/frameworks/base/core/java/android/os/MessageQueue.java 

309 Message next() {
310 // Return here if the message loop has already quit and been disposed.
311 // This can happen if the application tries to restart a looper after quit
312 // which is not supported.
313 final long ptr = mPtr;
314 if (ptr == 0) {
315 return null;
316 }
317
318 int pendingIdleHandlerCount = -1; // -1 only during first iteration
319 int nextPollTimeoutMillis = 0;
320 for (;;) {
321 if (nextPollTimeoutMillis != 0) {
322 Binder.flushPendingCommands();
323 }
324
325 nativePollOnce(ptr, nextPollTimeoutMillis);
326
327 synchronized (this) {
328 // Try to retrieve the next message. Return if found.
329 final long now = SystemClock.uptimeMillis();
330 Message prevMsg = null;
331 Message msg = mMessages;
332 if (msg != null && msg.target == null) {
333 // Stalled by a barrier. Find the next asynchronous message in the queue.
334 do {
335 prevMsg = msg;
336 msg = msg.next;
337 } while (msg != null && !msg.isAsynchronous());
338 }
339 if (msg != null) {
340 if (now < msg.when) {
341 // Next message is not ready. Set a timeout to wake up when it is ready.
342 nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
343 } else {
344 // Got a message.
345 mBlocked = false;
346 if (prevMsg != null) {
347 prevMsg.next = msg.next;
348 } else {
349 mMessages = msg.next;
350 }
351 msg.next = null;
352 if (DEBUG) Log.v(TAG, "Returning message: " + msg);
353 msg.markInUse();
354 return msg;
355 }
356 } else {
357 // No more messages.
358 nextPollTimeoutMillis = -1;
359 }
360
361 // Process the quit message now that all pending messages have been handled.
362 if (mQuitting) {
363 dispose();
364 return null;
365 }
366
367 // If first time idle, then get the number of idlers to run.
368 // Idle handles only run if the queue is empty or if the first message
369 // in the queue (possibly a barrier) is due to be handled in the future.
370 if (pendingIdleHandlerCount < 0
371 && (mMessages == null || now < mMessages.when)) {
372 pendingIdleHandlerCount = mIdleHandlers.size();
373 }
374 if (pendingIdleHandlerCount <= 0) {
375 // No idle handlers to run. Loop and wait some more.
376 mBlocked = true;
377 continue;
378 }
379
380 if (mPendingIdleHandlers == null) {
381 mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
382 }
383 mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
384 }
385
386 // Run the idle handlers.
387 // We only ever reach this code block during the first iteration.
388 for (int i = 0; i < pendingIdleHandlerCount; i++) {
389 final IdleHandler idler = mPendingIdleHandlers[i];
390 mPendingIdleHandlers[i] = null; // release the reference to the handler
391
392 boolean keep = false;
393 try {
394 keep = idler.queueIdle();
395 } catch (Throwable t) {
396 Log.wtf(TAG, "IdleHandler threw exception", t);
397 }
398
399 if (!keep) {
400 synchronized (this) {
401 mIdleHandlers.remove(idler);
402 }
403 }
404 }
405
406 // Reset the idle handler count to 0 so we do not run them again.
407 pendingIdleHandlerCount = 0;
408
409 // While calling an idle handler, a new message could have been delivered
410 // so go back and look again for a pending message without waiting.
411 nextPollTimeoutMillis = 0;
412 }
413 }

 

535 boolean enqueueMessage(Message msg, long when) {
536 if (msg.target == null) {
537 throw new IllegalArgumentException("Message must have a target.");
538 }
539 if (msg.isInUse()) {
540 throw new IllegalStateException(msg + " This message is already in use.");
541 }
542
543 synchronized (this) {
544 if (mQuitting) {
545 IllegalStateException e = new IllegalStateException(
546 msg.target + " sending message to a Handler on a dead thread");
547 Log.w(TAG, e.getMessage(), e);
548 msg.recycle();
549 return false;
550 }
551
552 msg.markInUse();
553 msg.when = when;
554 Message p = mMessages;
555 boolean needWake;
556 if (p == null || when == 0 || when < p.when) {
557 // New head, wake up the event queue if blocked.
558 msg.next = p;
559 mMessages = msg;
560 needWake = mBlocked;
561 } else {
562 // Inserted within the middle of the queue. Usually we don't have to wake
563 // up the event queue unless there is a barrier at the head of the queue
564 // and the message is the earliest asynchronous message in the queue.
565 needWake = mBlocked && p.target == null && msg.isAsynchronous();
566 Message prev;
567 for (;;) {
568 prev = p;
569 p = p.next;
570 if (p == null || when < p.when) {
571 break;
572 }
573 if (needWake && p.isAsynchronous()) {
574 needWake = false;
575 }
576 }
577 msg.next = p; // invariant: p == prev.next
578 prev.next = msg;
579 }
580
581 // We can assume mPtr != 0 because mQuitting is false.
582 if (needWake) {
583 nativeWake(mPtr);
584 }
585 }
586 return true;
587 }

 

/frameworks/base/core/java/android/os/Looper.java

129 public static void loop() {
130 final Looper me = myLooper();
131 if (me == null) {
132 throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
133 }
134 final MessageQueue queue = me.mQueue;
135
136 // Make sure the identity of this thread is that of the local process,
137 // and keep track of what that identity token actually is.
138 Binder.clearCallingIdentity();
139 final long ident = Binder.clearCallingIdentity();
140
141 for (;;) {
142 Message msg = queue.next(); // might block
143 if (msg == null) {
144 // No message indicates that the message queue is quitting.
145 return;
146 }
147
148 // This must be in a local variable, in case a UI event sets the logger
149 final Printer logging = me.mLogging;
150 if (logging != null) {
151 logging.println(">>>>> Dispatching to " + msg.target + " " +
152 msg.callback + ": " + msg.what);
153 }
154
155 final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
156
157 final long traceTag = me.mTraceTag;
158 if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
159 Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
160 }
161 final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
162 final long end;
163 try {
164 msg.target.dispatchMessage(msg);
165 end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
166 } finally {
167 if (traceTag != 0) {
168 Trace.traceEnd(traceTag);
169 }
170 }
171 if (slowDispatchThresholdMs > 0) {
172 final long time = end - start;
173 if (time > slowDispatchThresholdMs) {
174 Slog.w(TAG, "Dispatch took " + time + "ms on "
175 + Thread.currentThread().getName() + ", h=" +
176 msg.target + " cb=" + msg.callback + " msg=" + msg.what);
177 }
178 }
179
180 if (logging != null) {
181 logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
182 }
183
184 // Make sure that during the course of dispatching the
185 // identity of the thread wasn't corrupted.
186 final long newIdent = Binder.clearCallingIdentity();
187 if (ident != newIdent) {
188 Log.wtf(TAG, "Thread identity changed from 0x"
189 + Long.toHexString(ident) + " to 0x"
190 + Long.toHexString(newIdent) + " while dispatching to "
191 + msg.target.getClass().getName() + " "
192 + msg.callback + " what=" + msg.what);
193 }
194
195 msg.recycleUnchecked();
196 }
197 }

 

1. Handler可以在任意線程發送消息,這些消息會被添加到關聯的Message Queue上.

2. Handler是在它關聯的Looper線程中處理消息的.

3. 開發者需要重寫Handler的handleMessage().

 

 Message Structure

 

 

一個線程只有一個消息迴圈looper和一個消息隊列;但是可以有多個handler,那麼如何區分消息發送給誰處理呢?
每個消息中都有target對應的handler對象
將消息壓入消息隊列: Message對象的target欄位關聯了哪個線程的消息隊列, 這個消息就會被壓入哪個線程的消息隊列中.
調用Handler對象的方法入隊的Message(最終都會調用enqueueMessage), 其target屬性會被賦值為這個handler對象.
調用Handler類中以send開頭的方法可以將Message對象壓入消息隊列中;
調用Handler類中以post開頭的方法可以將一個runnable對象包裝在一個Message對象中, 然後再壓入消息隊列, 此時入隊的Message其callback欄位不為null, 值就是這個runnable對象.
調用Message對象的sendToTarget()方法可以將其本身壓入與其target欄位(即handler對象)所關聯的消息隊列 中. 
從消息隊列中取出消息並處理消息: 所有在消息隊列中的消息, 都具有target欄位. 消息是在target所關聯的線程上被取出和處理的.

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 抓到視窗期,分享紅利,所有為快不破!!! 當年學習移動互聯網的程式員現在年薪都50萬了,抓住機遇創業的都成功了 如今會多種主流後端技術的複合型人才已成為市場標配,這就是Java大數據 Java開發、大數據 人才缺口達到20萬以上,每年以20%的速度在增長 後端伺服器開發最流行的是Java開發,而開發 ...
  • 一. 查詢緩存 1.開啟緩存 設置了緩存開啟,緩存最大限制128M,重啟服務後,再次查詢 2 測試緩存 現在是緩存2次,命中一次 上面是二個查詢sql語句,此時緩存數是4,如下圖所示: 此時緩存數是6,說明緩存區分where條件值的大小寫。同樣也會區分sql關鍵詞的大小寫。如下圖所示: 設置好que ...
  • 什麼是SYS_OP_C2C呢?官方的介紹如下: SYS_OP_C2C is an internal function which does an implicit conversion of varchar2 to national character set using TO_NCHAR func... ...
  • " " 思維導圖可在 "幕布" 找到 1. 基礎 如果在相對佈局里,控制項沒有指明相對位置,則預設都是在相對佈局的左上角: gravity 屬性用來設置容器內組件的對齊方式 效果為 2. 根據兄弟控制項定位 2.1 相對兄弟組件的位置 代碼示例 等屬性通過制定控制項的 來選擇需要參考的兄弟組件,即 : 顯 ...
  • Xutils這個框架非常全面,可以進行網路請求,可以進行圖片載入處理,可以數據儲存,還可以對view進行註解,使用這個框架非常方便,但是缺點也是非常明顯的,使用這個項目,會導致項目對這個框架依賴非常的嚴重,一旦這個框架出現問題,那麼對項目來說影響非常大的。、 OKhttp:Android開發中是可以 ...
  • 系統架構分析 體繫結構 安卓結構有四大層,五個部分, 分四層為: 應用層 ,應用框架層 ,系統運行層 和`Linux`內核層。 那麼我來講講應用層有什麼? 就是一些應用軟體,如首頁,聯繫人,電話,瀏覽器等等;應用框架如何理解? 應用框架層是用 寫的,有事件管理器, 管理器,內容提供,查看系統 ,消息 ...
  • 所謂“工欲善其事,必先利其器”。Android Studio 是谷歌推出一個Android集成開發工具,基於IntelliJ IDEA. 類似 Eclipse ADT,Android Studio 提供了集成的 Android 開發工具用於開發和調試。 在IDEA的基礎上,Android Studi ...
  • 一.什麼是模塊化 什麼是模塊化呢?有一種定義是:模塊化是一種處理複雜系統分解為更好的可管理模塊的方式。由此可見,模塊化思路下構成的複雜系統是由各個可管理的子模塊構成的,每個子模塊之前相互獨立,並通過某種特定的方式進行通信。在工業上面,有模塊化汽車的概念,也有模塊化手機的概念,各個模塊根據一定的標準進 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...