详解Android 消息处理机制

论坛 期权论坛 脚本     
niminba   2021-5-23 03:07   823   0

摘要

Android应用程序是通过消息来驱动的,当Android主线程启动时就会在内部创建一个消息队列。然后进入一个无限循环中,轮询是否有新的消息需要处理。如果有新消息就处理新消息。如果没有消息,就进入阻塞状态,直到消息循环被唤醒。
那么在Android系统中,消息处理机制是怎么实现的呢?在程序开发时,我们经常会使用Handler处理Message(消息)。所以可以知道Handler是个消息处理者,Message是消息主体。除此之外还有消息队列和消息轮询两个角色。它们分别是MessageQueue和Looper,MessageQueue就是消息队列,Looper负责轮询消息。

简介

我们已经知道Android的消息机制处理主要由Handler、Message、MessageQueue、Looper四个类的实现来完成。那么它们之间的关系是怎样的?
其中,Message是消息主体,它负责存储消息的各种信息,包括发送消息的Handler对象、消息信息、消息标识等。MessageQueue就是消息队列,在其内部以队列的形式维护一组Message(消息)。Handler负责发送和处理消息。Looper负责轮询消息队列。

Android消息机制原理

创建线程消息队列

在Android应用程序中,消息处理程序运行前首先要创建消息队列(也就是MessageQueue)。在主线程中,通过调用Looper类的静态成员函数prepareMainLooper()来创建消息队列。在其他子线程中,通过调用静态成员函数prepare()来创建。
prepareMainLooper()与prepare()的实现:

  /**
   * Initialize the current thread as a looper, marking it as an
   * application's main looper. The main looper for your application
   * is created by the Android environment, so you should never need
   * to call this function yourself. See also: {@link #prepare()}
   * 用来初始化主线程中的Looper,有Android环境调用,不应该有用户调用.
   */
  public static void prepareMainLooper() {
    prepare(false);
    synchronized (Looper.class) {
      if (sMainLooper != null) {
        throw new IllegalStateException("The main Looper has already been prepared.");
      }
      sMainLooper = myLooper();
    }
  }
  
  public static @Nullable Looper myLooper() {
    return sThreadLocal.get();
  }

   /** 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()}.
   * 交给用户自己调用,通过loop()方法开启消息循环.同时当不需要处理消息时,需要手动调用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));
  }

在这两个函数调用的过程中,sThreadLocal变量都有被使用。这个变量是ThreadLocal类型的,用来保存当前线程中的Looper对象。也就是说在Android应用程序中每创建一个消息队列,都有一个并且是唯一 一个与之对应的Looper对象。而且我们可以从源码中看到当对象不唯一时就会抛出异常。

private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed); //创建消息队列
    mThread = Thread.currentThread();
  }

从上面的源码中可以看到,当Looper对象实例化的过程的同时会创建一个消息队列。

消息循环过程

在消息队列建立完成之后,调用Looper对象的静态成员方法loop()就开始了消息循环。

  /**
   * Run the message queue in this thread. Be sure to call
   * {@link #quit()} to end the loop.
   */
  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(); // 在接收消息时有可能阻塞
      if (msg == null) {
        //message为null时,退出消息循环
        return;
      }

      // This must be in a local variable, in case a UI event sets the logger
      final Printer logging = me.mLogging;
      if (logging != null) {...}

      final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

      final long traceTag = me.mTraceTag;
      ifJ3b"_rC
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1060120
帖子:212021
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP