Handler源码阅读

Handler源码的阅读主要围绕Lopper这个对象和这个对象中的Message队列这两个东西。

Message

在Android的Handler中,会通过在子线程发送Message消息回到主线程并将数据更新到主线程的UI。而这个过程首先从sendMessage这个方法入手。

  public final boolean sendMessage(@NonNull Message msg) {
          return sendMessageDelayed(msg, 0);
  }

这里会调用 sendMessageDelayed 方法,这个方法会带有一个延时发送的性质。

   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) {
        //Handler 的消息队列
        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);
    }

跟踪到 sendMessageAtTime 这个方法可以看到 enqueueMessage 这个方法并返回一个布尔值。

进入到这个方法里

 private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
            long uptimeMillis) {
        //将Handler自身放入Message对象中
        msg.target = this;
        msg.workSourceUid = ThreadLocalWorkSource.getUid();

        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
  }

这里调用了queue的enqueueMessage方法,继续追踪。

boolean enqueueMessage(Message msg, long when) {
        //这里的target是发送消息Handler自身
        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) {
         
            //部分代码省略...

            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;
                    }
                }
                //将消息插入链表中,并将next指向下一个message
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }

           //部分代码省略...

        }
        return true;
    }

可以看到,这里主要就是将Message对象放入到队列之中,而之前那个延时发送,在这里就会通过判断 when 来插入到队列之中,改变消息队列发送顺序。这也是为什么队列是一个链表结构的原因。

Looper

上面的 Message 队列只看到了将消息放入队列之中,并没有看到 handlerMessage() 方法的调用,而 handlerMessage 则跟Lopper有关。

之前在项目中,用到 Handler 时,有想到过能不能通过 Handler 方式来让子线程发送消息给主线程。而研究的结果是可以的,但是要调用 Looper.prepareLooper() 和 Looper.loop()这两个方法。而这两个方法就是Handler发送消息回调handlerMessage()的关键。

在 ActvitiyThread 类的main()方法中,会调用 Looper.prepareMainLooper()Looper.loop() 这两个方法。

 public static void main(String[] args) {

        //...代码省略      

        //生成主线程的looper
        Looper.prepareMainLooper();

        //...代码省略     
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

Looper.prepareMainLooper()

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

上面这段代码可以看到调用了 prepare(false)myLooper() 来那个个方法,下面那个方法看名字就能知道是获取了 Looper 对象。

先看prepare(false) 这个方法。

    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        //生成looper对象,并放入主线程的ThreadLocal对象中
        //此处的set方法就是ThreadLocal获取当前线程并保存和将对象保存到ThreadLocal中的方式
        //set方法中会通过当前线程去ThreadLocalMap中拿到线程的数据信息
        sThreadLocal.set(new Looper(quitAllowed));
    }

可以看到 sThreadLocal.set(new Looper(quitAllowed)) 这段,这段代码做了两件事情:

  1. 生成 Looper 对象,并放入主线程的 ThreadLocal 对象中

  2. ThreadLocal获取当前线程并将线程和 Lopper 对象保存到 ThreadLocalMap 中

这里的set方法,会将生成的 Looper 对象放入到 ThreadLocalMap 中,这个Map的Key为当前的线程对象,Value 为 Lopper 对象。

而myLooper()方法就是从ThreadLocalMap中获取Looper对象。

   public static @Nullable Looper myLooper() {
        //通过ThreadLocal获取到当前线程的looper对象
        //如果是主线程,则在ActivityThread的main()方法中已经声明了looper对象的生成
        return sThreadLocal.get();
    }

Looper.loop();

接下来看 Looper.loop() 方法。

 public static void loop() {
        //拿到当前线程的looper对象
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        //获取looper对象中保存的队列
        final MessageQueue queue = me.mQueue;

       //...省略代码

        //无线循环队列
        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            //...省略代码
          
            try {
                //调用Handler的dispatchMessage方法
                msg.target.dispatchMessage(msg);
                if (observer != null) {
                    observer.messageDispatched(token, msg);
                }
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } catch (Exception exception) {
                if (observer != null) {
                    observer.dispatchingThrewException(token, msg, exception);
                }
                throw exception;
            } finally {
                ThreadLocalWorkSource.restore(origWorkSource);
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
          
            //...省略代码

            //回收此次的Message对象,之后申请Message对象时可以重复使用
            msg.recycleUnchecked();
        }
    }

而上面这段代码就能看到通过 myLooper() 方法拿到 Looper 对象,并且通过 Looper 对象拿到队列。然后无线循环从这个对象拿出消息,最后调用 Handler 的 dispatchMessage(msg) 方法。

这个在主线程无线循环不会卡死手机的原因就在它是在 ActvitiyThread 类的main()方法中,并且是最后执行的一个方法。这样其实也可以理解为正因为这个无线循环,我们的APP才会一直执行,直到用户关闭APP。

 /**
     * Handle system messages here.
     */
    public void dispatchMessage(@NonNull Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

而dispatchMessage方法里就会调用handleMessage,也就是回调Handler handleMessage方法。

这样,Handler整个流程就走完了。

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

推荐阅读更多精彩内容

  • 首先handler的分发过程主要涉及到四个类:Handler(分发器),Message(消息),Looper(轮询...
    lucasDev阅读 180评论 0 0
  • handler工作流程图 参考DonKingLiang的文章图片老是上传失败,不知道为啥,本地和网络的都不可以。。...
    etrnel阅读 238评论 0 0
  • Handler是Android中最常用线程通讯方式之一、也是非UI线程与线程通讯的主要方式。 你可能有个疑问基础a...
    CrazyDevp阅读 136评论 0 0
  • 一、提出问题 面试时常被问到的问题: 简述 Android 消息机制 Android 中 Handler,Loop...
    崽子猪阅读 1,485评论 0 10
  • 每日一题: Handler源码 深入了解handler 面试率: ★★★☆☆ 面试技巧与建议 handler作为A...
    林锐波阅读 511评论 0 1