Android 消息机制原码详细解读

本文介绍了Android的消息机制,涵盖handler、looper、messageQueue和message。阐述了消息队列先进先出的链表结构,模拟实现相关方法。还介绍了自定义looper循环定时器的创建,以及消息队列的数据读取、出队、分发流程,最后说明了入队的两种方法。

android的消息机制包括:handler(处理者)、looper(循环)、messageQueue(消息队列)、message消息。

Message

public class Message implements Parcelable {
    /* ========= 消息携带的业务数据(内部状态,可复用) ========= */
    public int what;        // 用户自定义消息码
    public int arg1;        // 低负载 int 参数 1
    public int arg2;        // 低负载 int 参数 2
    public Object obj;      // 任意对象载荷

    /* ========= 框架控制字段 ========= */
    int flags;              // 标志位:FLAG_IN_USE / FLAG_ASYNCHRONOUS 等
    public long when;       // 应该被执行的绝对时间(uptimeMillis)
    Handler target;         // 目标 Handler(外部状态,每次由发送者注入)
    Runnable callback;      // 回调 Runnable(外部状态)
    Message next;           // 链表指针,构成消息队列或对象池

    /* ========= 享元对象池(Flyweight Pool) ========= */
    public static final Object sPoolSync = new Object(); // 池锁(线程安全)
    private static Message sPool;        // 链表头:空闲对象
    private static int sPoolSize = 0;    // 当前池内对象数
    private static final int MAX_POOL_SIZE = 50; // 池上限,防止无限膨胀

    /**
     * 享元工厂方法:优先从池中取,池空才 new
     * 相当于 FlyweightFactory.obtain()
     */
    public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {          // 池里有可用对象
                Message m = sPool;        // 取出头节点
                sPool = m.next;           // 链表头后移
                m.next = null;            // 断链
                m.flags = 0;              // 清除“正在使用”标志
                sPoolSize--;
                return m;                 // 返回复用对象
            }
        }
        return new Message();             // 池空则新建
    }

    /**
     * 把用完的消息回收进池(供 Handler/Looper 内部调用)
     * 1. 清零所有内部状态,避免旧数据残留
     * 2. 头插法放回链表,线程安全
     */
    void recycleUnchecked() {
        // 标记“正在使用”,防止二次回收
        flags = FLAG_IN_USE;

        /* ===== 重置复用字段(内部状态清零) ===== */
        what = 0;
        arg1 = 0;
        arg2 = 0;
        obj = null;
        replyTo = null;
        sendingUid = UID_NONE;
        workSourceUid = UID_NONE;
        when = 0;
        target = null;
        callback = null;
        data = null;

        /* ===== 放回对象池 ===== */
        synchronized (sPoolSync) {
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;   // 头插
                sPool = this;
                sPoolSize++;
            }
            // 若池已满,则直接丢弃(由 GC 回收)
        }
    }

    /**
     * 把消息标记为异步(用于屏障机制)
     * 设置/清除 FLAG_ASYNCHRONOUS 位
     */
    public void setAsynchronous(boolean async) {
        if (async) {
            flags |= FLAG_ASYNCHRONOUS;
        } else {
            flags &= ~FLAG_ASYNCHRONOUS;
        }
    }
}

MessageQueue

public final class MessageQueue {

    /* ========= 1. 基本字段 ========= */
    private final boolean mQuitAllowed;   // 是否允许退出(主线程 false,普通线程 true)
    private long mPtr;                    // native 层队列指针,0 表示已 dispose
    Message mMessages;                    // 消息链表头,按 when 升序排列

    /* ========= 2. native 方法 ========= */
    // 阻塞等待消息或超时;native 层 epoll 实现
    private native void nativePollOnce(long ptr, int timeoutMillis);
    // 立即唤醒等待的 native epoll
    private native static void nativeWake(long ptr);
    // 创建 native 队列,返回指针
    private native static long nativeInit();

    /* ========= 3. 构造 ========= */
    MessageQueue(boolean quitAllowed) {
        mQuitAllowed = quitAllowed;
        mPtr = nativeInit();              // 初始化 native 对象
    }

