从源码角度彻底捋一遍Handler内部逻辑

Handler内部逻辑彻底捋一遍

一直看Handler的逻辑都是半自己看半看博客,今天自己从最开始,抛开以前的理解,从最开始的使用方式一步一步跟源码,从远吗分析Handler在发出消息之后如何一步一步调回自己来处理,我们从最开始的Hander handler = new Hander(); handler.sendMessage();这两个方法跟下去。

Handler handler = new Handler();

public Handler() {
    this(null, false);
}

public Handler(Callback callback, boolean async) {
    /***/

    //初始化当前handler的looper
    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;
}

Looper.myLooper()

//ThreadLocal变量是线程自己独享的内存空间,不与其他线程共享数据,这里将Looper与线程绑定,每个线程都有自己的Looper
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

public static @Nullable Looper myLooper() {
    //这里如果没有将Looper设置进sThreadLocal的话,sThreadLocal.get()拿到的就是null
    return sThreadLocal.get();
}

将Looper设置进sThreadLocal的方法就是Looper.prepare();

private static void prepare(boolean quitAllowed) {
    //如果已经prepare过了会抛异常
    if (sThreadLocal.get() != null) {
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    //设置Looper到sThreadLocal
    sThreadLocal.set(new Looper(quitAllowed));
}

所以我们再子线程使用Handler的话需要自己手动调用Looper.prepare();而主线程中的Looper在ActivityThread中已经初始化了

这里看下Looper的构造函数,看看为什么一定需要先初始化这个Looper,这里有什么东西是Handler机制中必不可少的。

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

这里初始化了一个MessageQueue,也就是消息队列,所以消息队列其实是在Looper里面的,还有拿到了当前的线程Thread,有什么用我们接下去看Handler.sendMessage();

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

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    //将当前Handler设置到了Message消息内部
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

最后调用到了MessageQueue的enqueueMessage中。

MessageQueue.enqueueMessage();

boolean enqueueMessage(Message msg, long when) {
     /***/

    synchronized (this) {
        /***/

        msg.markInUse();
        msg.when = when;
        Message p = mMessages;
        boolean needWake;
        //将message插入到queue中一个合适的未知
        if (p == null || when == 0 || when < p.when) {
                //将当前msg插入到queue中最开头的位置
            // New head, wake up the event queue if blocked.
            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; // invariant: p == prev.next
            prev.next = msg;
        }

        if (needWake) {
            nativeWake(mPtr);
        }
    }
    return true;
}

这里用到了几个MessageQueue的成员变量:

mMessages 当前消息队列中最前面的消息
mBlocked 是否阻塞当前队列
mPtr 用于native代码,进行一些native唤醒操作

我们可以看到在MessageQueue.enqueueMessage()方法中做的只是将msg插入到MessageQueue中。那么这个消息是如何送到我们handler中的handlerMessage等方法中处理的呢,我们知道在主线程中使用Handler只需要调用new Handler()无参构造方法就可以使用,前面也说过这是因为主线程Looper早已经初始化好了,这个在ActivityThread中的main方法可以看到:

    public static void main(String[] args) {
    /***/

        Looper.prepareMainLooper();

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        Looper.loop();

    /***/
    }

    public static void prepareMainLooper() {
    prepare(false);
    synchronized (Looper.class) {
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already been prepared.");
        }
        sMainLooper = myLooper();
    }
}

我们可以看到在主线程中调用了Looper.prepareMainLooper()方法,而prepareMainLooper方法内部也是调用的prepare方法,在调用prepare方法以后还调用了一个Looper.loop()方法,我们可以看看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;
        }

        final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

        final long traceTag = me.mTraceTag;

        final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        final long end;
        try {
                //在这里将消息发送回去给到msg.target处理,msg.target在之前已经被赋值给了当前的Handler
            msg.target.dispatchMessage(msg);
            end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }

        msg.recycleUnchecked();
    }
}

在loop方法中拿到了当前Looper类并获取到了内部的MessageQueue队列,然后通过一个for死循环从内部轮询获取到message,queue.next()方法是一个阻塞方法,如果消息队列没有消息的话将会一直阻塞在这里知道下一个消息通过之前的MessageQueue.enqueueMessage()方法插入到队列中,然后在通过msg.target.dispatchMessage(msg)将消息发送回去给到Handler,于是就完成了一个消息从发送接受的全过程。所以我们在子线程中使用Handler除了Handler.prepare()方法还需要调用Looper.loop()方法。
而最后代码也就回到了Looper.loop()方法中,线程也就切换回了loop()方法所在的线程。

关于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;
            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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值