Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

深入理解 Android 異步消息處理機制

編輯:Android 資訊

一、概述

Android 中的異步消息處理主要由四部分組成:Message、Handler、MessageQueue 和 Looper。它們的關係如圖所示:

1. Message 是線程之間傳遞的消息,可以在內部攜帶少量信息,用於在不同線程間交換數據。

2. MessageQueue 是消息隊列,用於存放所有由 Handler 發送過來的消息,這些消息會一直排隊等待被處理。每個線程中只有一個 MessageQueue 對象。

3. Handler 是處理者,負責發送和處理消息。發送一般用 sendMessage(),處理則調用 handleMessage()。

4. Looper 是每個線程中 MessageQueue 的管家。調用 loop() 後便進入一個無限循環,每當發現隊列中有消息就取出,交給 handleMessage() 處理。每個線程中也只有一個 Looper 對象。

二、詳細介紹

1、Looper

Looper 主要是 prepare() 和 loop() 兩個方法。

public static final void prepare() { if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper(true)); }

sThreadLocal 是一個 ThreadLocal 對象,可以在一個線程中存儲變量,Looper 就存在這裡面。這個方法被調用後,會先判斷當前線程有沒有 Looper:沒有就創建一個,有就拋異常。可見 prepare() 不能被調用兩次,這就保證了一個線程只有一個 Looper。

再看 Looper 的構造函數:

private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mRun = true; mThread = Thread.currentThread(); }

構造函數裡創建了 MessageQueue 對象,這也保證了一個線程只有一個 MessageQueue。

然後看 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(); 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.recycle(); } }

這個方法先調用 myLooper() 拿到 sThreadLocal 裡保存的 Looper,再拿到它對應的 MessageQueue,然後進入無限循環。循環主要做兩件事:取出一條消息(沒有就阻塞);調用 msg.target.dispatchMessage(msg),把消息交給 msg 的 target 去處理。

Looper 的主要作用:

1、與當前線程綁定,保證一個線程只有一個 Looper 實例,同時一個 Looper 也只有一個 MessageQueue。
2、loop() 方法不斷從 MessageQueue 取消息,交給消息 target 屬性的 dispatchMessage 去處理。

2、Handler

用 Handler 之前,我們都會先初始化一個實例。比如用於更新 UI 時,我們會在聲明處直接初始化,或在 onCreate 中初始化:

private Handler mHandler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case value: break; default: break; } }; };

三、小結

1、首先 Looper.prepare() 在本線程保存一個 Looper 實例,該實例裡又保存一個 MessageQueue;因為 prepare() 在一個線程只能調用一次,所以 MessageQueue 在一個線程也只會有一個。可能有人會問:Activity 裡我們並沒顯式調用 Looper.prepare() 和 Looper.loop(),為何 Handler 還能成功創建?這是因為在 Activity 的啟動代碼裡,已經在當前 UI 線程調用過這兩個方法了。

2、Looper.loop() 讓當前線程進入一個無限循環,不斷從 MessageQueue 讀取消息,然後回調 msg.target.dispatchMessage(msg)。

3、Handler 的構造方法會先拿到當前線程保存的 Looper 實例,並與它裡面的 MessageQueue 關聯起來。

4、Handler 的 sendMessage 方法會把 msg 的 target 賦值為 handler 自身,然後加入 MessageQueue。

5、構造 Handler 實例時,我們會重寫 handleMessage 方法,也就是 msg.target.dispatchMessage(msg) 最終調用的那個方法。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved