Android的消息机制

Android的消息机制主要是指Handler的运行机制,Handler的运行机制需要底层的MessageQueue和Looper的支撑。MessageQueue的中文翻译是消息队列,顾名思义,它的内部存储了一组消息,以队列的形式对外提供插入和删除的工作。虽然叫消息队列,但是它的内部存储结构并不是真正的队列,而是采用单链表的数据结构来存储消息列表。Looper的中文翻译为循环,这里可以理解为消息循环。由于MessageQueue只是一个消息的存储容器,它不能处理消息,而Looper填补了这个功能,否则就一直等待着。Looper中还有一个特殊的概念,就是ThreadLocal,ThreadLocal并不是线程,它的作用是可以在每一个线程中存储数据。我们知道,Handler创建的时候会采用当前线程的Looper来构造消息循环系统,那么Handler内部如何获取到当前线程的Looper呢?这就要使用ThreadLocal了,ThreadLocal可以在不同的线程中互不干扰地存储数据,通过ThreadLocal可以轻松获取每个线程的Looper。需要注意的是,线程默认是没有Looper的,如果需要使用Handler就必须为线程创建Looper。我们经常提到的主线程,也就是UI线程,它就是ActivityThread,ActivityThread被创建时就初始化Looper,这也是主线程中默认可以使用Handler的原因。

1、Android的消息机制概述

前面提到,Android的消息机制主要指Handler的运行机制以及Handler所附带的MessageQueue和Looper的工作过程,这三者实际上是一个整体,只不过我们开发过程中去比较多接触到Handler而已。Handler的主要作用是将一个任务切换到某个指定的线程中去执行。因为Android中规定,访问UI只能在主线程中进行,如果在子线程中访问UI就会抛出异常。ViewRootImpl对UI操作做了验证,这个验证工作是由ViewRootlmpl的checkThread方法来完成的,如下所示:

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

针对checkThread方法中抛出的异常信息,相信各位在开发中都曾经遇到过。因为这个限制,使得必须在主线程中访问UI,但是Android有不建议在主线程中进行耗时操作,否则会导致程序无法响应即ANR。考虑一种情况,假如我们需要充服务器拉取一些信息并将其显示在UI上,这时候必须在子线程中进行拉取工作,拉取完毕不能再子线程中直接访问UI,如果没有Handler,那么我们的确没有办法将访问UI的工作切换到主线程中去执行。因此,系统之所以提供Handler,主要原因就是为了解决子线程中无法访问UI的矛盾。

延伸一下,系统为什么不允许在子线程中访问UI 呢?
因为Android中的UI控件不是线程安全的,如果在多线程中并发访问可能会导致UI控件处于不可预期的状态。那,能否为UI控件加上锁机制呢?
会产生两个严重的缺点:
1.加上锁机制会让UI访问的逻辑变得复杂
2.锁机制会降低UI访问的效率(因为锁机制会阻塞某些线程的执行)

我们在前面说过,子线程是没有Looper的,如果要使用Looper,需要为当前线程创建Looper,或者在一个有Looper的线程中创建Handler也行。

Handler创建完毕后,这时候其内部的Looper以及MessageQueue就可以和Handler一起协同工作了,然后通过Handler的post方法将一个Runnable投递到Handler内部的Looper中去处理,也可以通过Handler的send方法发送一个消息,这个消息同样会在Looper中处理。其实post方法最终也是通过send方法来完成的,接下来主要看一下send方法将这个消息放入消息队列里,然后Looper发现有新消息到了时就会处理这个消息,最终消息中的Runnable或者Handler的HandlerMessage方法就会被调用。注意Looper是运行在创建Handler所在的线程中的,这样Handler中的业务逻辑就被切换到创建Handler所在的线程中去了

2.Android的消息机制分析

2.1ThreadLocal的工作原理

ThreadLocal是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据数据,数据存储以后,只有在指定线程中可以获取到存储的数据,对于其他线程来说则无法获取到数据。ThreadLocal的使用场景不好统一描述,一般来说,当某些数据是以线程为作用域并且不同线程具有不同的Looper,这时候通过ThreadLocal就可以轻松实现Looper在线程中的存取。如果不采用ThreadLocal,那么系统就必须提供一个全局的哈希表供Handler查找指定线程的Looper,这样就必须提供类似于LooperManager的类了。但是系统并没有这么做而是选择了ThreadLocal,这就是ThreadLocal的好处了。

ThreadLocal另一个使用场景是复杂逻辑下的对象传递,比如监听器的传递。有时候一个线程中的任务过于复杂,这可能表现为函数调用栈比较深以及代码入口的多样性,在这种情况下,我们又需要监听能够贯穿整个线程的执行过程,这个时候怎么做呢?
这时就可以用ThreadLocal,采用ThreadLocal可以让监听器作为线程内的全局对象而存在,在线程内只用通过get方法就额可以获取到监听器。如果不采用ThreadLocal,那么我们能想到的可能就是如下两种方法:1.将监听器通过参数形式在函数调用栈中进行传递2.将监听器作为静态变量供线程访问

这两个方法都是有局限性的。方法1的问题是当函数调用栈很浅的时候,通过函数参数来传递监听器对象这几乎是不可接受的,因为会让程序设计看起来很糟糕;方法2.是可以接受的,但是这种状态是不可扩充的,比如有两个线程在执行,那么就需要提供两个静态的监听器对象,如果有10个线程在并发执行呢?还要提供10个静态监听器对象?这是不可思议的,而采用ThreadLocal,每个监听器对象都在自己的线程内部存储,根本就不会有方法2的问题。

下面通过一个例子演示一下ThreadLocal的真正含义。首先定义一个ThreadLocal对象,这里选择Boolean类型的,如果下所示

private ThreadLocal<Boolean> booleanLocal=new ThreadLocal<Boolean>();

然后分别在主线程、子线程1和子线程2中设置和访问它的值,代码如下所示:

booleanThreadLocal.set(true);
Log.d(TAG,"[Thead#main]booleanThreadLocal="+booleanThreadLocal.get());

new Thread("Thread#1"){
     @Override
     public void run(){
     booleanLocal.set(false);
     Log.d(TAG,"[Thead#1]booleanThreadLocal="+booleanLocal.get());
     }
  }.start();

new Thread("Thread#2"){
      @Override
      public void run(){
      Log.d(TAG,"[Thead#2]booleanThreadLocal="+booleanLocal.get());
       }
 }.start();

在上面的代码中,主线程中设置booleanLocal的值为true,在子线程1中设置booleanLocal的值为false,在子线程2不设置booleanLocal的值。然后分别在3个线程中通过get方法取booleanLocal的值,根据前面对ThreadLocal的描述,这时候,主线程中应该是true,子线程1中应该是false,而子线程2中由于没有设置值,所以应该是null。安装并运行程序,日志如下:

ThreadLocaltest: [Thead#main]booleanThreadLocal=true
ThreadLocaltest: [Thead#1]booleanThreadLocal=false
ThreadLocaltest: [Thead#2]booleanThreadLocal=null

从上面的日志来看,虽然在不同的线程中访问的是同一个对象,但是他们通过ThreadLocal获取到的值却是不一样的,这就是ThreadLcoal的奇妙之处。结合这个例子,然后再看一遍前面对ThreadLocal的两个使用场景的理论分析,我们应该就能比较好地理解ThreadLocal的使用方法了。ThreadLocal之所以有这么奇妙的效果,是因为不同线程访问同一个ThreadLocal的get方法,ThreadLocal内部会从各自的线程中取出一个数组,然后再从数组中根据当前ThreadLcoal的索引去查找出对应的value值。很显然,不同线程中的数组是不同的,这就为什么通过ThreadLocal可以在不同的线程中维护一套数据的副本彼此互不干扰。

对ThreadLocal的使用方法和工作过程做了介绍之后,下面分析ThreadLocal的内部实现,ThreadLocal是一个泛型类,它的定义为public class ThreadLcoal ,只需要弄清楚ThreadLocal的get和set方法就可以明白它的工作原理了

首先看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);
    }

在上面的set方法中,首先通过getMap方法获取当前线程中的ThreadLocalMap。接下来看看map的值是如何存储进去的

private void set(ThreadLocal<?> key, Object value) {

            // We don't use a fast path as with get() because it is at
            // least as common to use set() to create new entries as
            // it is to replace existing ones, in which case, a fast
            // path would fail more often than not.

            Entry[] tab = table;
            int len = tab.length;
            int i = key.threadLocalHashCode & (len-1);

            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                ThreadLocal<?> k = e.get();

                if (k == key) {
                    e.value = value;
                    return;
                }

                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

            tab[i] = new Entry(key, value);
            int sz = ++size;
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }

上面分析了ThreadLocal的set方法,这里来分析它的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();
    }

2.2消息队列的工作原理

消息队列在Andrid中指的是MessageQueue,MessageQueue主要包含两个操作:插入和读取。读取本身伴随着删除操作,插入和读取对应的方法分别是enqueueMessage和next,其中enqueueMessage的作用是往消息队列里插入一条消息,而next的作用是从消息队列中取出一条消息并将其从消息队列中移除。尽管MessageQueue叫做消息队列,但是它的内部实现并不是用的队列,实际上它是通过一个单向链表的数据结构来维护消息列表,单链表在插入和删除上比较有优势。下面看一下它的enqueueMessage方法和next方法的实现

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

可以发现next方法是一个无限循环的方法,如果消息队列中没有消息,那么next方法会一直阻塞在这里。当有新消息到来时,next方法会返回这条消息并将其从单链表中移除。

2.3 Looper的工作原理

2.2介绍了消息队列的主要实现,下面咱们分析一下Looper的具体实现。Looper在Android的消息机制中扮演着消息循环的角色,具体来说就是它会不停地从MessageQueue中查看是否有新的消息,如果有新消息就会处理,否则就一直阻塞在哪里。先来看一下它的构造方法,在构造方法中它会创建一个MessageQueue即消息队列,然后将当前线程的对象保存起来,如下:

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

