Android 消息机制

一、消息机制概述

Android的消息机制主要是指Handler的运行机制以及Handler所附带的MessageQueue和Looper的工作过程,Handler的主要作用是将一个任务切换到当前Handler所在的线程中去执行

Android提供这个功能主要是它规定了访问UI只能在主线程中进行,如果在子线程中访问UI,那么程序就会抛出异常。

以上规定的原因是:Android的UI控件不是线程安全的,如果在多线程并发访问时可能会导致UI控件处于不可预期的状态。但是加锁又会让UI的访问逻辑变得复杂;而且锁会阻塞某些线程的执行,因而锁机制会降低UI访问的效率。所以Android采用了最简单高效的一种方法——采用单线程模型来处理UI操作

二、消息机制的整体流程

Handler调用sendMessage()向MessageQueue发送一条消息,这时会调用一个MessageQueue的enqueueMessage()将消息加入MessageQueue中,MessageQueue中有消息后通过MessageQueue.next()取走消息交给Looper,当Looper发现有新消息到来后,Looper通过Looper.loop()方法不断地从消息队列中读取消息,然后将这个消息交由Handler,在Handler中的handleMessage中对消息进行处理。

三、概念释义

Handler:消息辅助类,主要功能向消息池发送各种消息事件(Handler.sendMessage)和处理相应消息事件(Handler.handleMessage)。

MessageQueue:消息队列,但是内部存储结构并不是队列,而是采用单链表的数据结构来存储消息列表(因为单链表在插入和删除上比较有优势)。

为了能够更好地理解Looper,我们需要先了解一下ThreadLocal这个概念。

  • ThreadLocal

ThreadLocal是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储以后,只有在指定线程中可以获取到存储的数据,对于其他线程来说则无法获取到数据。

为什么Looper需要用到ThreadLoacl?

因为Handler需要获取到当前线程的Looper,而Looper的作用域是线程,并且不同线程具有不同的Looper。所以这个时候通过ThreadLocal就可以轻松实现Looper在线程中的存取。如果不采用这个ThreadLocal的话那么系统就必须提供一个类似于LooperManager的类来管理Looper了,这时就体现出ThreadLocal的好处了。

Looper:消息循环,它会不停地从MessageQueue查看是否有新消息,如果有新消息就会处理,否则就会一直阻塞在那里。

四、工作原理

  • Handler的工作原理:

Handler的主要工作包含消息的发送和接收,消息的发送可以通过post或send等一系列方法来实现,但最终都是用到了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);
    }

可以看到这个函数的返回的是enqueueMessage(),相当于Handler发送消息的过程就是向消息队列插入了一条消息。

在发送完消息后,MessageQueue的next()会返回这条消息给Looper,Looper收到消息就开始处理了,最终消息由Looper交由Handler处理,这时Handler的dispatchMessage()会被调用。

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

从dispatchMessage中我们可以看到Handler就开始进入消息处理阶段了。

首先,会检查Message的callback是否为null,不为null就通过handleCallback来处理消息。Message的callback是一个Runnable对象,实际上就是Handler的post方法所传递的Runnable参数。

通过Callback可以采用如下方式来创建Handler对象:Handler handler = new Handler(callback)。这个Callback的作用就是去创建一个Handler的实例而不需要派生Handler子类。一般我们也可以直接派生一个Handler的子类,再重写hanldeMessage方法来处理具体的消息,这个Callback给我们提供了另外一种使用Handler的方式,可以让我们不派生Handler子类就可以创建Handler了。

  • MessageQueue的工作原理:

  MessageQueue主要包含两个操作:插入(enqueueMessage)和读取(next),读取的同时也包含着删除。因为单链表在插入和删除上比较有优势,所以内部是用的单链表进行的存储,这一点在上面也提到过,下面我们来看下这两个主要方法的源码。

enqueueMessage():

//这里的主要操作就是单链表的插入操作,没什么特别的
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;
    }

next():

这里面有个for的死循环,是next()读取消息的关键。如果MessageQueue中有消息的话,next就会返回消息并从单链表中移除这条消息;如果MessageQueue中没有消息的话,它就会一直阻塞在这里,等待新消息的到来

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

            // 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(TAG, "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;
        }
    }
  • Looper的工作原理:

之前说过,Looper在整个消息机制中扮演的是消息循环的角色,它会不停地从MessageQueue中查看是否有新消息,如果有新消息就会立刻处理,否则就一直阻塞在那里。

因为整个消息机制其实就是Handler的运行机制,而Handler的工作需要Looper,没有Looper的线程会报错,所以我们就需要在每个使用到Handler的线程中去创建Looper,一般在主线程当中,Looper是Android系统为我们创建好的,但是如果要在其他线程中创建Looper,就需要用到Looper的prepare()这个方法来为当前线程创建一个Looper,但是有一点需要注意,如果在子线程中手动创建了Looper,那么在所有事情处理完之后就应该调用quit()来终止消息循环,否则这个子线程会一直处于等待状态;在Looper成功创建之后,就可以通过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
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            try {
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (slowDispatchThresholdMs > 0) {
                final long time = end - start;
                if (time > slowDispatchThresholdMs) {
                    Slog.w(TAG, "Dispatch took " + time + "ms on "
                            + Thread.currentThread().getName() + ", h=" +
                            msg.target + " cb=" + msg.callback + " msg=" + msg.what);
                }
            }

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

 

你可能感兴趣的:(Android,消息机制,源码解析)