    /* ========= 4. 核心循环:Looper.loop() 会死循环调用 next() ========= */
    Message next() {
        final long ptr = mPtr;
        if (ptr == 0) return null;        // native 层已释放,直接退出

        int pendingIdleHandlerCount = -1; // 首次循环标记
        int nextPollTimeoutMillis = 0;    // 0:立即检查;-1:无限等待

        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands(); // 让 Binder 也处理一下
            }

            nativePollOnce(ptr, nextPollTimeoutMillis); // 阻塞直到有消息或超时

            synchronized (this) {
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;

                /* 4.1 遇到同步屏障:跳过所有同步消息,只找异步消息 */
                if (msg != null && msg.target == null) {
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }

                /* 4.2 找到待处理消息 */
                if (msg != null) {
                    if (now < msg.when) {
                        // 还没到时候,计算下次等待时间
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // 真正取出消息
                        mBlocked = false;
                        if (prevMsg != null) prevMsg.next = msg.next;
                        else mMessages = msg.next;
                        msg.next = null;
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // 队列空,无限等待
                    nextPollTimeoutMillis = -1;
                }

                /* 4.3 处理退出 */
                if (mQuitting) {
                    dispose();            // 释放 native 资源
                    return null;
                }

                /* 4.4 空闲处理器 IdleHandler(仅在首次循环且队列空时触发) */
                if (pendingIdleHandlerCount < 0 &&
                    (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    mBlocked = true;       // 继续阻塞
                    continue;
                }
                // 运行 IdleHandler
                for (int i = 0; i < pendingIdleHandlerCount; i++) {
                    IdleHandler idler = mPendingIdleHandlers[i];
                    mPendingIdleHandlers[i] = null;
                    boolean keep = idler.queueIdle(); // 回调
                    if (!keep) synchronized (this) { mIdleHandlers.remove(idler); }
                }
                pendingIdleHandlerCount = 0;
                nextPollTimeoutMillis = 0; // 立即再次检查
            }
        }
    }

    /* ========= 5. 同步屏障:插入 target==null 的占位消息 ========= */
    public int postSyncBarrier() {
        return postSyncBarrier(SystemClock.uptimeMillis());
    }

    private int postSyncBarrier(long when) {
        synchronized (this) {
            final int token = mNextBarrierToken++;   // 唯一标识
            Message msg = Message.obtain();          // 从享元池拿
            msg.markInUse();
            msg.when = when;
            msg.arg1 = token;                        // token 存 arg1
            msg.target = null;                       // 这就是“屏障”

            /* 按时间升序插入链表 */
            Message prev = null, p = mMessages;
            while (p != null && p.when <= when) { prev = p; p = p.next; }
            if (prev != null) { prev.next = msg; msg.next = p; }
            else { mMessages = msg; msg.next = p; }

            return token; // 外部用来 removeSyncBarrier
        }
    }

    /* ========= 6. 入队消息:Handler.sendMessage() 最终走到这里 ========= */
    boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) throw new IllegalArgumentException("Message must have a target.");

        synchronized (this) {
            if (msg.isInUse()) throw new IllegalStateException("msg in use");
            if (mQuitting) { msg.recycle(); return false; } // 已退出

            msg.markInUse();
            msg.when = when;

            /* 按时间升序插入链表,决定是否需要唤醒 nativePollOnce */
            Message p = mMessages;
            boolean needWake;
            if (p == null || when == 0 || when < p.when) {
                // 插入到链表头,需要唤醒
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                // 插入到中间,只当头部是屏障且最早异步消息时才需唤醒
                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;
                prev.next = msg;
            }
            if (needWake) nativeWake(mPtr);   // 立即唤醒等待线程
        }
        return true;
    }
}

Looper

public final class Looper {
    /* ========= 1. 成员变量 ========= */
    final MessageQueue mQueue;                // 当前线程的消息队列(链表 + 屏障 + epoll)
    final Thread mThread;                     // 当前 Looper 所在的线程对象
    // ThreadLocal 保证“一个线程一个 Looper”
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<>();

    /* ========= 2. 准备阶段:为当前线程创建 Looper ========= */
    private static void prepare(boolean quitAllowed) {
        // 每个线程只能调用一次 prepare()
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        // 创建 Looper 并放入 ThreadLocal
        sThreadLocal.set(new Looper(quitAllowed));
    }

    /* ========= 3. 主循环:死循环读取消息 ========= */
    public static void loop() {
        // 取出当前线程绑定的 Looper
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }

        me.mInLoop = true;                   // 防止重复 loop
        Binder.clearCallingIdentity();       // 保证线程身份一致

        // 读取系统属性,用于慢日志阈值
        final int thresholdOverride = SystemProperties.getInt(...);

        // 死循环:不断取消息并分发
        for (;;) {
            if (!loopOnce(me, Binder.clearCallingIdentity(), thresholdOverride)) {
                return;                      // 无消息 / 队列退出
            }
        }
    }

    /* ========= 4. 单次循环:取消息 → 分发 → 回收 ========= */
    private static boolean loopOnce(final Looper me, final long ident, final int thresholdOverride) {
        // 4-1 从 MessageQueue 取出下一条消息(可能阻塞)
        Message msg = me.mQueue.next();
        if (msg == null) {
            return false;                    // 队列退出 -> loop 结束
        }

        // 4-2 日志/性能统计
        final Printer logging = me.mLogging;
        final Observer observer = sObserver;
        final long traceTag = me.mTraceTag;
        long slowDispatch = me.mSlowDispatchThresholdMs;
        long slowDelivery = me.mSlowDeliveryThresholdMs;
        if (thresholdOverride > 0) {
            slowDispatch = slowDelivery = thresholdOverride;
        }

        // 4-3 真正分发:Handler.dispatchMessage(...)
        Object token = null;
        long origWorkSource = ThreadLocalWorkSource.setUid(msg.workSourceUid);
        try {
            if (observer != null) token = observer.messageDispatchStarting();
            msg.target.dispatchMessage(msg);  // 把消息交给目标 Handler
            if (observer != null) observer.messageDispatched(token, msg);
        } catch (Exception ex) {
            if (observer != null) observer.dispatchingThrewException(token, msg, ex);
            throw ex;
        } finally {
            ThreadLocalWorkSource.restore(origWorkSource);
            if (traceTag != 0) Trace.traceEnd(traceTag);
        }

        // 4-4 慢日志 & 线程身份校验
        if (slowDelivery > 0 && (SystemClock.uptimeMillis() - msg.when) > slowDelivery) {
            showSlowLog(...);
        }
        if (slowDispatch > 0 && ...) {
            showSlowLog(...);
        }
        if (logging != null) logging.println("<<<<< Finished ...");

        final long newIdent = Binder.clearCallingIdentity();
        if (ident != newIdent) {
            Log.wtf(TAG, "Thread identity changed while dispatching");
        }

        // 4-5 享元回收:把 Message 放回对象池
        msg.recycleUnchecked();
        return true;
    }

    /* ========= 5. 工具方法 ========= */
    // 返回当前线程绑定的 Looper
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }
}

Looper 通过 ThreadLocal 保证“一线程一循环”,MessageQueue 负责阻塞/唤醒取消息,loopOnce 完成 取 → 分发 → 回收 的闭环,实现 Android 主线程/Handler 的核心调度。

Handler

public class Handler {
    /* ========= 1. 关键成员 ========= */
    final Looper mLooper;           // 当前线程绑定的 Looper
    final MessageQueue mQueue;      // 该 Looper 的消息队列(链表 + 屏障)
    @UnsupportedAppUsage
    final Callback mCallback;       // 可选回调接口,替代子类重写 handleMessage
    final boolean mAsynchronous;    // 是否把消息设为异步(用于屏障插队)

    /* ========= 2. 构造方法集合 ========= */

