Android的Handler消息机制

本文深入剖析Android消息机制,包括Handler的运行原理、MessageQueue的工作机制、Looper的循环机制等核心内容,帮助读者全面掌握Android线程间通信的技术细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android的消息机制

概述

  • Android的消息机制主要是指Handler的运行机制,Handler的运行需要底层的MessageQueueLooper的支撑。
  • Message只是一个单链表构成的存储消息的列表
  • Looper是一个无限循环的机制,一遍一遍的去查询Message是否有新消息,如果有就去处理,没有就继续循环等待
  • Looper中还有一个特殊的概念(ThreadLocal),ThreadLocal并不是线程,他的作用是可以在每个线程里面存储数据,可以在不同线程中互不干扰的存储并提供数据

  • 我们都知道,Android是不允许在除主线程之外的线程访问UI界面的,因为为了杜绝并发访问出现显示错误,所以就直接禁止了非主线程访问UI
  • 这个限制是在ViewRootImpl的checkThread方法来做的
void checkThread() {
        if (mThread != Thread.currentThread()) {
            throw new CalledFromWrongThreadException(
                    "Only the original thread that created a view hierarchy can touch its views.");
        }
    }
  • 所以,Android提供了Handler来为我们使得我们可以更方便的访问UI

先探ThreadLocal

  • 由上面简单的说明可知,消息机制的重要工作是将一个线程的数据挪到另外一个线程,而这里ThreadLocal明显有这个能力,我们就先来分析它吧

  • ThreadLocal是一个线程内部的数据存储类,通过他可以在指定的线程中存储数据,只有在指定线程中可以获取到存储的数据
  • 一般来说,当数据以线程为作用域,并且不同线程具有不同副本的时候,可以用ThreadLocal来实现。
  • 很显然,对于Handler来说,Looper的作用域就是线程,并且不同线程具有不同的Looper,这个时候ThreadLocal就可以实现Looper在线程中数据的存取
  • 还是来看看用法吧,先定义一个Boolean类型的ThreadLocal
private ThreadLocal<Boolean> mBooleanThreadLocal = new ThreadLocal<>();
  • 然后分别在主线程,新开两个线程给他设置不同的值,如下
mBooleanThreadLocal.set(true);
Log.d(TAG, "主线程中 mBooleanThreadLocal = " + mBooleanThreadLocal.get());

new Thread("分线程一号"){
    @Override
    public void run() {
        mBooleanThreadLocal.set(false);
        Log.d(TAG, "分线程一号 mBooleanThreadLocal = " + mBooleanThreadLocal.get());
    }
}.start();

new Thread("分线程二号"){
    @Override
    public void run() {
        Log.d(TAG, "分线程二号 mBooleanThreadLocal = " + mBooleanThreadLocal.get());
    }
}.start();
  • 那么,打印出来的log信息为
主线程中 mBooleanThreadLocal = true
分线程一号 mBooleanThreadLocal = false
分线程二号 mBooleanThreadLocal = null
  • 所以,这里可以看到,虽然我们只在主线程创建了一次ThreadLocal对象,但是当我们在不同线程访问他的时候,他会在每个线程都创建一个副本(并且这个副本是初始化状态的)
  • 这就是ThreadLocal的神奇之处,每个线程对象都有一个自己的Map,这个Map是ThreadLocal的内部类,当我们set的时候,就会把set的参数和ThreadLocal对象本身以键值对的方式存储在Map 中
  • ThreadLocal内部会在每个线程调用他时,为每个线程创建一个Map,这个Map就是保存不同线程里面ThreadLocal的值的
  • 那么他在get的时候,就看看是哪个ThreadLocal对象想要获取他存在本线程中的数据,适当返回就行

消息队列(MessageQueue)的工作原理

  • 消息队列在Android中指的是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方法
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());
                    //退出dowhile的条件是到最后一个结点或者此消息是异步消息
                }
                if (msg != null) {
                //如果找到了最后一个结点,我们应该根据他的when参数,设置他什么时候被返回出去
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        //这里就是根据消息的when参数设置什么时候去执行这条消息
                        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();
                        //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(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在消息机制中扮演着消息循环的角色,会不停的从消息队列中查看是否有新消息,有则处理,无则按照消息队列的机制一直阻塞
  • 先看一下他的构造方法
private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }
  • 可以看到,我们在Looper里面初始化了一个消息队列,然后得到当前线程的实例保存在自己内部
  • 不过这个构造却是个私有的,找了找,在他的prepare方法里面找到了实例化他的方法
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));
}
  • 可见,我们只有在不存在Looper的时候才能调用此方法
  • 此外,Looper还为我们提供了prepareMainLooper这个静态方法,我们可以在我们需要的时候给主线程(也就是ActivityThread)创建Looper
  • Looper还提供了两个结束的方法quit和quitSafely,前者立即退出Looper,后者在将Looper的消息队列消息处理完才退出
  • 所以,如果是在新开的线程中使用Looper,我们应该在不需要的时候将他退出,不然这个线程就算任务执行完毕,也就一直等待下去,而不会自动销毁
  • 那么,Looper的创建说完了,我们接下来应该说说控制Looper循环的机制了,不然不会循环的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 (;;) {
        //在无限循环的内部调用消息队列的next方法,通过消息队列的机制我们可以知道
            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();
        }
    }
  • 在这个方法中我们看到处理消息是msg.target.dispatchMessage(msg);这条代码执行的,而通过查阅Message,我们知道这里的target是一个Handler对象
  • 所以说,我们通过Handler发送的消息最终又由Handler自身的dispatchMessage方法去解决了,而这个时候因为ThreadLocal的内部机制,执行的线程已经变换,那么这里的逻辑就到Handler了,我们接下来看看Handler是怎么工作的

Android之Handler解析

  • Handler是安卓线程间通信的机制,日常使用如下:
Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                //这里根据不同的what处理消息
            }
        }
    };

    {
        //在另外的线程执行发送消息的方法
        handler.sendEmptyMessage(1);
        handler.sendMessage(Message.obtain());
        handler.sendEmptyMessageDelayed(1,1000);
    }
  • 可以看到就这么简单,那么他是怎么将别的线程的东西放置到主线程的呢?
  • 不着急,我们一步一步看

先看发送消息的部分-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);
}

public final boolean sendEmptyMessage(int what){
    return sendEmptyMessageDelayed(what, 0);
}

public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
    Message msg = Message.obtain();
    msg.what = what;
    return sendMessageDelayed(msg, delayMillis);
}

public final boolean sendMessageAtFrontOfQueue(Message msg) {
    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, 0);
}

  • 可以看到,虽然重载的方法有好几个
  • 但是最终调用的都是enqueueMessage(queue, msg, 0);这个方法,根据方法名我们能判断出他是将消息放在了一个队列中,并且这个队列必须存在,否则就是发送错误
  • 我们来看一下这个方法

再看入队方法-enqueueMessage

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;//通过Message查看这个target的类型就是handler
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
  • 先看这一句,msg.target = this,那么这里的this是什么呢?我们是通过Handler的实例变量来最终调用到了这个方法,所以这个this就是这个的Handler的实例变量,或者说最终处理消息的那个线程的Handler的实例变量
  • 并且最终调用了queue.enqueueMessage,这个queue是哪里的queue呢?
  • 我们来看一下Handler的构造方法
public Handler() {
    this(null, false);
}

public Handler(Callback callback, boolean async) {
.....
    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;
}

public Handler(Looper looper, Callback callback) {
    this(looper, callback, false);
}
//其他的不贴了
  • 这里我们重点关注中间的这个方法,Handler在初始化的时候会有三个本地变量mLooper,mQueue,mCallback
  • mLooper是通过Looper.myLooper();得到
  • mQueue是mLooper的本地变量
  • mCallback是我们人为传进去的,一般我们不传这个,为空
  • 所以这里重点是这个 mLooper的获取方式
  • 来看一下Looper.myLooper();方法
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));
}
  • 看一下sThreadLocal.set(new Looper(quitAllowed));这个方法
  • SThreadLocal是Looper的本地变量,定义如下
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
  • 我们来看一下这个ThreadLocal类的实现
  • 先看一下他的构造方法