我们知道,Handler的工作需要Looper,如果没有Looper的线程就会报错,那么如何为一个线程创建Looper呢?其实很简单,通过Looper.prepare()即可为当前线程创建一个Looper,接着通过Looper.loop()来开启消息循环,如下:

new Thread(){
	@Override
	public void run(){
		Looper.prepare();
		Handler handler=new Handler();
		Looper.loop();
	};
}.start();

Looper除了prepare方法外,还提供了prepareMainLooper方法,这个方法主要给主线程也就是ActivityThread创建Looper使用的,其本质也是通过prepare方法来实现的。由于主线程的Looper比较特殊,所以Looper提供了一个getMainLooper方法,通过它可以在 任何地方获取到主线程的Looper。Looper也是可以退出的,Looper提供了quit和tuitSafely来退出一个Looper。二者的区别在于:quit会直接退出Looper,而quitSafely只是设定一个退出标记,然后把消息队列中的已有消息处理完毕才安全退出。

Looper退出后,通过Handler发送的消息会失败,这时候Handler的send方法会返回false。子线程中,如果手动为其创建 了Looper,那么在所有的事情完成以后应该调用quit方法来终止消息循环,否则这个子线程就会一直处于等待的状态,而如果退出Looper以后,这个线程就会离开终止,因此建议不需要的时候终止Looper。

Looper最重要的一个方法是loop方法,只有调用了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();
        }
    }

Looper的loop方法的工作过程也比较好理解,loop方法是一个死循环,唯一跳出循环的方式是MessageQueue的next方法返回了null。当Looper的quit方法被调用的时候,Looper就会调用MessageQueue的quit或者quitSafely方法来通知消息队列退出当消息队列被标记为退出状态时,它的next方法就会返回null。也是就说Looper必须退出,否则loop方法就会无限循环下去。loop方法会调用MessageQueue的next方法来获取新消息,而next是一个阻塞操作,当没有消息时,next方法会一直阻塞在那里。如果MessageQueue的next返回了新消息,Looper就会处理这条消息:msg.target.dispatchMessage(msg),这里的msg.target是发送这条消息的Handler对象。这样Handler发送的消息最终又交给它的dispatchMessage方法来处理了。不同的是,Handler的dispatchMessage方法是在创建Handler时所使用的Looper中执行的,这样就成功地将代码逻辑切换到指定的线程中去执行了。

2.4 Handler的工作原理

Handler的工作主要包含消息的发送和接收过程。消息的发送可以通过post的一系列方法以及send的一系列方法来实现,post的一系列方法最终是通过send的一系列方法来实现的。发送一条消息的典型过程如下:

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);
    }
    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

可以发现,Handler发送消息的过程仅仅是向消息队列中插入了一条消息,MessageQueue的next方法就会返回这条消息给Looper,Looper收到消息后就可以处理了,最终消息由Handler处理,即Handler的dispatchMessage方法会被调用,这时Handler就进入了处理消息的阶段。dispatchMessage的实现如下所示。

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

Handler处理消息的过程如下:

首先检查Message的callback是否为null,不为null就通过handleCallback来处理消息。Message的callback是一个Runnable对象实际就是Handler的post方法所传递的Runnable参数。handleCallback的逻辑也很简单,如下:

private static void handleCallback(Message message) {
        message.callback.run();
    }

其次,检查mCallback是否为null,不为null就调用mCallback的handleMessage方法来处理消息。Callback是一个接口,它的定义如下:

/**
     * Callback interface you can use when instantiating a Handler to avoid
     * having to implement your own subclass of Handler.
     *
     * @param msg A {@link android.os.Message Message} object
     * @return True if no further handling is desired
     */
    public interface Callback {
        public boolean handleMessage(Message msg);
    }

通过Callback可以采用如下方式来创建Handler对象:Handler handler=new Handler(callback)。那么Callback的意义是什么呢?源码里的注释以及做了说明:可以用来创建一个handler的实例但并不需要创建子类。在日常开发中,创建handler最常见的方式就是派生一个Handler的子类并重写其HandleMessage方法来处理具体的消息,而Callback给我们提供了另一种使用Handler的方式,当我们不想派生子类的时候,就可以通过Callback来实现.

3.主线程的消息循环

Androidd 主线程就是ActivityThread,主线程的入口方法为main,在main方法中系统会通过Looper.prepareMainLooper()来创建主线程的Looper以及MessageQueue,并通过Looper.loop()来开启主线程的消息循环.

ActivityThread通过ApplicationThread和AMS进行进程间通信,AMS以进程间通信的方式完成ActivityThread的请求后,会回调ApplicationThread的Binder方法,然后ApplicationThread会向H发送消息,H收到消息后会将ApplicationThread中的逻辑切换到ActivityThread中去执行,即切换到主线程中去执行,这过程就是主线程的消息循环模型。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值