【源码分析】Android消息机制:Handler发出的消息经历了怎样的流程

本文深入解析Android中的消息机制,从Looper、Handler、MessageQueue的基本概念出发,详细阐述了消息发送、接收及处理的全过程,帮助读者理解主线程Looper的工作原理。

消息机制在Android中很重要,网上也有很多优质的分析文章,但很多人看了以后可能还是一头雾水,看着眼花缭乱的源码懵圈。

本文不会介绍Looper、Handler、MessageQueue是什么,请读者自行了解相关基础知识。

在这里笔者试图通过尽可能少的源码,分析Handler发出的消息经历了怎样的流程Looper、Handler、MessageQueue又是如何紧密合作实现这一流程,以便大家快速抓住重点。

开始分析源码之前,请大家先思考以下两点疑问:
1.一个Handler发出的消息要放入哪一个MessageQueue,又被哪一个Looper所取出?
2. Looper取出的消息给哪一个Handler处理?
解决了这两个疑问,也就明白了Handler发出的消息经历了怎样的流程

带Looper的线程

Looper源码的注释中有这么一个示例:

  *  class LooperThread extends Thread {
  *      public Handler mHandler;
  *
  *      public void run() {
  *          Looper.prepare();
  *
  *          mHandler = new Handler() {
  *              public void handleMessage(Message msg) {
  *                  // process incoming messages here
  *              }
  *          };
  *
  *          Looper.loop();
  *      }
  *  }

这个示例展示了在一个线程中使用Looper的正确姿势:
1. 调用Looper.prepare();
2. 创建mHandler
3. 调用Looper.loop();
4. 使用mHandler

下面我们来逐步看一下整个流程:

Looper.prepare()

Looper类中相关代码如下:

    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    final MessageQueue mQueue;

      /** Initialize the current thread as a looper.
      * This gives you a chance to create handlers that then reference
      * this looper, before actually starting the loop. Be sure to call
      * {@link #loop()} after calling this method, and end it by calling
      * {@link #quit()}.
      */
    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));
    }

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

第15-17行的判断,决定了一个线程只能有一个Looper和一个MessageQueue
第22行给成员变量mQueue赋值。
第18行将新生成的Looper对象保存到静态ThreadLocal对象sThreadLocal中。

简单地说,调用Looper.prepare()后,为一个线程生成了一个Looper对象和一个MessageQueue对象,并将它们保存了起来以便日后使用。

创建mHandler

创建mHandler的相关代码如下:

    public Handler() {
        this(null, false);
    }

    public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }

        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

    类Looper:
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

第15行获取了之前sThreadLocal中保存的Looper对象。
第18行的错误如果你看到过,说明你曾经在没有调用Looper.prepare()的线程中创建Handler,结果只能是失败。
第20行将之前Looper对象中保存的成员变量mQueue保存到正在创建的Handler中。

看到这里,我们就明白了为什么一定要先调用Looper.prepare()才能创建Handler,在创建Handler时又使用了之前调用Looper.prepare()时保存的哪些变量。

使用mHandler

一般使用Handler有两种方式:
1. post一个Runnable
2. send一条Message
每种方式又可以设置延迟时间,各有几种实现方法。
我们看一下入参最少的post方法,相关方法如下:

    public final boolean post(Runnable r){
        return sendMessageDelayed(getPostMessage(r), 0);
    }

    private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }

    public final boolean sendMessageDelayed(Message msg, long delayMillis){
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

    public boolean sendMessageAtTime(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(MessageQueue queue, Message msg, long uptimeMillis) {
         msg.target = this;
         if (mAsynchronous) {
             msg.setAsynchronous(true);
         }
         return queue.enqueueMessage(msg, uptimeMillis);
    }

第5-9行,方法getPostMessage()Runnable转换成了Message,其中Runnable保存在Message的成员变量callback中。
第19行将之前创建mHandler时赋值的成员变量mQueue传给enqueueMessage()方法。
第30行将mHandler自身保存在Message的成员变量target中。
第34行调用MessageQueueenqueueMessage()方法,将这条msg插入到消息队列中,至于enqueueMessage()方法是如何插入的,不在本文讨论范围之内。

可见post一个Runnable也会转为send一条Message,所有的post和send相关方法最终都会进入到HandlerenqueueMessage中,在这个方法中调用MessageQueueenqueueMessage()方法,插入一条消息到消息队列。

Message的处理

我们都知道,Looper会开启无限循环,取出MessageQueue中的Message进行处理,具体的方法为Looperloop()

    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;

        // 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 (;;) {
            Message msg = queue.next(); // might block
            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
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }

            // Make sure that during the course of dispatching the
            // identity of the thread wasn't corrupted.
            final long newIdent = Binder.clearCallingIdentity();
            if (ident != newIdent) {
                Log.wtf(TAG, "Thread identity changed from 0x"
                        + Long.toHexString(ident) + " to 0x"
                        + Long.toHexString(newIdent) + " while dispatching to "
                        + msg.target.getClass().getName() + " "
                        + msg.callback + " what=" + msg.what);
            }

            msg.recycleUnchecked();
        }
    }

第14行为循环开始的位置,此处将阻塞直至取出下一条消息。
第32行就是处理消息的位置,根据之前的分析,msg的成员变量target就是一个Handler,这个Handler对象是消息插入队列时赋值的,说明消息交给了HandlerdispatchMessage()方法,我们看一下这个方法:

    public void dispatchMessage(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();
    }

    public interface Callback {
        public boolean handleMessage(Message msg);
    }

    /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
    }

第2行的msg.callback就是之前post()方法传入的Runnable对象,也就是说如果是用post一个Runnable的形式发出的消息,最终将按第15行所示,进入Runnable对象的run()方法。

第5行的mCallbackHandler时一种构造方法传入的,它是个接口对象,如果不为null的话,Message将被第19行的handleMessage()方法所处理。

如果msg.callbackmCallback都为null或者mCallback.handleMessage返回了false,则Message将被第25行——HandlerhandleMessage()方法所处理,所以Handler的子类需要重写该方法以处理Message

总结

现在再回头看最初的两个疑问:
1.一个Handler发出的消息要放入哪一个MessageQueue,又被哪一个Looper所取出?
2. Looper取出的消息给哪一个Handler处理?

经过之前的分析,答案已经很清楚了:
1. Handler在创建时会获取Looper.prepare()所准备好的LooperMessageQueue,于是该Handler的消息会存入该MessageQueue中,然后被该Looper取出。
2. Handler在存入消息时,会将自身赋值给Message的成员变量target,于是Looper就可以将消息交给这个target处理。

根据以上分析,可以画出这样的流程图:
这里写图片描述

主线程的Looper问题

可能有人会问:为什么我没在主线程中调用Looper.prepare()Looper.loop()
,却可以随手创建一个Handler使用,这不是不符合刚才的分析吗?

其实主线程也是一样的,只是系统已经帮我们调用了Looper.prepare()Looper.loop()

app启动后会进入ActivityThreadmain()方法,该方法如下:

