六、消息机制(Handler)

Handler

通常情况下,handler就是用来更新UI的。

1.消息机制的模型

消息机制主要包含:MessageQueue,Handler和Looper这三大部分,以及Meesage

  • Message:需要传递的消息,可以传递数据。
  • MessageQueue:消息队列,但是它的内部实现,并不是用的队列,实际上是通过一个单链表的数据结构来维护消息列表,因为单链表在插入和删除有优势。主要功能向消息池投递消息(MessageQueue.enqueueMessage)和取走消息池的消息(MessageQueue.next)。
  • Handler:消息辅助类,主要功能向消息池发送各种消息(Handler.sendMessage)和处理相应的消息事件(Handler.handlMessage);
  • Looper:不断循环执行(Looper.loop),从MessageQueue中读取消息,按分发机制将消息分发给目标处理者。
2.消息机制的架构

消息机制的运行流程:在子线程执行完耗时操作,当Handler发送消息时,将会调用MessageQueue.enqueueMessage,向消息队列中添加消息。当通过Looper.loop开启循环后,会不断从线程池中读取消息,即调用MessageQueue.next方法,然后调用目标Handler(即发送该消息的Handler)的dispatchMessage方法传递消息,然后返回到Handler所在的线程,目标Handler收到消息,调用handleMessage方法,接收消息,处理消息。


image.png
3.消息机制源码解析
    1. Looper
      要想使用消息机制,首先要创建一个Looper。
      初始化Looper
      无参的情况下,默认调用prepare(true),表示的是这个Looper可以退出,而对于false的情况,表示当前Looper不能退出。
    public static void prepare() {
        prepare(true);
    }

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

不能重复创建Looper,只能创建一个。创建Looper,并保存在ThreadLocal。其中ThreadLocal是线程本地存储区(Thread Local Storage,简称TLS),每个线程都有自己的私有的本地存储区域,不同的线程不能访问其他线程的TLS。
开启Looper

public static void loop() {
 final Looper me = myLooper();//获取TLS存储中的Looper对象。
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;//获取Looper对象中的消息队列
        // 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();
        for (;;) { //进入looper的主循环方法
            Message msg = queue.next(); // 可能会阻塞,因为next()方法会无线循环
            if (msg == null) { //消息为空,则退出循环
                // No message indicates that the message queue is quitting.
                return;
            }
          ... 
          msg.target.dispatchMessage(msg);//获取msg的目标Handler然后用于分发Messae。
         }
}

loop(),进入循环模式,不断进行下面的操作,直到消息为空时退出循环:

  1. 读取MessageQueue的下一条Message,把Message分发给对应的Handler。
  2. 当next(),读取下一条消息,队列中已经没有消息时候,next()会无限循环,产生阻塞。等待MessageQueue中加入消息,然后重新唤醒。
  3. 主线程中不需要自己创建Looper,这是由于在程序启动的时候,系统已经自动调用了Looper.prepare()方法。ActivityThread中的main()方法有调用。
    1. Handler
    public Handler(@Nullable Callback callback, boolean async) {
      // 需要先执行Looper.prepare(),才能获取Looper对象。
       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;//消息队列,来自Looper对象
        mCallback = callback;//回调方法
        mAsynchronous = async;//设置消息是否未异步处理
    }

对于handler的无参构造方法,默认采用当前线程TSL中的Looper对象,并且回调方法为null,且消息为同步处理。只要执行Looper.prepare()方法,那么便可以获取有效的Looper对象。
handler的发送消息的方法有几种,无论是post()还是send(),但是终究还是调用了sendMessageAtTime()方法
在子线程中,使用runOnUiThread,内部调用的是handler的post()方法,最终调用的是sendMessageAtTime()方法。

   public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
    }

sendMessageAtTime()代码

  public boolean sendMessageAtTime(@NonNull Message msg, long uptimeMillis) {
        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);
    }
   private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
            long uptimeMillis) {
        msg.target = this;
        msg.workSourceUid = ThreadLocalWorkSource.getUid();

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

主要就是调用enqueueMessage方法。往消息队列里面插入一条数据。
MessageQueue 中enqueueMessage方法

  boolean enqueueMessage(Message msg, long when) {
        //每一个Message必须有一个Target。
        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) {
            if (mQuitting) { //正在退出,回收msg,加入到消息池。
                msg.recycle();
                return false;
            }
            msg.markInUse();
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
            if (p == null || when == 0 || when < p.when) {
                // p为null(代表MessageQueue没有消息) 或者msg的触发时间是队列内最早的,则加入该分支。
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {

//将消息按时间顺序插入到MessageQueue。通常不需要唤醒时间队列,除非消息头部存在阻塞,并且同时Message是队列中最早的异步消息。  
                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;
    }

MessageQueue是按照Message触发时间的先后排序排列的,队头的消息将是最早触发的,当有消息需要加入消息队列时,会从队列头开始遍历,直到找到消息应该插入的合适位置,保证所有消息的时间顺序。

    1. 获取消息
      当发送了消息后,在MessageQueue维护了消息队列,然后在Looper中通过loop()方法,不停的获取消息。其中最重要的就是调用了queue.next()方法来获取下一条消息。
      MessageQueue.next()具体实现流程
  @UnsupportedAppUsage
   Message next() {
       final long ptr = mPtr;
       if (ptr == 0) { //当前循环已经退出,则直接返回
           return null;
       }
       int pendingIdleHandlerCount = -1; // 循环迭代的首次= -1
       int nextPollTimeoutMillis = 0;
       for (;;) {
           if (nextPollTimeoutMillis != 0) {
               Binder.flushPendingCommands();
           }
         //阻塞操作,当等待nextPollTimeoutMillis时长,或者消息队列被唤醒是都会返回。
           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) {
                   // 当消息Handler为空时, 查询MessageQueue中的下一条异步消息msg, 为空则退出循环。
                   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 {  
                       mBlocked = false;
                       if (prevMsg != null) {
                           prevMsg.next = msg.next;
                       } else {
                           mMessages = msg.next;
                       }
                       msg.next = null;
                 //设置消息的使用状态, 即flags |= FLAG_IN_USE
                       msg.markInUse();
              // 获取一条消息,并返回。
                       return msg;
                   }
               } else {
                   //没有消息
                   nextPollTimeoutMillis = -1;
               }
               // 消息正在退出,返回null
               if (mQuitting) {
                   dispose();
                   return null;
               }
          }
   }

nativePollOnce是阻塞操作,其中nextPollTimeoutMillis表示下一个消息到来前,还需要等待的时长,当nextPollTimeoutMillis = -1时,表示消息队列中没有消息,会一直等待下去。
可以看出next(),方法根据消息的触发时间,获取下一条需要执行的消息,队列中消息为空,则会进行阻塞操作。

    1. 分发消息
      在loop()中,获取到下一条消息后,执行 msg.target.dispatchMessage(msg),来分发消息到目标Handler对象。msg.target实际上Handler的引用,所以该方法实际调用的是Handler的dispatchMessage()方法。
      dispatchMessage()方法
    public void dispatchMessage(@NonNull Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }
 private static void handleCallback(Message message) {
        message.callback.run();
    }

分发消息流程:
当message的msg.callback不为空时,则回调方法msg.callback.run();
当handler的mCallback不为空时,则回调mCallback.handleMessage(msg);
最后调用Handler自身的回调方法handleMessage(),默认为空实现。需要开发者重写。
优先级:
message.callback.run() > mCallback.handleMessage(msg) > handleMessage(msg)

4.消息机制总结

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

推荐阅读更多精彩内容