Android消息機制


概述

  Android UI是線程不安全的,如果在子線程中嘗試進行UI操作,程序就有可能會崩潰,因為在ViewRootImpl.checkThread對UI操作做了驗證,導致必須在主線程中訪問UI,但Android在主線程中進行耗時的操作會導致ANR,為了解決子線程無法訪問UI的矛盾,提供了消息機制。

void checkThread() {
    if (mThread != Thread.currentThread()) {
        throw new CalledFromWrongThreadException(
                "Only the original thread that created a view hierarchy can touch its views.");
    }
}

  Android消息機制主要指Handler的運行機制,Handler的運行需要底層的MessageQueue和Looper的支撐。MQ即消息隊列,存儲消息的單元,但並不能處理消息,這時需要Looper,它會無限循環查找是否有新消息,有即處理消息,沒有就等待。
Handler的創建方式很簡單,只需要new一個實例即可,但是當前線程中沒有Looper而創建Handler就會導致報錯,下面來看下兩個Handler的創建過程,看看有什么不一樣。

private Handler handler1;
private Handler handler2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    handler1 = new Handler();
    new Thread(new Runnable() {
        @Override
        public void run() {
            handler2 = new Handler();
        }
    }).start();
}

  運行下會發現handler2會報下面的錯誤“Can't create handler inside thread that has not called Looper.prepare()”

11-14 11:51:56.591 5751-5769/com.fomin.demo E/AndroidRuntime: FATAL EXCEPTION: Thread-642
    Process: com.fomin.demo, PID: 5751
    java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
        at android.os.Handler.<init>(Handler.java:200)
        at android.os.Handler.<init>(Handler.java:114)
        at com.fomin.demo.MainActivity$1.run(MainActivity.java:20)
        at java.lang.Thread.run(Thread.java:818)

  為什么handler1沒有報錯呢?因為Handler的創建時會采用當前線程的Looper來構建內部的消息循環系統,而handler1是在主線程創建的,而主線程已經默認調用Looper.prepareMainLooper()創建Looper,所以handler2創建時需要先調用Looper.prepare()創建Looper。

  接下來看下整個Handler的處理流程並且會具體分析下ThreadLocal、Handler、MessageQueue和Looper,如圖:
圖片

ThreadLocal工作原理

  ThreadLocal是一個線程內部的的數據存儲類,通過它可以在指定的線程中存儲數據,存儲以后,也只能在指定的線程中獲取存儲數據,對於其他線程來說則無法獲取到數據。在Handler中,需要獲取當前的線程的Looper,而Looper作用域就是線程並且不同線程具有不同的Looper,使用ThreadLocal可以輕松實現Looper在線程中的存取。
  先看一個例子,分別在主線程、線程1和線程2設置和訪問它的值,如下:

private ThreadLocal<Boolean> mBooleanThreadLocal = new ThreadLocal<>();
Log.d(TAG, "Current Thread: mBooleanThreadLocal is : " + mBooleanThreadLocal.get());
new Thread("Thread#1") {
    @Override
    public void run() {
        mBooleanThreadLocal.set(false);
        Log.d(TAG, "Thread 1: mBooleanThreadLocal is : " + mBooleanThreadLocal.get());

    }
}.start();

new Thread("Thread#2") {
    @Override
    public void run() {
        Log.d(TAG, "Thread 2: mBooleanThreadLocal is : " + mBooleanThreadLocal.get());
    }
}.start();

  運行程序,日志如下:

11-14 14:18:41.731 7754-7754/com.fomin.demo D/MainActivity: Current Thread: mBooleanThreadLocal is : true
11-14 14:18:41.731 7754-7807/com.fomin.demo D/MainActivity: Thread 1: mBooleanThreadLocal is : false
11-14 14:18:41.731 7754-7808/com.fomin.demo D/MainActivity: Thread 2: mBooleanThreadLocal is : null

  日志可以看出,不同線程訪問同一個ThreadLocal對象,但是他們的值是不一樣的。因為ThreadLocal會從各自的線程中取出一個數據,然后數組根據當前ThreadLocal的索引去查找對應的value值。可以先看下ThreadLocal的set方法:

public void set(T value) {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
}

  在看下get方法

