Handler在Android中的那些事

前言

在Android开发过程中,使用Handler已经是一件很平常的事了。比如经常遇到在子线程中如何更新UI,AsyncTask的实现,IntentService是如何实现在子线程工作的,当碰到这些问题的时候,一下子就想到是Handler通过发送消息来实现的。那么Handler是如何实现消息发送机制的呢?

Handler工作流程

说到Handler,就要提起MessageQueue,Looper,Message。通常做法是在线程A中通过Handler发送一条消息Message到消息队列MessageQueue,而Looper会在MessageQueue有消息到达时取出消息Message并且发送给Handler.dispatchMessage处理。它们之间的关系如下图:


handler流程.png

new Handler()

public Handler(@Nullable Callback callback, boolean async) {
        // Looper.myLooper() =>  sThreadLocal.get()
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

通过创建Handler的源码可以发现,会先取Looper.myLooper(),如果mLooper为空会抛出异常,看异常错误可以得知是在当前线程中没有调用Looper.prepare()。那么为什么我们在主线程直接new Handler不会抛出异常呢?是因为zygote启动应用进程的时候,在ActivityThread.main()中已经给主线程创建了Looper,如下代码所示:

public static void main(String[] args) {
        // ...省略其他代码
        // 最终也是执行Looper.prepare()
        Looper.prepareMainLooper();
        // ...省略其他代码
        //获取的是H类的实例,H类也是继承Handler
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        //开启死循环
        Looper.loop();
        //一旦 Looper.loop() 执行结束,那么就抛出异常了
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

Looper.prepare()

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

首先会执行sThreadLocal.get(),如果不为空则抛出异常,这里也解释了为什么一个线程只能创建一个Looper的问题;如果为空,则创建一个Looper设置给sThreadLocal,这样就实现了Looper和ThreadLocal的双向绑定。使用ThreadLocal就能达到线程间数据互不干扰的效果,这样的设计也能避免线程间共享的数据不会错乱。接下来看下new Looper(quitAllowed)做了什么

new Looper(quitAllowed)

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

私有构造函数也说明在创建Looper的时候是不允许通过new来创建的,只能通过
Looper.prepare()来创建。在创建Looper的时候也创建了当前线程的MessageQueue。接下来就是开始消息循环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;
        // ...省略代码
        for (;;) {
            //从MessageQueue中取消息,没有消息会阻塞,nativePollOnce
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }
            // ...省略代码
            try {
                // msg.target == handler
                msg.target.dispatchMessage(msg);
            } catch (Exception exception) {
                if (observer != null) {
                    observer.dispatchingThrewException(token, msg, exception);
                }
                throw exception;
            } finally {
                ThreadLocalWorkSource.restore(origWorkSource);
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
           // ...省略代码
           // 这里是回收msg的逻辑,提高性能和内存
            msg.recycleUnchecked();
        }
    }

首先还是判断当前线程是否有Looper,如果没有抛出异常,否则获取当前MessageQueue,通过死循环来调用MessageQueue的next方法获取消息,如果没有消息则会阻塞,阻塞是在MessageQueue.next方法中实现,后面会分析。当没有获取到消息的会直接退出循环,这也是退出Looper的原因,而触发的原因是调用了Looper.quit()间接的调用MessageQueue.quit()实现的。如果获取到了消息,则调用msg.target.dispatchMessage(msg)来处理消息,在MessageQueue.enqueueMessage给Message.target赋值为了当前的Handler,这样就能执行到Handler.dispatchMessage中去了。所以也可以得到消息处理是在创建Handler所使用的Looper的线程中,从而达到线程切换的目的。

MessageQueue的生产者enqueueMessage()

当我们在Handler中发送消息时,最终都会调用MessageQueue.enqueueMessage方法,使得消息入队。

boolean enqueueMessage(Message msg, long when) {
        //判断msg必须得有Handler
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        //判断当前msg还没有被处理过
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }
        //MessageQueue是生产者消费者,在next方法中同样有synchronized (this) ,这里是生产者
        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) {
                  //如果msg是第一条消息或者执行时间小于当前第一条消息则放在链表第一条,并且将needWake置为mBlocked,mBlocked是在next中赋值的,下面分析
                // 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;
            }
            // 如果需要唤醒,则调用nativeWake来唤醒被nativePollOnce挂起的线程
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

MessageQueue是一种生产者消费者模式,enqueueMessage方法内部用synchronized (this)获取当前对象的锁,将msg按照执行的时间顺序添加到MessageQueue中,如果当前线程是被挂起的状态,还要通过nativeWake来唤醒线程。

MessageQueue的消费者next()

从前面我们可以知道,在Looper.loop()开启死循环后,就在等待MessageQueue.next()返回可以处理的消息。

Message next() {
       //如果消息队列已经退出了,则就返回null,那么在looper.loop()就会得null的message,从而退出
        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();
            }
            //挂起当前线程,native中通过epoll_wait()来阻塞的
            nativePollOnce(ptr, nextPollTimeoutMillis);
            //这里的 synchronized (this)是消费者
            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) {
                    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;
                }

                //mQuitting是quit()函数赋值的,如果mQuitting为true表示消息队列要退出了,返回msg=null;
                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();
                }
                //如果msg==null时,nextPollTimeoutMillis = -1,之所以nextPollTimeoutMillis没有执行循环末尾的重新赋值为0,就是因为这里需要执行空闲时的IdleHandler个数为0,continue后,执行nativePollOnce进入了阻塞
                if (pendingIdleHandlerCount <= 0) {
                    //阻塞挂起,并且赋值 mBlocked为true,那么下次有消息时,在enqueueMessage方法中就要唤醒被挂起的线程
                    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;
        }
    }

首先判断消息队列是否退出,如果退出则直接返回null给Looper退出,没有退出则继续执行。nativePollOnce(ptr, nextPollTimeoutMillis)是通过nextPollTimeoutMillis来说明当前是否需要挂起和挂起时间。当nextPollTimeoutMillis==-1时表示一直阻塞不会超时;当nextPollTimeoutMillis==0时表示不会阻塞立即返回;当nextPollTimeoutMillis>0时表示当前线程最长需要挂起多长时间。局部变量nextPollTimeoutMillis初始值为0,进入同步代码块后,如果获取到当前msg为空,则nextPollTimeoutMillis=-1,我们可以发现在循环末尾会重新给nextPollTimeoutMillis赋值为0,那么nativePollOnce就不会阻塞挂起了。但其实还要注意到pendingIdleHandlerCount这个空闲时可处理的IdleHandler个数,如果没有添加的IdleHandler那么就是0,所以这里执行continue后,继续for循环nativePollOnce(ptr,-1)阻塞挂起了。如果msg!=null的时候,就会比较当前时间是否小于消息执行的时间,如果小于的话,线程就会进入最长需要挂起的时间;如果大于就返回当前的msg。

执行工作的Handler.dispatchMessage()

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

如果msg的callback不为空,就执行msg的callback.run(),如果调用Handler.post系列的方法。如果msg.callback为空,则判断Callback是否为空,不为空就执行mCallback的handleMessage方法,最后才执行Handler的handleMessage,这也是平常用的最多的。

Message.recycleUnchecked()

在Looper.loop()执行完msg.target.dispatchMessage(msg)后,还会执行msg.recycleUnchecked()。

void recycleUnchecked() {
        // ...省略初始化代码
        synchronized (sPoolSync) {
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }

如果当前sPoolSize还没有到MAX_POOL_SIZE(50个),就把当前的msg放入队列的头部。这种方式相比于new Message(),可以提升内存的使用率,如果一直new实例,则在内存空间上就会出现很多碎片,也可能造成频繁gc。所以推荐使用Handler.obtainMessage()

public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

Looper.quit()和quitSafely()

如果在子线程中创建了Looper,就可以通过quit或者quitSafely来退出消息队列。这样可以停止线程的Looper.loop(),并且不会有内存泄漏问题。quit和quitSafely的区别就是,quit会移除所有的消息,quitSafely只会移除还没处理的消息。
至此,就明白Android中Handler的工作原理,再去看AsyncTask,IntentService,HandlerThread就比较容易理解了。

总结:

1.使用handler之前必须先调用Looper.prepare来创建Looper,否则会报异常。所以在子线程需要执行Looper.prepare(),通过Looper.myLooper()来获取当前线程的Looper,一个线程只有一个Looper和MessageQueue。主线程不用执行是因为在ActivityThread.main中已经执行了Looper.prepareMainLooper()
2.处理Handler消息的线程是Looper所在的线程,所以在IntentService中虽然在主线程中创建的ServiceHandler,但是Looper是HandlerThread中的子线程Looper,所以在处理消息onHandleIntent()时是在子线程处理的,可以做耗时操作
3.MessageQueue消息队列是生产者消费者模式,在添加消息是按照执行的时间when顺序插入到链表中去的。
4.Looper.loop()死循环不会导致ANR,因为在没有消息时会阻塞并且挂起当前线程,而不会超时,只有超时没有响应才会导致ANR。当MessageQueue没有消息时,会调用nativePollOnce导致线程阻塞,直到有消息到达时调用nativeWake来唤醒线程。
5.如果需要退出Looper,可以调用Looper.quit()或者quitSafely(),但是主线程是不能退出的,因为主线程在mQuitAllowed为false,调用quit会直接异常。
6.在使用Message时,最好使用Handler.obtainMessage来取代new Message()
7.Handler引起内存泄漏的原因,在发送消息的时候msg会引用Hanlder作为target成员变量的值。在子线程中没有释放Looper对象。

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

推荐阅读更多精彩内容