Android Handler 机制详解(二)源码解析

在这里插入图片描述
ps:这是Handler系列的第二篇文章,让我来带大家分析一遍Android Handler机制的源码,因为技术有限,欢迎指正与补充

Handler简介

大家刚开始对于handler的认识就是切换线程更新UI,但如果你分析过Handler的源码之后,你会发现Handler机制对于整个APP的运行起到了至关重要的作用,而不只是简简单单的用于切换线程

基本用法

这个我在第一篇Handler机制中就已经很详细的说明了,大家可以去我的主页找到这一篇文章

源码分析

先来看一下Handler机制中涉及到的几个核心类:

类名 描述
Message 发送消息的实体,类中用几个字段,常用的有what、obj,用来存储信息
MessageQueue 是一种链表实现的队列的数据结构,用来管理Message,先进先出
Looper 通过无限循环来监控MessageQueue,每当有Message发送到队列时,从中取出Message来处理
Handler 处理消息
ThreadLocal 线程隔离的存储数据的类,可以在一个线程内存储数据

先对这几个类有一个大体的了解

消息入队机制

先从我们熟悉的,Handler.sengMessage(Message msg)方法看起:

public final boolean sendMessage(@NonNull Message msg) {
        return sendMessageDelayed(msg, 0);
    }
public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }
public boolean sendMessageAtTime(@NonNull 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);
    }

上面三个方法的调用链依次为

sendMessage -> sendMessageAtTime -> sendMessageAtTime

看方法名知其意,这三个方法的作用就是发送消息,方法的参数delayMillis表示消息什么时候从消息队列中被取出,时间的单位是毫秒。
可以看到sendMessage内部调用了sendMessageDelayed方法

return sendMessageDelayed(msg, 0);

也是就是通过handleMessage这个方法发送的消息是立即被处理的,延迟时间为0。
最后调用的是

enqueueMessage(queue, msg, uptimeMillis);

这个方法的作用是将消息入队,这里就接触到了Handler机制中的第一个核心类:MessageQueue,这个方法的作用,正是将发送的Message入队到MessageQueue中。

private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
            long uptimeMillis) {
        msg.target = this;  //注释1处,标重点
        msg.workSourceUid = ThreadLocalWorkSource.getUid();

        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
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.
                //注释2处
                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;
    }

注意注释一处

msg.target = this;  //注释1处

这个this当然就是我们new的handler实例,也就是说Message持有的handler的引用。划重点,以后要考。
然后接着看enqueueMessage方法,这个方法的主要逻辑就是链表的入队操作,如果仔细看插入逻辑的话你会发现不是将新的msg插入队尾,而是插入队头

                // New head, wake up the event queue if blocked.
                //注释2处
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;

注意mMessages这个成员变量,就是链表的表头,了解过数据结构的话就会知道,链表的表头就是一个链表,因为通过表头可以找到链表中的所有元素。
到这里,Handler机制中的消息入队的部分就分析完毕了。、
有没有发现忽略的一个非常重要的问题,刚才说将发送的消息入队,那这个messagequeue是从哪里获取到的?看一下我们写的代码,只有一个可能,那就是在new Handle()的时候:

	public Handler(@Nullable Callback callback, boolean async) {
        ...

		//注释1处
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
       //注释2处
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

这样就出现了Handler机制中的第二个核心类:Looper。这里的queue正是通过Looper拿到的,然后看一下Looper.myLooper();

	public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

又出现了第三个核心类,ThreadLoal,这个类的作用就是存储线程范围的数据,也就是说,通过ThreadLocal拿到了当前线程的Looper,因为Handler是在主线程new出来的,所以这里拿到的是主线程的Looper,然后再通过Looper得到MessageQueue。在这里可以分析出来,一个线程只有一个Looper,而Looper中有一个MessageQueue,所以一个线程只有一个Looper和一个MessageQueue:
在这里插入图片描述
到这里消息入队部分差不多就结束了,还有一个问题是:Looper什么时候设置给主线程的?我们接着往下看

分析

整个流程分析到这里,仅仅是发送消息,将消息入队到MessageQueue。并没有看到有哪里去调用使用handler是要覆写的handleMessage方法。到底是哪里去调用的呢?
前面说到Looper这个类,其实就是通过looper无限循环来不断询问MessageQueue是否有新消息插入,如果有的话就取出消息并处理。那是从哪里去开启的无限循环呢?很容易就会想到应用程序的入口,ActivityThread的main函数(如果你了解过Activity的启动流程,实际上是通过Zygote进程,使用反射,来调用的这个main函数)

APP能一直运行不退出,其实就是因为Looper一直在不断循环。

循环机制

public static void main(String[] args) {
        ...
        
        //注释1处
        Looper.prepareMainLooper();

        // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
        // It will be in the format "seq=114"
        long startSeq = 0;
        if (args != null) {
            for (int i = args.length - 1; i >= 0; --i) {
                if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
                    startSeq = Long.parseLong(
                            args[i].substring(PROC_START_SEQ_IDENT.length()));
                }
            }
        }
        ActivityThread thread = new ActivityThread();
        //注释2处
        thread.attach(false, startSeq);

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

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        //注释3处
        Looper.loop();
        //注释4处
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

果不其然看到了熟悉的身影,先看注释1处

Looper.prepareMainLooper();
public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }
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));
    }

就是在这里,APP启动过程中,就已经给在主线程创建了Looper对象,然后将Looper对象设置给ThreadLocal。然后看一下Looper的构造方法

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

这里new出了messagequeue对象,刚才分析入队机制时,就是通过Looper来给Message赋值,正是因为Looper初始化时就已经new出了MessageQueue。
从这里可以看到Looper和messagequeue的关系:Looper包含messagequeue,messagequeue是looper对象的一个成员变量,一个线程只有一个messagequeue。

四个类的关系

分析到这里,已经可以找到四个类的关系了:

 Looper ---->(引用) MessageQueue ---->(引用) Message ---> (引用)Handler
 //后者都是前者的一个成员变量
 //知道引用关系之后,你可以试着分析,使用Handler为什么会存在内存泄漏问题?
 //第三篇,讲解内存泄漏时会回答这个问题

到这里prepareMainLooper()方法就分析完了,这个方法一共做了哪几件事呢?

  • 创建Looper对象,存入ThreadLocal类中,线程独有
  • 创建MessageQueue对象,MessagEqueue是Looper的一个成员变量,因此MessagEqueue也是线程独有

至此,主线程的looper和messageQueue对象创建完毕,那是哪里开启循环的呢,当然是下面的注释3处的loop方法

 //注释3处
        Looper.loop();
public static void loop() {
        //这个方法之前介绍过,就是得到当前线程的looper对象
        final Looper me = myLooper();
        //如果在子线程创建过handler,而没有手动开启循环的话
        //就会报这个异常,原因显而易见,你没有在当前线程调用
        //looper.prepare()方法来创建当前线程的looper对象和messageQueue对象
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        //得到当前线程的MessageQueue对象
        final MessageQueue queue = me.mQueue;

        .
        .
        .

            
        //这里开启无限循环
        for (;;) {
            //从消息队列中拿到下一个Message
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

           .
           .
           .

            try {
                //注释1处
                //这里通过msg的target字段(眼熟吗)的dispatchMessage方法对msg进行处理
                msg.target.dispatchMessage(msg);
                if (observer != null) {
                    observer.messageDispatched(token, msg);
                }
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            }
            //将msg回收
            //这个方法内部就是将msg的每个字段都设置为null或者默认值
            //然后将这个msg放入缓存池
            //其实缓存池的大小只有1
            msg.recycleUnchecked();
        }
    }

至此,终于找到开启无限循环的地方,这个方法里面有几处很重要

  • queue.next() ,得到messageQueue的下一个message。
  • msg.target.dispatchMessage(msg); 将message交给handler处理。

其余的一些重要的地方我写有注释
Message的next()方法也很重要,虽然作用很简单,就是得到下一个消息链表中的消息,但是代码实现没有这么简单,这里我就不作分析,大家有兴趣可以自己下来看 ,我把代码贴出来,需要注意的一点是,当队列中没有消息时,next()方法会堵塞,而不是让for循环无休止的运行,消耗cpu资源。

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

消息处理机制

终于分析到消息处理了,在这个方法里可以看到handleMessage(msg);这个方法了,也就是我们使用Handler时复写的那个方法。
现在我们来看一下dispatchMessage这个方法

                //注释1处
                //这里通过msg的target字段(眼熟吗)的dispatchMessage方法对msg进行处理
                msg.target.dispatchMessage(msg);
 public void dispatchMessage(@NonNull Message msg) {
        if (msg.callback != null) {
            //第一种
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                //第二种
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            //第三种
            handleMessage(msg);
        }
    }

这就是我在Handler系列文章中第一篇重点分析的一个方法,处理消息的逻辑。

收尾

最后看main函数的注释4处

//注释4处
        throw new RuntimeException("Main thread loop unexpectedly exited");

这里抛出了异常,也就是说程序不应该运行到这里。为什么呢?想想很简单呀,已经在上面的loop方法内开启循环了,程序自然就不会运行到这里了,如果运行到这里就说明出问题了,自然要报异常。

思考

Handler机制差不多就分析完了,我分析完之后脑子里是有一个很大的疑问的,既然是靠主线程中的loop方法无限循环来维持app的运行,那为什么Android还能响应点击事件呢?不是所有逻辑都应该堵塞在循环那里了吗?
答案其实很简单,点击事件、启动Activity等等都是将各个系统事件打包成一个Message,发送到MessageQueue中,然后在loop循环内收到这条消息,去做相应的操作。具体深入还要涉及到进程间的通信,这里就不展开讲了


既然都看完了,大家点个赞再走呀

原创文章 3 获赞 3 访问量 340

猜你喜欢

转载自blog.csdn.net/qq_43747542/article/details/104104278