您当前的位置: 首页 >  android

Kevin-Dev

暂无认证

  • 0浏览

    0关注

    544博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【Android -- 技术周刊】第 008 期

Kevin-Dev 发布时间:2022-05-19 08:15:00 ,浏览量:0

在这里插入图片描述

老司机们都知道,Android的线程间通信就靠Handler、Looper、Message、MessageQueue这四个麻瓜兄弟了,那么,他们是怎么运作的呢?下面做一个基于主要源代码的大学生水平的分析。 原文链接

Looper

在 Looper 中,维持一个Thread对象以及MessageQueue,通过Looper的构造函数我们可以知道:

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);//传入的参数代表这个Queue是否能够被退出
        mThread = Thread.currentThread();
    }

Looper在构造函数里干了两件事情:

  1. 将线程对象指向了创建Looper的线程
  2. 创建了一个新的MessageQueue

分析完构造函数之后,接下来我们主要分析两个方法:

  1. looper.loop()
  2. looper.prepare()
looper.loop()
 public static void loop() {
        final Looper me = myLooper();//获得当前线程绑定的Looper
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;//获得与Looper绑定的MessageQueue

        // 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();
        
        //进入死循环,不断地去取对象,分发对象到Handler中消费
        for (;;) {
            Message msg = queue.next(); // 不断的取下一个Message对象,在这里可能会造成堵塞。
            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
            Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }
            
            //在这里,开始分发Message了
            //至于这个target是神马?什么时候被赋值的? 
            //我们一会分析Handler的时候就会讲到
            msg.target.dispatchMessage(msg);

            if (logging != null) {
                logging.println("            
关注
打赏
1658837700
查看更多评论
0.0458s