Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> [Android]簡略的Android消息機制源碼分析

[Android]簡略的Android消息機制源碼分析

編輯:關於Android編程

相關源碼
framework/base/core/java/andorid/os/Handler.java
framework/base/core/java/andorid/os/Looper.java
framework/base/core/java/andorid/os/Message.java
framework/base/core/java/andorid/os/MessageQueue.java
libcore/luni/src/main/java/java/lang/ThreadLocal.java

1. 為什麼需要消息機制?

首先我們知道Android中有兩個特別重要的機制,一個是Binder,另一個是消息機制(Handler + Looper + MessageQueue)。畢竟Android是以消息驅動的方式來進行交互的。

為什麼需要在android中添加這樣的消息機制呢?

有時候我們需要在子線程中進行好事的I/O操作,可能是讀取文件或訪問網絡,當耗時操作完成以後可能要在UI上做一些改變,但由於Android的開發規范,不可以在子線程上更新UI,否則就會觸發程序異常,這個時候就可以通過Handler來將更新UI的操作切換到主線程中執行。因此,本質上來說Handler並不是專門用於更新UI的,他只是常常被開發者用來更新UI。

 


為什麼不可以在子線程中訪問UI呢?

 

這是因為Android的UI空間不是線程安全的,如果在多線程中並發訪問可能導致UI空間處於不可預期的狀態。當然也不可以在UI空間的訪問加鎖,原因有兩個,首先加鎖會讓UI訪問的邏輯變得復雜;其次鎖機制會降低UI訪問的效率,因為鎖機制會阻塞某些線程的執行。
鑒於這兩個缺點,最簡單搞笑的方法就是采用單線程模型來處理UI操作,對於開發者來說也不是很麻煩,只是需要通過Handler來切換一下UI訪問的執行線程即可。

2.消息機制概述

\
Message: 消息分為硬件產生的消息和軟件產生的消息
MessageQueue:消息隊列的主要功能向消息池投遞消息-enqueueMessage和取走消息池的消息-next;
Handler:消息輔助類,主要功能向消息池發送各種消息事件-sendMessage和處理相應消息事件-handleMessage;
Looper:不斷循環執行-loop,按分發機制將消息分發給目標處理者。

首先需要在主線程中建立一個Handler對象,並重寫Handler.Message(),並調用sendMessage(),將之存到MessageQueue中,而Looper則會一直嘗試從MessageQueue中取出待處理消息,最後分發回handleMessage()中,這是一個無限循環。Looper若沒有新消息需要處理則會進入等待狀態,直到有消息需要處理為止。<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxwPiZuYnNwOzwvcD4NCjxwPrzytaXAtMu1PGJyIC8+DQoqIExvb3BlciDW0NPQTWVzc2FnZVF1ZXVlPGJyIC8+DQoqIE1lc3NhZ2VRdWV1ZdbQ09DSu9fptP20psDttcRNZXNzYWdlPGJyIC8+DQoqIE1lc3NhZ2XT0NK7uPbTw9PatKbA7c/7z6K1xEhhbmRsZXI8YnIgLz4NCiogSGFuZGxlctbQ09BMb29wZXK6zU1lc3NhZ2VRdWV1ZTwvcD4NCjxoMiBpZD0="3消息機制分析">3.消息機制分析

Android的消息機制主要包括Hanler、Looper、MessageQueue和ThreadLocal

3.1 ThreadLocal工作原理

ThreadLocal是一個線程內部的數據存儲類,可以理解為一個HashMap。
當某些數據是以先成為作用域並且不同線程具有不用的數據副本的時候,就可以采用ThreadLocal。
對於Handler來說,它需要獲取當前線程的Looper,很顯然Looper的作用於就是線程並且不同線程具有不同的Looper,這個時候通過ThreadLocal就可以輕松實現Looper在線程中的存取。如果不采用ThreadLocal,那麼系統就必須提供一個全局的哈希表提供Handler查找指定的Looper。最後還是和ThreadLocal一個道理。

ThreadLocal常用的就兩個方法,get和set。set就沒什麼好說的,我們主要需要了解get。通過get,ThreadLocal內部會從各自的線程中取出一個數組,然後再從數組中根據當前ThreadLocal的索引去查找出對應的value,因而ThreadLocal可以在不同的線程中維護一套數據的副本而且不會彼此干擾。

接著我們來看set和get的源碼,通過這兩個就可以大致明白它的工作原理。

首先看set的源碼

    public void set(T value) {
        Thread currentThread = Thread.currentThread();
        Values values = values(currentThread);
        if (values == null) {
            values = initializeValues(currentThread);
        }
        values.put(this, value);
    }

    Values values(Thread current) {
        return current.localValues;
    }

    void put(ThreadLocal key, Object value) {
            cleanUp();

            // Keep track of first tombstone. That's where we want to go back
            // and add an entry if necessary.
            int firstTombstone = -1;

            for (int index = key.hash & mask;; index = next(index)) {
                Object k = table[index];

                if (k == key.reference) {
                    // Replace existing entry.
                    table[index + 1] = value;
                    return;
                }

                if (k == null) {
                    if (firstTombstone == -1) {
                        // Fill in null slot.
                        table[index] = key.reference;
                        table[index + 1] = value;
                        size++;
                        return;
                    }

                    // Go back and replace first tombstone.
                    table[firstTombstone] = key.reference;
                    table[firstTombstone + 1] = value;
                    tombstones--;
                    size++;
                    return;
                }

                // Remember first tombstone.
                if (firstTombstone == -1 && k == TOMBSTONE) {
                    firstTombstone = index;
                }
            }
        }