public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
        }
    }
    return setInitialValue();
}

  ThreadLocal的get和set方法操作的對象都是當前線程ThreadLocalMap,讀寫操作僅限於各自線程的內部。這也是為什么ThreadLocal在多個線程中互不干擾的操作。

MessageQueue工作原理

  MessageQueue只有兩個操作:插入和讀取。其內部是一個單鏈表的數據結構來維護消息列表,鏈表的節點就是 Message。它提供了 enqueueMessage() 來進行插入新的消息,提供next() 從鏈表中取出消息,值得注意的是next()會循環地從鏈表中取出 Message 交給 Handler,但如果鏈表為空的話會阻塞這個方法,直到有新消息到來。

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(TAG, 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主要操作就是單鏈表的插入操作,在看下next方法

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 (DEBUG) Log.v(TAG, "Returning message: " + msg);
                    msg.markInUse();
                    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);
        }
        ...
        // 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方法是一個無線信息的方法,如果消息隊列沒有消息,會一直阻塞在這里。

Looper工作原理

  Looper在Android的消息機制中扮演着消息循環的角色,它不停從MessageQueue查看是否有新消息,有會立即處理,否則會一直阻塞在那里。
Looper會在構造方法中構建一個MessageQueue和當前線程對象。

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

  Looper提供了兩個退出方法quit和quitSafely,區別是前個是直接退出,后一個把消息隊列中已有的消息處理完畢后安全退出,均是調用MessageQueue中退出quit方法。

public void quit() {
    mQueue.quit(false);
}
public void quitSafely() {
    mQueue.quit(true);
}

void quit(boolean safe) {
    if (!mQuitAllowed) {
        throw new IllegalStateException("Main thread not allowed to quit.");
    }

    synchronized (this) {
        if (mQuitting) {
            return;
        }
        mQuitting = true;

        if (safe) {
            removeAllFutureMessagesLocked();
        } else {
            removeAllMessagesLocked();
        }

        // We can assume mPtr != 0 because mQuitting was previously false.
        nativeWake(mPtr);
    }
}

  Looper最重要的方法是loop方法,只有調用了loop后,消息系統才會真正的起作用,具體代碼如下

/**
 * Run the message queue in this thread. Be sure to call
 * {@link #quit()} to end the 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();

    // Allow overriding a threshold with a system prop. e.g.
    // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
    final int thresholdOverride =
            SystemProperties.getInt("log.looper."
                    + Process.myUid() + "."
                    + Thread.currentThread().getName()
                    + ".slow", 0);

    boolean slowDeliveryDetected = false;

    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
        final Printer logging = me.mLogging;
        if (logging != null) {
            logging.println(">>>>> Dispatching to " + msg.target + " " +
                    msg.callback + ": " + msg.what);
        }

        final long traceTag = me.mTraceTag;
        long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
        long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
        if (thresholdOverride > 0) {
            slowDispatchThresholdMs = thresholdOverride;
            slowDeliveryThresholdMs = thresholdOverride;
        }
        final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
        final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);

        final boolean needStartTime = logSlowDelivery || logSlowDispatch;
        final boolean needEndTime = logSlowDispatch;

        if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
            Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }

        final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
        final long dispatchEnd;
        try {
            msg.target.dispatchMessage(msg);
            dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        if (logSlowDelivery) {
            if (slowDeliveryDetected) {
                if ((dispatchStart - msg.when) <= 10) {
                    Slog.w(TAG, "Drained");
                    slowDeliveryDetected = false;
                }
            } else {
                if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
                        msg)) {
                    // Once we write a slow delivery log, suppress until the queue drains.
                    slowDeliveryDetected = true;
                }
            }
        }
        if (logSlowDispatch) {
            showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", 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();
    }
}

  loop方法是一個死循環,唯一跳出就是next返回null。如果next返回了新消息,會調用msg.target.dispatchMessage(msg)處理消息(即Handler處理)。

Handler工作原理

  Handler的工作主要包含消息的發送和接收過程。消息發送通過post系列方法和send系列方法來實現,而post最終還是調用sendMessageAtTime方法來實現發送消息。

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

  可以發現,發送消息最終只是在向消息隊列中插入了一條消息,流程MessageQueue——>Looper——>Handler,最終在dispatchMessage處理,由handleMessage消費。

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM