Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android Handler Looper,MessageQueue消息機制原理

android Handler Looper,MessageQueue消息機制原理

編輯:關於Android編程

安卓消息處理類:

Looper、Handler、MessageQueue、Message、ThreadLocal、ThreadLocal.Values、HandlerThread。

Looper:

線程默認是沒有消息循環的,要為一個線程創建一個消息循環通過調用prepare(),然後在調用loop()方法進入消息循環(這意味著線程將一直在此方法循環)。例如:
class LooperThread extends Thread {
      public Handler mHandler;

      public void run() {
          Looper.prepare();

          mHandler = new Handler() {
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };

          Looper.loop();
      }
  }
那麼到這裡你肯定會想安卓的主線程並沒有prepare和loop也可以創建Handler,處理消息循環。這是因為安卓在創建主線程的時候已經為我們添加了消息循環。
那麼Looper如何管理每一個線程對應的一個looper的呢?
public final class Looper {
    // sThreadLocal.get() will return null unless you've called prepare().
    static final ThreadLocal sThreadLocal = new ThreadLocal();
    private static Looper sMainLooper;  // guarded by Looper.class

    final MessageQueue mQueue;
    final Thread mThread;

    private Printer mLogging;

    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));
    }

    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

    public static Looper getMainLooper() {
        synchronized (Looper.class) {
            return sMainLooper;
        }
    }

    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
            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);
            }

            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();
        }
    }

    public static Looper myLooper() {
        return sThreadLocal.get();
    }
下面通過圖解講解上面的過程:(prepare調用threadLocal的get的set方法) \
\

Handler類:

構造函數: 1)Handler handler = new Handler(),內部會調用 public Handler(Callback callback, boolean async)方法,將Handler的成員變量mLooper和mQueue賦值為當前線程的looper對象和對應的消息隊列,如果當前線程沒有looper會拋出異常。 2)Handler handle = new Handler(Looper looper),內部會調用public Handler(Looper looper, Callback callback, boolean async),將參數的looper對象傳遞給handler的mHandler對象,mQueue對象賦值。通過此方法可以在其它線程中為主線程創建Handler,例如:new Handler(Looper.getMainLooper());
handler的sendMessage()方法,在內部會將handler對象賦值為Message的mTarget中,然後調用mQueue將消息發送到線程的消息隊列中。

Message類:

Message類內部會保存一個Handler對象mTarget。
Looper的loop方法,取出消息,然後調用Message對象中的handler的dispatchMessage方法,dispatchMessage根據callback是否為空執行handleMessage方法。
流程圖如下: \
HandlerThread是一個可以簡單創建一個進行消息處理的線程類。

總結:

1)Thread最多與一個looper建立聯系。 2)一個looper有且僅有一個MessageQueue 3)一個handler只能與一個looper關聯 4)一個Message只能與一個handler關聯 這四個一對一的關系使得消息發送和處理得到正確的相應。











  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved