美文网首页程序员
android Handler运行原理总结复习

android Handler运行原理总结复习

作者: 7b3a41b7334e | 来源:发表于2018-01-03 17:03 被阅读33次

下了7.0系统的源码,打算要赶在过阴历年之前,看一些东西!不能再这么颓废下去了!
早上又复习了Handler的运行流程,看了源码后,感觉和几年前看的时候真是大不相同!

这里写图片描述

OK,不皮了,进入正题!

嗯,从ActivityThread开始吧!因为它是隐藏的,在你的IDE中是看不到的!所以在你解压系统源码后的android-7.1.0_r1\frameworks\base\core\java\android\app这个目录下,你可以找道这个文件!当然,如果你觉得系统源码有点大,自己的网速有很烂下载不方便,你可以在这个网址在线看

http://grepcode.com/file/repo1.maven.org/maven2/org.robolectric/android-all/5.0.0_r2-robolectric-1/android/app/ActivityThread.java#ActivityThread.%3Cinit%3E%28%29

在ActivityThread这个文件的末尾,你会看到一个main函数,这个就是程序的入口了。


这里写图片描述

OK,功力有限,其它的我们先不考虑,我们先来看我们能看的懂的。
看到 Looper.prepareMainLooper();//.......Looper.loop();应该知道为啥我们可以在主线程中直接使用Handler了吧!哈哈..
我们看看Looper.prepareMainLooper();做了哪些操作。

这里写图片描述

这几行英文注释很简单,大意呢就是,android系统为创建了一个当前线程的looper,作为我们的application的主looper。看到 我们熟悉的prepare(false);我们还是点进去瞅瞅

这里写图片描述

看仔细点,这是两个方法,一个带参数的,一个不带参数的,同样的都是为我们Handler提供一个Looper的,带参数的跟不带参数有什么区别呢?嗯,还是看注释,当你的参数是true的时候,我们自己创建的looper会自动调用quit(),进行注销操作,回到上面的Looper.prepareMainLooper(),它的方法体中传的false,也就是说,我们系统在创建主线程的Looper是不会自动销毁的,为什么要销毁呢?下面我们看loop()方法体的时候,你就明白了!

我们接着看prepare(boolean quitAllowed)中的代码,sThreadLocal.get(),sThreadLocal是啥玩意,跟上去看看

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

直接实例化了,还是静态的!点进去,只有这么简单的一行描述:

[图片上传失败...(image-afd390-1514970145505)]

创建一个线程局部变量!!emmm,不太明白,那我们先跳过看它怎么给参数的:

sThreadLocal.set(new Looper(quitAllowed));
这里写图片描述

嗯,大概明白了,sThreadLocal维护的是一个保存当前运行线程变量信息的HashMap!
它的get方法如下:

这里写图片描述

我们再捋一遍哈!当执行Loop的 prepare()方法的时候,会判断当前的线程信息,也就是为啥会抛出一个线程只允许创建一次prepare()的异常;

这里写图片描述

接着,如果当前线程还没prepare();,我们也就创建出了Looper的实例,并将其塞入ThreadLocal

这里写图片描述

实例化这步中,我们就为我们当前的线程创建出了MessageQueue(消息队列),并拿到当前线程的各个信息!

OK!至此,我们总算是搞清楚了Looper的实例化,是在prepare(),中完成,并且,并且,并且(重要的事情说三遍!我们也创建出了当前线程的一个消息循环器。

当前线程的消息循环器创建好了,但是我们还没有启动它!那怎么启动呢?

终于到Looper.loop();他就是启动轮询器的执行方法体了!

 /**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the 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 traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

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

我们一行一行来吧!

这里写图片描述

根据下面抛出的异常,我们应该可以知道些什么!跳进去:

这里写图片描述

阿西吧,这不就是prepare()的时候塞进去的那个Looper嘛!

final MessageQueue queue = me.mQueue;

这行不就是,Looper实例化创建的那个MessageQueue嘛

这里写图片描述

一个不可打断的死for循环!无限循环的消息队列是不是用Looper.loop();搞定了!

并且,我们是不是看到一个熟悉的方法调用?哈哈!

msg.target.dispatchMessage(msg);

是Handler的方法体吧!!!

OK,到这里,当前线程无限循环的消息队列是创建成功了!

那么问题又来了?Handler是怎么把消息存到当前线程无限循环的消息队列呢?

默认Handler实例化

这里写图片描述

this方法体:


这里写图片描述

看到执行了!!!

mLooper = Looper.myLooper();//获取当前线程Looper

mQueue = mLooper.mQueue;//获取当前线程的消息队列

OK,初始化完成,拿到当前线程的Looper了,拿到了当前线程Looper关联的消息队列mQueue.

再接着,我们发送一个最简单的消息进行处理!

这里写图片描述

嗯,接着走!

这里写图片描述

我们看一下这两行代码发生了什么!

 Message msg = Message.obtain();
        msg.what = what;

给的注释说我们 从公共池中返回一个新的消息实例,让我们避免在许多情况下分配新对象。

解释一下吧!上面多截出来的几个变量很重要,sPool是一个全局的Message的索引,这也是就注释的第一句话的意思,当前对象中如果存在Message对象,我们不需要创建新的实例对象,然后会将当前Message的各个信息补充完整,它的next也是一个Message对象,我们会将当前存在的Message对象生成一个新的Message节点,就酱!那如果没有的话,则返回一个新的new Message(),我们面试常问到的Handler绑定,也就是target的赋值,还没到,大家不要急!

回到Handler,我们接着往下走!

这里写图片描述

没有什么有用的信息,接着往下走!

这里写图片描述

们初始化Handler的时候mQueue,被赋给别人了!

接着走!

这里写图片描述

来了,此时将Handler附在Message上了!!!!

接着看return queue.enqueueMessage(msg, uptimeMillis);
从字面理解,是将Message和执行的时间点存入了MessageQueue中!我们也跟进去看看!

    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插入MessageQueue中,主要的几行代码,我标出来了!哈哈

这里写图片描述

其实没什么可说的这个方法,主要是按照when(执行时间点)来插入队列中!当没有消息可插入的时候,就会跳出这个循环!

总结:
实例化Handler(拿到当前线程的Looper,MessageQueue),发送消息(将生成的携带Handler标记的Message插入MessageQueue),完成了消息的生成存储流程!之后的Looper.loop();方法就将开无限循环处理消息了!

这篇写的有些简陋,感觉主要是整个流程框架有点庞大复杂,整体的把握还是有些不足!这是我这边的复习总结!个人感觉吧,大家还是自己看看源码比较好!哈哈!话说回来,面试的时候这个问道的概率很大很大!掌握其中的各个关键点和整体的架构把握很重要!

OK,据扯到这了!

每天进步一点点,时间会让你成为巨人!加油!

相关文章

网友评论

    本文标题:android Handler运行原理总结复习

    本文链接:https://www.haomeiwen.com/subject/khxknxtx.html