通過這段代碼可以知道,通過使用Thread的方法localValues來獲取當前ThreadLocal的數據,
localValues的值通過put就可以存在它內部的一個table數組中。
通過閱讀put的源碼,我們可以知道ThreadLocal的值在table中的存儲位置總是為了ThreadLocal的reference字段所標識的對象的下一個位置,即table[index+1] = value。

再來看get。

    public T get() {
        // Optimized for the fast path.
        Thread currentThread = Thread.currentThread();
        Values values = values(currentThread);
        if (values != null) {
            Object[] table = values.table;
            int index = hash & values.mask;
            if (this.reference == table[index]) {
                return (T) table[index + 1];
            }
        } else {
            values = initializeValues(currentThread);
        }

        return (T) values.getAfterMiss(this);
    }

這個的邏輯就相當清楚了,前兩步和set一樣,接著判斷value是否為null,如果是null,則返回由initializeValues設定的初始值,否則就返回table[index+1]的值。

3.2 MessageQueue的工作原理

MessageQueue主要有兩個操作,插入和讀取,相對應的是enqueueMessage和next。
MessageQueue內部是采用的單鏈表的數據結構來維護MessageQueue的,畢竟單鏈表在插入和刪除上面比較有優勢。

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("MessageQueue", 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;
}

enqueueMessage的主要操作就是單鏈表的插入操作了

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 (false) Log.v("MessageQueue", "Returning message: " + msg);
                    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("MessageQueue", "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;
    }
}

next則是讀取,並且這是一個無限循環的方法,如果消息隊列中沒有消息,那麼next則會一直阻塞。當有新消息到來時,next方法會返回這條消息並將其從單鏈表中移除。

3.3 Looper的工作原理

(1)創建消息循環

prepare()用於創建Looper消息循環對象。Looper對象通過一個成員變量ThreadLocal進行保存。

(2)獲取消息循環對象

myLooper()用於獲取當前消息循環對象。Looper對象從成員變量ThreadLocal中獲取。

(3)開始消息循環

loop()開始消息循環。循環過程如下:

每次從消息隊列MessageQueue中取出一個Message

使用Message對應的Handler處理Message

已處理的Message加到本地消息池,循環復用

循環以上步驟,若沒有消息表明消息隊列停止,退出循環

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 Looper myLooper() {
    return sThreadLocal.get();
}

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

3.4 Handler的工作原理

(1)發送消息

Handler支持2種消息類型,即Runnable和Message。因此發送消息提供了post(Runnable r)和sendMessage(Message msg)兩個方法。從下面源碼可以看出Runnable賦值給了Message的callback,最終也是封裝成Message對象對象。學姐個人認為外部調用不統一使用Message,應該是兼容Java的線程任務,學姐認為這種思想也可以借鑒到平常開發過程中。發送的消息都會入隊到MessageQueue隊列中。

(2)處理消息

Looper循環過程的時候,是通過dispatchMessage(Message msg)對消息進行處理。處理過程:先看是否是Runnable對象,如果是則調用handleCallback(msg)進行處理,最終調到Runnable.run()方法執行線程;如果不是Runnable對象,再看外部是否傳入了Callback處理機制,若有則使用外部Callback進行處理;若既不是Runnable對象也沒有外部Callback,則調用handleMessage(msg),這個也是我們開發過程中最常覆寫的方法了。

(3)移除消息

removeCallbacksAndMessages(),移除消息其實也是從MessageQueue中將Message對象移除掉。

public void handleMessage(Message msg) {
}

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

public final Message obtainMessage()
{
    return Message.obtain(this);
}

public final boolean post(Runnable r)
{
   return  sendMessageDelayed(getPostMessage(r), 0);
}

public final boolean sendMessage(Message msg)
{
    return sendMessageDelayed(msg, 0);
}

private static Message getPostMessage(Runnable r) {
    Message m = Message.obtain();
    m.callback = r;
    return m;
}

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

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

public final void removeCallbacksAndMessages(Object token) {
    mQueue.removeCallbacksAndMessages(this, token);
}

代碼裡面有個Callback,跟蹤一下會發現這是一個接口,它是用於創建一個Handler的實例但並不需要派生Handler的子類,在日常開發中,最常見的方式就是派生一個Handler的子類並重寫其handleMessage來處理具體消息,而Callback給我們提供了另一種使用Handler的方式。總結一下Handler的消息處理流程如下圖

\
最後用一張圖來說明Message、Handler、Looper之間的關系。

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