    /**
     * 显式指定 Looper 的构造
     * 通常用于子线程或跨线程发消息
     */
    public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async) {
        mLooper = looper;
        mQueue  = looper.mQueue;   // 直接引用 Looper 里的队列
        mCallback = callback;
        mAsynchronous = async;
    }

    /**
     * 默认构造:绑定当前线程的 Looper
     * 必须在已调用 Looper.prepare() 的线程中使用
     */
    public Handler(@Nullable Callback callback, boolean async) {
        /* 可选:检测匿名/内部类导致的内存泄漏 */
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "Handler 应该是 static,否则可能内存泄漏:" + klass.getCanonicalName());
            }
        }

        mLooper = Looper.myLooper();   // 从 ThreadLocal 获取当前线程 Looper
        if (mLooper == null) {
            throw new RuntimeException(
                    "当前线程尚未调用 Looper.prepare(),无法创建 Handler");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

    /* ========= 3. 消息处理回调接口 ========= */
    public interface Callback {
        /**
         * 如果返回 true,表示消息已处理完,不再调用 handleMessage()
         */
        boolean handleMessage(@NonNull Message msg);
    }

    /**
     * 子类重写此方法即可接收消息
     * 默认空实现,子类按需实现
     */
    public void handleMessage(@NonNull Message msg) {
        // 子类实现
    }

    /* ========= 4. 消息分发:Looper → Handler ========= */
    public void dispatchMessage(@NonNull Message msg) {
        /* 4-1 优先级 1:Message 自带 Runnable(post Runnable) */
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            /* 4-2 优先级 2:Callback 接口 */
            if (mCallback != null && mCallback.handleMessage(msg)) {
                return; // Callback 已消费
            }
            /* 4-3 优先级 3:子类 handleMessage() */
            handleMessage(msg);
        }
    }

    /* 工具方法:直接运行 Runnable */
    private static void handleCallback(Message message) {
        message.callback.run();
    }

    /* ========= 5. 发送消息系列 ========= */

    /**
     * 延时 post Runnable
     * 内部把 Runnable 包装成 Message
     */
    public final boolean postDelayed(@NonNull Runnable r, long delayMillis) {
        return sendMessageDelayed(getPostMessage(r), delayMillis);
    }

    /**
     * 真正的入队入口:把消息塞进 MessageQueue
     * 设置目标 Handler、异步标记、线程 UID 等元数据
     */
    private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
                                   long uptimeMillis) {
        msg.target = this;                     // 标记消息归属(回调目标)
        msg.workSourceUid = ThreadLocalWorkSource.getUid(); // 用于线程调度

        if (mAsynchronous) {                   // 如果是异步 Handler,给消息打异步标记
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis); // 最终交给队列
    }
}

模拟消息队列

这里先理解一个消息队列这个概念,handler的消息队列是先进先出的链表结构,下面是模拟消息队列写的一些方法。

消息类的写法

public class MessageData {
    //传递的数据类型,以作判断
    public int status;
    //你需要处理的数据
    public Object data;
    //用于连接消息的类
    public MessageData message;
    //最多连接数,这里没做处理
    public int linkedSize = 0;

}

消息队列的写法

public class MessageQueueData {
    private MessageData messageData;

   //入队:将消息存入消息队列中
    public void enqueueMessage(MessageData messageData) {
        Log.e("MessageQueueData", "enqueueMessage:" + messageData.status);
        //判断消息队列是否为空,如果为空,就讲链条的第一个消息置位假如的消息
        if (this.messageData == null) {
            this.messageData = messageData;
            this.messageData.message = null;
        } else {
            //如果不为空,进行链条循环,
            //将链条的第一数据赋值
            MessageData tempMy = this.messageData;
            MessageData tempInner;
            for (; ; ) {
                //取出该数据中用于连接的数据
                tempInner = tempMy.message;
                //如果该数据不为空,将该数据置为链条的类
                if (tempInner != null) {
                    tempMy = tempInner;
                } else {
                    //如果该数据为空,将该数据假如链条,结束循环
                    tempMy.message = messageData;
                    break;
                }

            }

        }

    }
    //出队,将消息从消息队列中取出
    public void next() {
        if (this.messageData != null) {
            Log.e("MessageQueueData", "next:" + this.messageData.status);
            //取出消息,将内部连接到该类中
            this.messageData = this.messageData.message;
        }
    }

}

执行过后的数据为