//类定义
public class ThreadLocal<T> {
//空构造
public ThreadLocal() {
}
}
  • 他的T变量是Looper
  • 又,我们在Looper的prepare方法里面调用了sThreadLocal.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);
}
  • 这里要看清楚,我们是从初始化Handler的构造方法走到这里的,所以这里的t变量就是我们Handler所属线程的引用
  • 再来看一下这个getMap(t)
ThreadLocalMap getMap(Thread t) {
    return t.threadLocals;
}
  • emmm,返回的是Thread的ThreadLocalMap对象,再根据set方法下面的代码可以知道,每个线程都会有一个ThreadLocalMap,并且这个ThreadLocalMap不是线程自己生成的,而是ThreadLocal这个类为每个需要的线程创建的
  • 那么我们就看下面的createMap(t,value)这个方法,注意这两个参数,第一个是当前线程的引用,第二个是Looper(这个参数是在Looper的prepare方法中传进来的,是一个Looper的新对象)
void createMap(Thread t, T firstValue) {
    t.threadLocals = new ThreadLocalMap(this, firstValue);
}
  • 这里是给Handler所在线程创建了一个ThreadLocalMap,第一个参数是this,由于我们是在ThreadLocal里面调用ThreadLocalMap的构造的,所以这个this是ThreadLocal的实例对象引用,而这个ThreadLocal的实例对象是我们在Looper里面的静态变量
  • 所以说,这个ThreadLocalMap的构造传进去的两个参数分别是:Looper类静态变量ThreadLocal变量和一个新的Looper对象,并且这个ThreadLocalMap在创建出来后是所属Handler所在的那个线程的
  • 我们接着来看ThreadLocalMap的构造方法
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
    table = new Entry[INITIAL_CAPACITY];
    int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
    table[i] = new Entry(firstKey, firstValue);
    size = 1;
    setThreshold(INITIAL_CAPACITY);
}
  • 可以看到,线程拥有一个Entry数组,这个数组的存储形式是hash表
  • 我们来看一下这个Entry对象
 static class Entry extends WeakReference<ThreadLocal<?>> {
    Object value;

    Entry(ThreadLocal<?> k, Object v) {
        super(k);
        value = v;
    }
}
  • 将Looper对象存到自己的地盘,将ThreadLocal对象存到entry的父类变量中,这里最终存到了他们的最终的父类Reference这个抽象类中,先不往下追究,我们接着往下看
  • 那么到这里这个Handler的初始化工作就做完了,
  • 最终的效果是:给当前线程创建了一个ThreadLocalMap,这个Map存的是ThreadLocal和Looper的键值对(这里要注意的是ThreadLocal是Looper的静态变量,所以说他在程序中只存在一个实例)
  • 上面说给线程弄了一个存ThreadLocal和Looper的Map,那么我们再接着往下看一下Looper是怎么创建的
  • 看一下他的构造方法
private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}
  • 所以,队列也有了
  • 这里稍稍总结一下,Looper是线程的ThreadLocalMap里面的,mQueue是Looper的
  • 还记得我们是怎么得到Looper的队列的吗?
  • 在Handler的构造方法中
 public Handler(Callback callback, boolean async) {
.....
        mLooper = Looper.myLooper();
.....
    }
  • 看一下Looper.myLooper();
public static @Nullable Looper myLooper() {
    return sThreadLocal.get();
}
  • 这个sThreadLocal是Looper的静态变量,看一下get方法
public T get() {
    Thread t = Thread.currentThread();
    //这个得到的Map就是线程所属的那个map,我们在前面有说到的
    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();
}
  • 看一下这个map.getEntry(this);
