Android Handler異步消息機制詳解

前言

作爲Android開發的我們都知道,Android的主線程即UI線程是不安全的,如果我們在子線程裏去更新UI則有可能造成程序崩潰。解決辦法我們都非常的熟悉了,就是創建message,然後使用handler去發送這個message,之後在handlerMessage裏去刷新UI。我們稱之爲異步消息處理線程,但是其中的原理是怎樣的,你真的知道嗎?


源碼分析

基本使用方法這裏就不再說明了,我們或許知道’在子線程裏直接創建handler會報錯’,至於爲什麼會報錯,我們來看看Handler的構造函數:

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

代碼12行,這裏做了判斷,如果mLooper爲null那麼就拋出一個異常,這裏就能解釋我們在線程裏直接創建handler會報錯了,所以我們在子線程中創建handler之前應該先創建Looper:

Looper.prepare();

我們來看下是如何創建Looper的,進入prepare方法

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,如果有,則拋出異常’一個線程只能有一個Looper’,反之則創建Looper對象,我們進入Looper的構造函數:

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

我們發現,在Looper的構造函數裏創建了MessagerQueue,由此,我們可以得出結論MessageQueue是一一對應的,且一個線程裏只能有1個Looper和1個MessageQueue。

那爲什麼主線程可以直接創建Handler呢?現在我們應該都知道答案了,因爲主線程默認創建了Looper.進入ActivityThread的main方法:

public static void main(String[] args) {
    SamplingProfilerIntegration.start();
    CloseGuard.setEnabled(false);
    Environment.initForCurrentUser();
    EventLogger.setReporter(new EventLoggingReporter());
    Process.setArgV0("<pre-initialized>");
    Looper.prepareMainLooper();
    ActivityThread thread = new ActivityThread();
    thread.attach(false);
    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
    }
    AsyncTask.init();
    if (false) {
        Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread"));
    }
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

可以看到,在第7行調用了Looper.prepareMainLooper()方法,而這個方法又會再去調用Looper.prepare()方法,代碼如下:

public static final void prepareMainLooper() {
    prepare();
    setMainLooper(myLooper());
    if (Process.supportsProcesses()) {
        myLooper().mQueue.mQuitAllowed = false;
    }
}

現在,從我們最熟悉的代碼繼續:

mHandler.sendMessage(msg);

進入sendMessage方法:

public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }
public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }
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);
    }

這裏的mQueue,我們上面已經看到,創建Looper的時候創建,這裏是加了個判斷,進入enqueueMessage方法:

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

我們看到,最終這個消息是交給了MessageQueue去處理,進入MessageQueue的enqueueMessage方法:

 boolean enqueueMessage(Message msg, long when) {
        if (msg.isInUse()) {
            throw new AndroidRuntimeException(msg + " This message is already in use.");
        }
        if (msg.target == null) {
            throw new AndroidRuntimeException("Message must have a target.");
        }

        synchronized (this) {
            if (mQuitting) {
                RuntimeException e = new RuntimeException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w("MessageQueue", e.getMessage(), e);
                return false;
            }

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

MessageQueue是一個消息處理隊列,毫無疑問enqueueMessage方法就是入隊,這裏我們要明白的是,MessageQueue並不像集合以一樣把所有消息存在一起,而是使用mMessages代表待處理的消息,然後觀察上面的代碼的16~43行我們就可以看出,這裏的入隊,實質就是將所有消息根據時間來排序,根據就是我們傳入的uptimeMillis參數,根據時間的順序調用msg.next,從而爲每一個消息指定它的下一個消息是什麼。

那Looper對MessageQueue做了怎樣的操作呢?進入Looper.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();
        }
    }

我們可以看到,從代碼的13行開始進入死循環,不斷的調用MessageQueue的next方法,對的,next就是出隊方法。邏輯就是:如果當前MessageQueue中存在mMessages,就將這個消息出隊,然後讓下一條消息成爲mMessages,否則就進入一個阻塞狀態,一直等到有新的消息入隊。我們繼續看代碼的27行,msg.target.dispatchMessage(msg);target是什麼?進入Message源碼我們會發現,實質就是我們的Handler。進入dispatchMessage方法:

public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

這裏會判斷mCallback是否爲空,如果不爲空,handleCallback(進入Callback源碼發現調用mCallback的handleMessage()方法)將消息傳出去,如果爲空,就使用handler的handleMessage方法將消息傳出去。這個handlerMessage我們是不是很熟悉,這下我們就明白爲什麼在handlerMessage方法裏能收到消息了。

在google官方copy了一段標準的創建異步消息的代碼,相信大家會很清楚的理解:

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

在文章的開頭我們提到在多線程中直接更新UI會報錯,我們也知道用什麼方法去解決。以下三個方法,可以直接在其他線程中更新UI:

1. Handler的post()方法
2. View的post()方法
3. Activity的runOnUiThread()方法

他們的實質就是異步消息機制。這裏就不一一說明了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章