Android Handler源码解析

预备知识点:

  1. 每一个线程都可以拥有一个Handler,但前提是需要首先调用Looper.prepare()然后创 建Handler,在调用Looper.loop()。(后面分析为什么要这么做)
  2. 对ThreadLocal<T>这个类要有所了解,可以认为该类是一个以线程为key,为每一个线程保存一份共享变量的副本,从而达到各个线程对共享变量的同步问题,但也要区分与同步锁的区别。同步锁是以时间换空间的做法,对多线程访问同一变量采用排队方式,而TheadLocal是以空间换时间的做法为每一个线程保存一份变量副本,每个线程操作的是属于自己的副本变量。但是要分清改类的内部储存结构并非跟HashMap一样,但是跟ArrayMap很像。是一个链表结构,(arr[i]=key,arr[i+1]=value,i%2=0)。Looper中所使用到的。

常见用法

下面主要以下面的代码对Handler进行源码分析,这是我们在子线程中创建Handler的一个用法,除了run方法里的三个调用,还有一个重要的方法就是Looper.quit()方法后面也会有涉及。个人不建议在子线程创建Handler除非有特定的业务逻辑需要通过子线程的模式去实现,就是因为Looper.quit方法如果没有在不使用的时候进行调用会造成问题。

new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                Handler newHandler = new Handler();
                Looper.loop();
            }
        });

这个方法与我们常说的程序入口的ActivityThread类中main方法很类似,这里不再过多的解释android程序启动流程仅做对比使用

public static void main(String[] args) {
        Process.setArgV0("<pre-initialized>");
        //创建UI线程也就是主线程
        Looper.prepareMainLooper();
        //这里最终启动应用程序
        ActivityThread thread = new ActivityThread();
        thread.attach(false);
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }
        //执行消息循环
        Looper.loop();
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

先看Looper这个类
为什么要先调用Looper.prepare()?这个方法主要调用prepare(boolean quitAllowed),参数代表是否允许退出。一般子线程调用Looper.prepare参数是默认的true,所以在子线程创建完Handler时在不使用的时候应该将其退出(调用quit)而主线程在ActivityThread的main函数中调用的是prepareMainLooper(),参数参入的是false,因为不能允许主线退出。

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

这个方法首先检查ThreadLocal是否保存了一个Looper实例如果有的话就会扔出异常,如果没有的保存会保存一个新的Looper实例。ThreadLocal的set方法会以当前线程为key值保存一个对应的Looper实例。
再看Looper的构造方法

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

该方法主要初始化了一个MessageQueue即消息队列,和当前的线程对象。MessageQueue现在可以简单理解为储存消息(Message)对象的容器,后面会详细讲解MessageQueue。
再来看Handler这个类的构造方法

/**
     * Default constructor associates this handler with the {@link Looper} for the
     * current thread.
     *
     * If this thread does not have a looper, this handler won't be able to receive messages
     * so an exception is thrown.
     */
    public Handler() {
        this(null, false);
    }

特地将注释也粘贴过来,简单解释一下就是默认的构造方法和当前线程的Looper相关,如果当前的线程没有一个Looper这个Handler是不能够去接收消息的,所以会抛异常。如何让当前线程拥有一个Looper呢,正如上文解析的当然要调用Looper.prepare去为当前线程保存一个Looper。这里会进入到Handler的另一个构造方法,Callback传入为空,如果要处理消息接受这要重写Handler的handleMessage(Message msg)方法,后面一个参数传的是false,可以理解为是通过该Handler发送的消息的是否是异步,如果为异步的则不保证消息的发送顺序和到达顺序的一致性。这里传入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());
            }
        }

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

FIND_POTENTIAL_LEAKS该值默认是false,所以不去看里面的内容。再往下看mLooper=Looper.myLooper(),mLooper是handler的一个成员变量Looper。再进入Looper类去看myLooper()方法。

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

这里返回的就是调用Looper.prepare()后以当前线程为key保存的Looper对象,并赋值给Handler的成员变量。这里也解释了为什么我们经常在Actiivty里或者主线程里去直接声明一个Handler而不用去调用Looper.prepare()函数?因为再程序启动的时候已经为我们调用了Looper.prepareMainLooper()。在Activity或主线程这里返回的是UI线程的Looper,所以就不需要再次调用。再往下看如果返回的Looper为空就会抛出一个新手会遇到的异常,不能在线程里创建Handler如果没有调用Looper.prepare()方法。如果不为空则将该Looper实例的MessageQueue赋值给Handler的成员变量mQueue。
最后再回去看Looper.loop()方法做了什么工作,省略了部分非重点代码

/**
     * Run the message queue in this thread. Be sure to call
     *这里说明了在不使用时调用quit去结束loop
     * {@link #quit()} to end the loop.
     */
    public static void loop() {
          ...................
        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }
           .......................
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            msg.recycleUnchecked();
        }
    }

看到这个方法开启的一个无线for循环去调用MessageQueue.next()方法去轮询消息,这个方法是堵塞方法与Socket.accpect()一样。去看下MessageQueue.next做了什么工作。

Message next() {
        ..............
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            ..............
            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;
        }
    }

这个函数稍微长点省略了一些非重点的代码,先看第一个变量pendingIdleHandlerCount=-1;
这个值表示空闲IdleHandler的数量,这里对IdleHandler简单介绍一下这个类的作用是在没有Message消息时执行一些工作,重写这个类的public boolean queueIdle()方法会根据返回值进行不同的操作,当返回false时在执行完这个IdleHandler时会从IdleHandler数组中移除,返回true会在线程空闲时及没有消息时一直执行。再看nextPollTimeoutMillis这个变量这里先认为是一个时间值,然后往下....,又一个无限for循环。看到循环里先调用了nativePollOnce(ptr, nextPollTimeoutMillis),这是一个native方法,实际作用就是通过Native层的MessageQueue阻塞nextPollTimeoutMillis毫秒的时间。
1.如果nextPollTimeoutMillis=-1,一直阻塞不会超时。
2.如果nextPollTimeoutMillis=0,不会阻塞,立即返回。
3.如果nextPollTimeoutMillis>0,最长阻塞nextPollTimeoutMillis毫秒(超时),如果期间有程序唤醒会立即返回。
这里看代码逻辑会有这样的疑问如果消息时延时小时那么如果阻塞后不就没办法再处理其他消息了吗,上面说了在有程序唤醒的时候这个函数就会立刻返回,那么什么时候会被唤醒呢会在后面说到。继续向下走mMessage变量指向是储存消息单向列表的第一个消息。这时候看第一个if里的代码当消息不为null且消息的target为null的时候,这个target是个Handler对象后面后讲这个target什么时候会赋值。通过Handler发送的消息竟然还有target为空的消息吗,心中不免疑惑。或许消息并不是同构Handler进入消息队列呢,ok在此断点一下,在MessgeQueue中发现了这个方法

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进行赋值,并插入到消息队列当中去了,那应该就是它了。回到断点的地方继续看第一个if里的逻辑,这里有聚注释
// Stalled by a barrier. Find the next asynchronous message in the queue.
由于屏障阻塞,去消息队列中查找下一个异步消息,结合上文提到Handler构造方法中提到的异步变量为false,所以在没有调用postSyncBarrier方法时该if里的逻辑是不走的,有兴趣的可以研究一下这个屏障消息的作用。回到next方法中看第二个if里的代码,如果message不为空检查message的when属性,when属性会在发送消息的时候时候进行赋值。如果当前时间小于消息待执行的时间即延时消息的情况时计算了一下距离延时消息的时间。并重新赋值给阻塞时间变量,非延时消息或者延时消息的时间到了会进入到else这是就获得的当前的消息,并进行了对消息对象的属性进行赋值后返回消息,后面的逻辑是处理上面说到的IdleHandler这里不再多说,回到Looper.loop()函数里的queue.next()返回了Message对象后继续向下走返回消息为null时返回,调用message的target成员变量Handler的dispatchMessage(Message)方法,看下这个方法代码

 public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

判断message的callback对象,callback是个runable对象如果不为空则执行runable的run方法。
继续看判断mCallback是否为null,前面讲Handler的构造方法时默认传的null,如果不为空则调用callback的抽象方法handleMessage并返回,这里会继续往下走调用Handler的空实现方法handleMessage(Message msg),这也是在Handler在构造时没有指定callback时要重写handleMessage的原因。
到这里通过上面三行代码的介绍了Handler、Looper、MessageQueue以及ThreadLocal之间的互相引用关系和源码层面上的解析。往下是调用Handler发送消息时都做了那些工作。
从发送最普通消息的方法来看


这些方法从上往下调用源码也很简单这里就不在粘贴,主要看下中间的比较重要的部分,首先就是sendMessageDelayed到sendMessageAtTime的过渡

 public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

这里将我们平常设置的延时消息的延时时间加上现在的系统时间传给了sendMessageAtTime方法去处理了。
最后不管我们发送什么消息最终都会调用enqueueMessage

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

这里对msg对象的target进行赋值也就是我们上文中提到的要调用msg的target进行消息进行处理消息,这里在handler构造的时候指定了消息是否是异步消息,如果是异步消息这里就会调用msg.setAsynchronous(true),这里该值是false所以就直接进入到下一步,queue.enqueueMessage(msg, uptimeMillis)这里进入到MessageQueue中,省略了一部分代码

boolean enqueueMessage(Message msg, long when) {
    ...........
        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;
    }

先简单了解一下MessgaeQueue的消息储存方式,如果有兴趣可自行学习MessageQueue的消息池加深理解。这里盗图一张帮助理解


每一个Messge对象都会包含next的属性指向下一个消息,类似有向链表的结构。对照这个图片去看下MessageQueue中的消息入队代码,先看消息的when属性的赋值这里就是上面在sendMessageAtTime时传入的值。也是上面在MessageQueue.next中讲过用来判断取出消息的判断标准。这里mMessages对象可以认为是消息队列中头结点,接着这个msg跟MessageQueue实例的头结点Message进行触发时间先后的比较,如果触发时间比现有的头结点Message前,则这个新的Message作为整个MessageQueue的头结点,如果阻塞着,则立即唤醒线程处理。如果触发时间比头结点晚,则按照触发时间先后,在消息队列中间插入这个结点,接着如果需要唤醒,则调用nativeWake函数进行唤醒。上面写过在MessageQueue.next中的nativePollOnce(ptr, nextPollTimeoutMillis)方法会在唤醒的时候立即返回,这里就实现了已入列的消息在next方法中返回,然后进行消息的处理操作。
最后用一张图总结一下Handler、Looper、MessageQueue的关系

可以理解为Handler即是消息的生产者(sendMessge),产生消息放入MessageQueue中,也是消息的消费者(handleMessage).MessageQueue是消息的存储厂库并且维护Message的时序,而Looper则是不停从仓库中取消息和检查消息的机器,如果有消息且时间相符就交给Handler去处理。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容