private Entry getEntry(ThreadLocal<?> key) {
    int i = key.threadLocalHashCode & (table.length - 1);
    Entry e = table[i];
    if (e != null && e.get() == key)
        return e;
    else
        return getEntryAfterMiss(key, i, e);
}
  • 这里传入的参数是Looper独享的类变量ThreadLocal,通过这个计算出hash地址,拿到线程变量Map的entry
  • 那么这里得到的就是在初始化的时候创建出来的那个Looper对象
  • 所以,每个线程独有Looper和Queue
  • 这里的逻辑有点多,需要仔细去理清楚,不过后面还会用到这里的逻辑,如果实在看不懂可以接着往下看看

发送消息之后,存到队列里-queue.enqueueMessage(msg, uptimeMillis);

boolean enqueueMessage(Message msg, long when) {

        synchronized (this) {

            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为结点的链表,好了,这里我们是将消息放到了当前线程所属的Queue里面了
  • 那么,将消息放进去是一回事,什么处理这些消息呢?
  • 如果你看过安卓源码,就会知道在ActivityThread的main方法的最后一行调用了Looper.loop()这个方法,如果你对Handler比较熟悉,你就会知道如果是在别的线程使用Handler的时候,我们是需要人为的去调用Looper.loop()这个方法的
  • 这个方法就是一个死循环,会不停的查看消息队列是否有消息,如果有的话就拿来处理,那么我们接下来看一下这个loop方法

Looper # loop

public static void loop() {
        //这个方法调用的是 return sThreadLocal.get();这句代码,最终返回的是当前线程的Looper
        final Looper me = myLooper();
        if (me == null) {
        //这个异常表示我们必须在loop方法之前调用Looper.prepare() 来为当前线程生成一个Looper
            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);
                }
            }
            //身份的判定吧
            // 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();
        }
    }
  • 可以看出,上面的方法主要分为三步:
  • Message msg = queue.next(); // might block 获取消息,可能会阻塞
  • msg.target.dispatchMessage(msg); //处理消息
  • msg.recycleUnchecked();//消息回收
  • 所以,我们接下来的就主要研究一下这三个方法吧
  • 先是Queue的next方法

Queue # 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();
            }
        //阻塞操作,当等待nextPollTimeoutMillis时长,或者消息队列被唤醒,都会返回。
            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;
                //由上面的分析可知,这里的this代表的是主线程的Handler对象,所以我们一般不走这里,这里先放下
                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 {
                        //所以根据逻辑,他会返回消息队列链表的第一个Message
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        //设置Message状态
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }

                // 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;
        }
    }
  • 所以这里有三个疑点:
  • 我上面注释一处的代码何时执行?
  • 为什么要在一次循环结束时直接将下次阻塞时间设置为0
  • mPendingIdleHandlers到底是干什么的?
  • 不过不影响我们继续往下看,我们接着看下面的消息处理的方法

msg.target.dispatchMessage(msg);

public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        //这是我们在设置Message的时候可以给他设置一个Callback,就是在这里执行的,这个Callback是一个Runable对象引用
        handleCallback(msg);
    } else {
        if (mCallback != null) {
        //这里的mCallBack是Handler的一个私有变量,他是一个接口类型,当我们去初始化一个handler的时候,我们可以传入这个接口的对象或者匿名类等等,这个接口也只有一个方法,就是用来处理消息的,不过这个处理会有一个返回值,代表处理成功或者失败
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        //这里是我们自己可以重写Handler的handleMessage方法来处理消息,这里相当于双层处理机制,当我们传入的接口对象未处理成功的时候,我们这里可以做最终的处理
        handleMessage(msg);
    }
}
  • 注释已经写得很清楚了,这里就不再说了
  • 再来简单的看一下消息的回收机制吧

msg.recycleUnchecked()