public static void main(String[] args) {
     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
     SamplingProfilerIntegration.start();

     // CloseGuard defaults to true and can be quite spammy.  We
     // disable it here, but selectively enable it later (via
     // StrictMode) on debug builds, but using DropBox, not logs.
     CloseGuard.setEnabled(false);

     Environment.initForCurrentUser();

     // Set the reporter for event logging in libcore
     EventLogger.setReporter(new EventLoggingReporter());

     // Make sure TrustedCertificateStore looks in the right place for CA certificates
     final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
     TrustedCertificateStore.setDefaultUserDirectory(configDir);

     Process.setArgV0("<pre-initialized>");

     Looper.prepareMainLooper();

     ActivityThread thread = new ActivityThread();
     thread.attach(false);

     if (sMainThreadHandler == null) {
         sMainThreadHandler = thread.getHandler();
     }

     if (false) {
         Looper.myLooper().setMessageLogging(new
                 LogPrinter(Log.DEBUG, "ActivityThread"));
     }

     // End of event ActivityThreadMain.
     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
     Looper.loop();

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

第21行和第37行就是相关调用的地方,所以我们才可以在主线程中随手创建一个Handler使用。

下载方式:https://pan.quark.cn/s/a4b39357ea24 布线问题(分支限界算法)是计算机科学和电子工程领域中一个广为人知的议题,它主要探讨如何在印刷电路板上定位两个节点间最短的连接路径。 在这一议题中,电路板被构建为一个包含 n×m 个方格的矩阵,每个方格能够被界定为可通行或不可通行,其核心任务是定位从初始点到最终点的最短路径。 分支限界算法是处理布线问题的一种常用策略。 该算法与回溯法有相似之处,但存在差异,分支限界法仅需获取满足约束条件的一个最优路径,并按照广度优先或最小成本优先的原则来探索解空间树。 树 T 被构建为子集树或排列树,在探索过程中,每个节点仅被赋予一次成为扩展节点的机会,且会一次性生成其全部子节点。 针对布线问题的解决,队列式分支限界法可以被采用。 从起始位置 a 出发,将其设定为首个扩展节点,并将与该扩展节点相邻且可通行的方格加入至活跃节点队列中,将这些方格标记为 1,即从起始方格 a 到这些方格的距离为 1。 随后,从活跃节点队列中提取队首节点作为下一个扩展节点,并将与当前扩展节点相邻且未标记的方格标记为 2,随后将这些方格存入活跃节点队列。 这一过程将持续进行,直至算法探测到目标方格 b 或活跃节点队列为空。 在实现上述算法时,必须定义一个类 Position 来表征电路板上方格的位置,其成员 row 和 col 分别指示方格所在的行和列。 在方格位置上,布线能够沿右、下、左、上四个方向展开。 这四个方向的移动分别被记为 0、1、2、3。 下述表格中,offset[i].row 和 offset[i].col(i=0,1,2,3)分别提供了沿这四个方向前进 1 步相对于当前方格的相对位移。 在 Java 编程语言中,可以使用二维数组...
源码来自:https://pan.quark.cn/s/a4b39357ea24 在VC++开发过程中,对话框(CDialog)作为典型的用户界面组件,承担着与用户进行信息交互的重要角色。 在VS2008SP1的开发环境中,常常需要满足为对话框配置个性化背景图片的需求,以此来优化用户的操作体验。 本案例将系统性地阐述在CDialog框架下如何达成这一功能。 首先,需要在资源设计工具中构建一个新的对话框资源。 具体操作是在Visual Studio平台中,进入资源视图(Resource View)界面,定位到对话框(Dialog)分支,通过右键选择“插入对话框”(Insert Dialog)选项。 完成对话框内控件的布局设计后,对对话框资源进行保存。 随后,将着手进行背景图片的载入工作。 通常有两种主要的技术路径:1. **运用位图控件(CStatic)**:在对话框界面中嵌入一个CStatic控件,并将其属性设置为BST_OWNERDRAW,从而具备自主控制绘制过程的权限。 在对话框的类定义中,需要重写OnPaint()函数,负责调用图片资源并借助CDC对象将其渲染到对话框表面。 此外,必须合理处理WM_CTLCOLORSTATIC消息,确保背景图片的展示不会受到其他界面元素的干扰。 ```cppvoid CMyDialog::OnPaint(){ CPaintDC dc(this); // 生成设备上下文对象 CBitmap bitmap; bitmap.LoadBitmap(IDC_BITMAP_BACKGROUND); // 获取背景图片资源 CDC memDC; memDC.CreateCompatibleDC(&dc); CBitmap* pOldBitmap = m...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值