美文网首页
Handler源码阅读

Handler源码阅读

作者: NC丶脑补东 | 来源:发表于2020-07-16 22:38 被阅读0次

    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整个流程就走完了。

    相关文章

      网友评论

          本文标题:Handler源码阅读

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