void recycleUnchecked() {
        // Mark the message as in use while it remains in the recycled object pool.
        // Clear out all other details.
        flags = FLAG_IN_USE;
        what = 0;
        arg1 = 0;
        arg2 = 0;
        obj = null;
        replyTo = null;
        sendingUid = -1;
        when = 0;
        target = null;
        callback = null;
        data = null;
        //上面是将所有东西都置为初始化,下面是判断一个数量,并且是一个链表用来回收,
        synchronized (sPoolSync) {
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }
  • 这里我要说的是,当我们平时使用Message的时候都尽量去调用Message的obtain方法,因为Message内部维护了一个消息池来避免Message对象的频繁创建
  • 那么,到这里呢?这个handler也就讲完了,如果跟着笔者的思路来理的话其实不难理解,这里我再说说其中笔者感觉比较重要的地方
  • 初始化Handler的时候那里的逻辑比较多,其中主要涉及到线程所属ThreadLocalMap这个东西,因为他要保证线程间数据的一致性
  • MessageQueue的next方法,理解那里的循环机制
  • 还有平时开发中如果用到Callback 这个参数的时候需要注意他的返回值

  • 那么,我们平时开发中遇到的就是这些了,可是关于Handler的消息机制却并没有完
  • 这里我再补充一些内容

同步消息之外的另外两种消息

barrier消息

  • 还记得我们在前面看到过这样一段代码吗?
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());
}
  • 这段代码是在MessageQueue的next方法内的,我们之前就说过,我们一般添加的Message都会被自动添加上target = this(也就是Handler所在线程的实例引用),那么何时这个target会为空呢?
  • 我们可以通过调用MessageQueue的postSyncBarrier方法,看一下
private int postSyncBarrier(long when) {
    // Enqueue a new sync barrier token.
    // We don't need to wake the queue because the purpose of a barrier is to stall it.
    synchronized (this) {
        final int token = mNextBarrierToken++;
        final Message msg = Message.obtain();
        msg.markInUse();
        msg.when = when;
        msg.arg1 = token;

        Message prev = null;
        Message p = mMessages;
        if (when != 0) {
            while (p != null && p.when <= when) {
                prev = p;
                p = p.next;
            }
        }
        if (prev != null) { // invariant: p == prev.next
            msg.next = p;
            prev.next = msg;
        } else {
            msg.next = p;
            mMessages = msg;
        }
        return token;
    }
}
  • 看到没,这里得到一个消息之后完全没关他的target属性就直接放到队列里面去了,所以这里的target是为null的,而且它是私有的,外部不可调用,那么这个消息是用来干嘛的呢?
  • 在这里我要解释一下Handler的消息:消息分为两类,同步消息和异步消息,同步消息就是msg.isAsynchronous()这个方法返回真,也就是async参数在Handler被初始化的时候设置为true
  • 那么?当设置了这个屏障之后,是不是就会人为的阻拦同步消息的处理,而会加快异步消息的处理,而这个正是我们在处理一些想要快速响应的消息的时候可以考虑的做法
  • 具体的应用是在网上百度的例子,Android应用框架在某些特定的场合为了更快的刷新UI,就会先发送一条barrier消息,然后在发送一条异步消息以便更快的执行
  • 那么在这里是不是突然领悟到,我们一般直接无参的去创建Handler实例其实是不太正确的呢?哈哈哈,好像也没别人说过,不管了不管了

总结

  • Handler的消息分为两类,同步消息和异步消息,通过构建Handler实例的时候传入构造方法的参数决定
  • 使用一种barrier消息可以使同步消息可以被选择性的拦截,这样就可以发送异步消息以便得到更快的执行
  • Handler通过使用Looper类的静态变量ThreadLocal来保证一个线程只有一个Looper
  • Looper中持有一个MessageQueue对象,所以,我们一般做的只是构建一个Looper就足够(如果我们要在非主线程中使用Handler)

补充一点native的东西

  • native的消息机制是在MessageQueue构造方法里面初始化的
MessageQueue(boolean quitAllowed) {
    mQuitAllowed = quitAllowed;
    mPtr = nativeInit();
}
  • native的消息Message是一个结构体
struct Message {
    Message() : what(0) { }
    Message(int w) : what(w) { }

    /* The message type. (interpretation is left up to the handler) */
    int what;
};
  • MessageQueue是用一个Voctor存储的
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值