这里就体现出了先进先出的逻辑,好了,下面自定义一个looper循环的定时器

 private class HandlerThread extends Thread {

        private Handler mHandler;
        private TimmerRunnable mTimmerRunnable;
        private int time = 0;

        public HandlerThread() {
            mTimmerRunnable = new TimmerRunnable();
        }

        @Override
        public void run() {
            super.run();
            //创建该线程的looper,一个线程只能创建一个looper
            Looper.prepare();
            //创建该线程的handler
            mHandler = new Handler();
            //发送消息,及消息入队
            mHandler.post(mTimmerRunnable);
            //开始循环,进入循环获取消息
            Looper.loop();
        }

        public void stopThread() {
            //退出循环,结束线程
            mHandler.getLooper().quit();
        }

        private class TimmerRunnable implements Runnable {

            @Override
            public void run() {
                //消息会送,在这里处理你的消息,这样就实现了一个消息循环了,完成定时器
                time++;
                tv_time.post(new Runnable() {
                    @Override
                    public void run() {
                        tv_time.setText("时间:" + time);
                    }
                });
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mHandler.post(mTimmerRunnable);
            }
        }

    }

先从创建开始,这里调用looper的prepare()

//先调用的这个方法
 public static void prepare() {
        prepare(true);
    }

//做空判断,如果该线程已近存在looper了就会抛出异常,所以一个线程只能有一个looper
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中
private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

Handler的创建

//没有传入参数的构造方法
 public Handler() {
        this(null, false);
    }
//调用的是该构造函数
 public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }
        //获取该线程的looper,如果该线程的looper不存在,就会抛出异常
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        //将looper创建的MessageQueue赋值到handler中
        mQueue = mLooper.mQueue;
        //消息处理接口,用于从消息队列出去后发送回主界面,以便于实现你的代码
        mCallback = callback;
        mAsynchronous = async;
    }

接下来进入Looper的循环机制

//进入循环
public static void loop() {
        //获取该线程的looper,如果为空则抛出异常
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        //获取looper中创建的消息队列
        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 (;;) {
            //获取消息队列的消息,如果消息队列返还为空,则跳出循环结束该方法
            //消息队列中,当队列中的消息问空的时候会进入死循环,这里会进入阻塞状态
            //只用手动调用queue.quit()方法才会返回空,然后结束该方法,结束线程
            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 {
                //经过一些列的数据处理,当到达这里的时候,将Message小心中的handler取出来
                //然后调用handler的dispatchMessage方法,将消息进行分发
                msg.target.dispatchMessage(msg);
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
           …………
            //释放Message,将Message数据重置,然后开始下一次消息的读取
            msg.recycleUnchecked();
        }
    }

消息队列的数据读取,出队,MessageQueue.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;
                //判断该消息和该消息保存的handler是
                //如果该消息不为空,但是该消息的handler为空,进入
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        //赋值,将该消息赋值给prevMsg,同时取出该消息内部存储的消息,
                        //赋值到msg中
                        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;
                }

                 //手动调用quit方法,结束该方法,返还空,到looper.loop层,然后结束该线程
                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose();
                    return null;
                }
……………………
        }
    }

接下来是消息分发了,handler.dispatchMessage方法

/**
     * Handle system messages here.
     */
//这里是判断调用的是handler的post方法还是sendMessage方法
    public void dispatchMessage(Message msg) {
        //取出保存在message的handler的callback方法,如果该保存了该方法,就调用回调的
        //post方法中的
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
        //如果调用的是sendMessage方法,就会调用handleMessage,需要在创建Handler中重新改方法
        //收取数据
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

这样就完成了出队的所有流程了。

接下来是入队,入队分为handler.post和handler.sendMessage两种方法入队

先讨论handler.post方法

  public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }
//创建Message
private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }
//进入到这个方法中
  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);
    }
//在这个方法中开始进入MessageQueue的入队方法
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

下面是MessageQueue中的enqueueMessage方法

boolean enqueueMessage(Message msg, long when) {
        //当message中没有保存handler的时候抛出异常
        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;
    }

至此,hander的入队出队就完成了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值