Handler 机制 源码分析

本文深入探讨了Android消息机制的核心组件,包括Handler、Message、MessageQueue和Looper的工作原理。详细介绍了消息如何在子线程和主线程之间传递,消息队列的管理方式,以及Looper如何不断轮询读取消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看之前先问自己下面几个问题:


  1. Message 是怎么获取到消息对象的
  2. 消息是怎么加入到消息队列中的,又是怎么被取出来的
  3. 到底是怎么实现子线程和主线程的通信的
  4. Handler sendMessage 是把消息发送到哪里了
  5. Handler 处理消息的方法有几种

消息传递机制的核心类:

Handler

Message

MessageQueue

Looper


下面是自己看的一些源码

  • Message 是怎么获取到消息对象的

    **Message.java**
    
    通过 Message.obtain();
    
/**
  * Return a new Message instance from the global pool. Allows us to
  * avoid allocating new objects in many cases.
  */
        public static Message obtain() {
            synchronized (mPoolSync) {
                if (mPool != null) {
                    Message m = mPool;
                    mPool = m.next;
                    m.next = null;
                    mPoolSize--;
                    return m;
                }
            }
            return new Message();
        }
  • 是通过一个单链表来维护的,如果消息池不为空,就把已有的消息赋值给 m ,然后把下一条消息变成第一条消息。
  • 当消息池为空的时候,再去 new Message();

  • 在创建 Handler 对象的时候,在其构造方法中就可以获得 Looper 和 MessageQueue 对象

    **Handler.java**
    
/**
         * Default constructor associates this handler with the queue for the
         * current thread.
         *
         * If there isn't one, this handler won't be able to receive messages.
         */
        public Handler() {

          ......

            //获取到一个 Looper
            mLooper = Looper.myLooper();

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

            //获取到一个 MessageQueue
            mQueue = mLooper.mQueue;
            mCallback = null;
        }

        来看看 Looper.myLooper()做了些什么

        Looper.java

        /**
         * Return the Looper object associated with the current thread.  Returns
         * null if the calling thread is not associated with a Looper.
         */
        public static final Looper myLooper() {
            return (Looper)sThreadLocal.get();
        }

ThreadLocal: 线程内单例 ThreadLocal.get(); 在哪个线程中set,get拿的就是哪个线程中的对象

  sThreadLocal 有get 方法大概就有set方法,去查找一下
/** 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 final void prepare() {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");//一个线程只能有一个 Looper
        }
        sThreadLocal.set(new Looper());
    }

在这里看出来 直接 new 出了一个 Looper();并且一个线程只能有一个 Looper Looper
在哪个线程new就会存在在哪个线程 在 Looper 的构造方法中 new 出了 MessageQueue

  private Looper() {
        mQueue = new MessageQueue();
        mRun = true;
        mThread = Thread.currentThread();
   }

Looper.prepare();就是向线程中添加了一个looper, sThreadLocal.set(new Looper());

    * 上面的prepare方法是在prepareMainLooper 中调用的
    /** 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.
      * {@link #prepare()}
      */

        public static final void prepareMainLooper() {
            prepare();
            setMainLooper(myLooper());//设置一个主线程的轮询器
            if (Process.supportsProcesses()) {
                myLooper().mQueue.mQuitAllowed = false;
            }
        }

prepareMainLooper()方法是在 ActivityThread 类的 main
方法中调用的在应用启动时,主线程要被启动,ActivityThread
会被创建,在此类的main方法中,在主线程调用任何方法,执行都会跑到主线程

    ActivityThread.java
//主线程
public static void main(String[] args) {

    Looper.prepareMainLooper();//Looper存在在主线程,然后不断的去轮询读消息

                ....

    Looper.loop();//不断的轮询读消息
}
    - Looper.loop();方法中有一个死循环,不断的从消息队列中取消息
        /**
         *  Run the message queue in this thread. Be sure to call
         * {@link #quit()} to end the loop.
         */
        public static final void loop() {
            Looper me = myLooper();
            MessageQueue queue = me.mQueue;

            ......

            while (true) {

                //取出消息队列中的下一条消息,可能会阻塞
                Message msg = queue.next(); // might block

                if (msg != null) {
                    if (msg.target == null) {// msg.target 其实就是一个 handler 对象,如果没有handler来处理,直接返回
                        // No target is a magic identifier for the quit message.
                        return;
                    }

            ......
                    //解析消息,分发消息
                    msg.target.dispatchMessage(msg);

                    msg.recycle();
                }
            }
        }
  • 关于取消息时的阻塞

Linux 的进程间通信机制: Pipe(管道)
原理:在内存中有一个特殊的文件,这个文件有两个句柄(引用),一个是读句柄,一个是写句柄。主线程 Looper
从主线程读取消息,当读取完所有的消息时,会进入睡眠状态,主线程阻塞。当子线程往消息队列中发送消息,并且往管道文件中写入数据,主线程马上被唤醒,从管道文件中读取数据。主线程被唤醒就是为了读取数据,当再次读取完毕之后,再次进入休眠状态

Handler 发消息 sendMessage() … sendEmptyMessage() … sendMessageDelay()… 其实最后都调用了同一个方法

Handler.java
public boolean sendMessageAtTime(Message msg, long uptimeMillis){
      boolean sent = false;
       MessageQueue queue = mQueue;
       if (queue != null) {
           msg.target = this;//在拿Handler发消息的时候,把Handler保存到了Message里面了,this就是handler对象,所以msg.target也是handler对象
           sent = queue.enqueueMessage(msg, uptimeMillis);//把消息msg放入到了消息队列(MessageQueue)中
       }
       else {
         ......
       }
       return sent;
}

MessageQueue.java

//enqueueMessage 把消息重新排列后放入消息队列中
            //排序的方式:根据消息队列中是否有消息,和消息时间的对比,之后放入队列。
final boolean enqueueMessage(Message msg, long when) {
       if (msg.when != 0) {
           throw new AndroidRuntimeException(msg
                   + " This message is already in use.");
       }

          msg.when = when;

          Message p = mMessages; // 队列中的第一条消息
          // 如果消息为空,或者时间为0,或者时间比第一条消息的时间要短,就把这条消息放在队列中的第一个位置
          if (p == null || when == 0 || when < p.when) { 
              msg.next = p;
              mMessages = msg;
              needWake = mBlocked; // new head, might need to wake up
          } else {
            //如果消息不为空,并且时间不比第一条消息的时间短。就把该消息插入到合适的队列中的位置。
              Message prev = null;
              //循环找出当前消息的位置
              while (p != null && p.when <= when) {
                  prev = p;
                  p = p.next;//当前消息要插到 prev 消息后面。
              }
              msg.next = prev.next;
              prev.next = msg;
              needWake = false; // still waiting on head, no need to wake up
          }
      }

        //唤醒主线程
   if (needWake) {
       nativeWake(mPtr);
   }

      return true;
}

此时,消息队列中如果已经有了消息,那么 Looper.loop() 就会不断的去轮询,通过 queue.next() 拿到消息,然后通过
handler 分发处理

Looper.loop()
//获取消息队列的消息
 Message msg = queue.next(); // might block
 ...
//分发消息,消息由哪个handler对象创建,则由它分发,并由它的handlerMessage处理  
msg.target.dispatchMessage(msg);
  • msg的target属性,用于记录该消息是由哪个 Handler 创建的,在obtain中赋值。

    • Handler 处理消息的几种方法
/**
  * Handle system messages here.
  */

 public void dispatchMessage(Message msg) {
     if (msg.callback != null) {
         handleCallback(msg);//下面的第 2 种方式。
     } else {
         if (mCallback != null) {
             if (mCallback.handleMessage(msg)) { // 下面的第 3 种方式
                 return;
             }
         }
         handleMessage(msg);//这个就是下面的第 1 种方式
     }
 }



//1,重写 handleMessage()方法进行处理。我们最常用的方法

Handler handler = new Handler(){

public void handleMessage(android.os.Message msg) {
        //处理相应的逻辑
    ......
    };
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Message msg = Message.obtain();
    handler.sendMessage(msg);
}


//2,封装一个 CallBack 的 Runnable 任务,在这个任务中处理数据

Handler handler = new Handler();

Runnable callback = new Runnable() {

    @Override
    public void run() {
        //在这里处理一些逻辑
        ......
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Message msg = Message.obtain(handler, callback);
    handler.sendMessage(msg);

}

//3, new 一个 Handler 的 CallBack ,重写 handleMessage 方法。
//和第 1 种方式中 的 handleMessage 方法哪个优先级高呢?从dispatchMessage 方法中可以看出来。如果下面的 handleMessage 返回值为 true,
//那么将不会执行 第一种方式的 handleMessage 方法。

Handler.Callback callback = new Handler.Callback(){

public boolean handleMessage(Message msg) {
        //处理相应逻辑
    ......
        return false;
    };
};

Handler handler = new Handler();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Message msg = Message.obtain();
    handler.sendMessage(msg);

}
  • 处理方式的优先级从分发消息的方法可以看的出来: 2 > 3 > 1
标题基于SpringBoot+Vue的学生交流互助平台研究AI更换标题第1章引言介绍学生交流互助平台的研究背景、意义、现状、方法与创新点。1.1研究背景与意义分析学生交流互助平台在当前教育环境下的需求及其重要性。1.2国内外研究现状综述国内外在学生交流互助平台方面的研究进展与实践应用。1.3研究方法与创新点概述本研究采用的方法论、技术路线及预期的创新成果。第2章相关理论阐述SpringBoot与Vue框架的理论基础及在学生交流互助平台中的应用。2.1SpringBoot框架概述介绍SpringBoot框架的核心思想、特点及优势。2.2Vue框架概述阐述Vue框架的基本原理、组件化开发思想及与前端的交互机制。2.3SpringBoot与Vue的整合应用探讨SpringBoot与Vue在学生交流互助平台中的整合方式及优势。第3章平台需求分析深入分析学生交流互助平台的功能需求、非功能需求及用户体验要求。3.1功能需求分析详细阐述平台的各项功能需求,如用户管理、信息交流、互助学习等。3.2非功能需求分析对平台的性能、安全性、可扩展性等非功能需求进行分析。3.3用户体验要求从用户角度出发,提出平台在易用性、美观性等方面的要求。第4章平台设计与实现具体描述学生交流互助平台的架构设计、功能实现及前后端交互细节。4.1平台架构设计给出平台的整体架构设计,包括前后端分离、微服务架构等思想的应用。4.2功能模块实现详细阐述各个功能模块的实现过程,如用户登录注册、信息发布与查看、在线交流等。4.3前后端交互细节介绍前后端数据交互的方式、接口设计及数据传输过程中的安全问题。第5章平台测试与优化对平台进行全面的测试,发现并解决潜在问题,同时进行优化以提高性能。5.1测试环境与方案介绍测试环境的搭建及所采用的测试方案,包括单元测试、集成测试等。5.2测试结果分析对测试结果进行详细分析,找出问题的根源并
内容概要:本文详细介绍了一个基于灰狼优化算法(GWO)优化的卷积双向长短期记忆神经网络(CNN-BiLSTM)融合注意力机制的多变量多步时间序列预测项目。该项目旨在解决传统时序预测方法难以捕捉非线性、复杂时序依赖关系的问题,通过融合CNN的空间特征提取、BiLSTM的时序建模能力及注意力机制的动态权重调节能力,实现对多变量多步时间序列的精准预测。项目不仅涵盖了数据预处理、模型构建与训练、性能评估,还包括了GUI界面的设计与实现。此外,文章还讨论了模型的部署、应用领域及其未来改进方向。 适合人群:具备一定编程基础,特别是对深度学习、时间序列预测及优化算法有一定了解的研发人员和数据科学家。 使用场景及目标:①用于智能电网负荷预测、金融市场多资产价格预测、环境气象多参数预报、智能制造设备状态监测与预测维护、交通流量预测与智慧交通管理、医疗健康多指标预测等领域;②提升多变量多步时间序列预测精度,优化资源调度和风险管控;③实现自动化超参数优化,降低人工调参成本,提高模型训练效率;④增强模型对复杂时序数据特征的学习能力,促进智能决策支持应用。 阅读建议:此资源不仅提供了详细的代码实现和模型架构解析,还深入探讨了模型优化和实际应用中的挑战与解决方案。因此,在学习过程中,建议结合理论与实践,逐步理解各个模块的功能和实现细节,并尝试在自己的项目中应用这些技术和方法。同时,注意数据预处理的重要性,合理设置模型参数与网络结构,控制多步预测误差传播,防范过拟合,规划计算资源与训练时间,关注模型的可解释性和透明度,以及持续更新与迭代模型,以适应数据分布的变化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_kayce

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值