Android消息机制回顾(Handler、Looper、MessageQueue源码解析)

news2024/9/25 15:22:27

回顾:

Android消息机制

Android消息机制主要指的是Handler的运行机制以及Handler所附带的MessageQueue和Looper的工作机制。

介绍

通过Handler 消息机制来解决线程之间通信问题,或者用来切换线程。特别是在更新UI界面时,确保了线程间的数据同步和交互。

  • Handler:Handler的主要作用是将一个任务切换到某个指定的线程中执行。在Android开发中,Handler常用于从子线程更新UI界面,因为Android的UI控件不是线程安全的,直接在非UI线程中更新UI可能会导致界面处于不可预期的状态。通过Handler,可以在主线程(即UI线程)中安全地更新UI。

  • MessageQueue:MessageQueue是消息机制的Java层和C++层的连接纽带,它存储了一组待处理的消息,并提供了插入和删除的操作。MessageQueue的内部实现并不是传统的队列,而是采用单链表的形式。

  • Looper:Looper在Android消息机制中扮演着消息循环的角色。它会不断地从MessageQueue中查看是否有新消息,如果有新消息就会立刻处理,否则就一直阻塞在那里。Looper是针对线程的,为线程创建Looper后,该线程就可以通过Handler来处理消息了。

  • ThreadLocal:ThreadLocal是一个可以在多个线程间互不干扰地提供数据的类。在Android中,每个线程都有自己的ThreadLocalMap实例,用于存储该线程的Looper信息。这意味着不同线程访问ThreadLocal时,会获得不同的值副本,从而保证了线程间的独立性。

总的来说,Android的消息机制通过Handler、MessageQueue、Looper和ThreadLocal的协同工作,实现了跨线程的通信和数据的处理,确保了应用程序的响应性和界面的流畅性。

流程

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

下图来自:https://www.jianshu.com/p/f10cff5b4c25

示例

Looper的使用示例

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

Looper

用于在指定线程中运行一个消息循环,一旦有新任务则执行,执行完继续等待下一个任务,即变成Looper线程。

创建

Looper的创建需要通过Looper.prepare()。

在构造函数中创建了一个消息队列MessageQueue的实例mQueue,并持有当前线程对象的引用mThread

    @UnsupportedAppUsage
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

    ...

    /** 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();
    }

ThreadLocal

ThreadLocal并不是线程,它的作用是可以在每个线程中存储数据。可以在不同的线程中互不干扰地存储并提供数据,通过它可以轻松获得每个线程的Looper。

运行

使用Looper.loop()在当前线程运行消息队列。(在这之前需要调用prepare方法,否则会抛出异常)

for循环中,不断调用MessageQueue对象queue的next方法来获取下一个待处理的消息Message对象message。msg.target.dispatchMessage(msg); msg.target是handler对象。

注:next方法可能会发生阻塞。

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.");
        }
        if (me.mInLoop) {
            Slog.w(TAG, "Loop again would have the queued messages be executed"
                    + " before this one completed.");
        }

        me.mInLoop = true;
        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();

        // Allow overriding a threshold with a system prop. e.g.
        // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
        final int thresholdOverride =
                SystemProperties.getInt("log.looper."
                        + Process.myUid() + "."
                        + Thread.currentThread().getName()
                        + ".slow", 0);

        boolean slowDeliveryDetected = false;

        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);
            }
            // Make sure the observer won't change while processing a transaction.
            final Observer observer = sObserver;

            final long traceTag = me.mTraceTag;
            long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
            long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
            if (thresholdOverride > 0) {
                slowDispatchThresholdMs = thresholdOverride;
                slowDeliveryThresholdMs = thresholdOverride;
            }
            final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
            final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);

            final boolean needStartTime = logSlowDelivery || logSlowDispatch;
            final boolean needEndTime = logSlowDispatch;

            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }

            final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
            final long dispatchEnd;
            Object token = null;
            if (observer != null) {
                token = observer.messageDispatchStarting();
            }
            long origWorkSource = ThreadLocalWorkSource.setUid(msg.workSourceUid);
            try {
                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);
                }
            }
            if (logSlowDelivery) {
                if (slowDeliveryDetected) {
                    if ((dispatchStart - msg.when) <= 10) {
                        Slog.w(TAG, "Drained");
                        slowDeliveryDetected = false;
                    }
                } else {
                    if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
                            msg)) {
                        // Once we write a slow delivery log, suppress until the queue drains.
                        slowDeliveryDetected = true;
                    }
                }
            }
            if (logSlowDispatch) {
                showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
            }

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

Message

Message

摘自:https://juejin.cn/post/6844903446571663374

这个类定义了一个包含描述和一个任意类型对象的对象,它可以被发送给Handler。

/** 
   *  
   * Defines a message containing a description and arbitrary data object that can be 
   * sent to a {@link Handler}.  This object contains two extra int fields and an 
   * extra object field that allow you to not do allocations in many cases. 
   * 
   * While the constructor of Message is public, the best way to get 
   * one of these is to call {@link #obtain Message.obtain()} or one of the 
   * {@link Handler#obtainMessage Handler.obtainMessage()} methods, which will pull 
   * them from a pool of recycled objects. 
   */

从注释里我们还可以了解到以下几点:

  • 尽管Message有public的默认构造方法,但是你应该通过Message.obtain()来从消息池中获得空消息对象,以节省资源。
  • 如果你的message只需要携带简单的int信息,请优先使用Message.arg1和Message.arg2来传递信息,这比用Bundle更省内存
  • 用message.what来标识信息,以便用不同方式处理message。
    /**
     * Return a new Message instance from the global pool. Allows us to
     * avoid allocating new objects in many cases.
     */
    public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

MessageQueue

在Looper的构造函数中创建了MessageQueue,在loop过程中,通过死循环不断的获取消息。
可以通过Looper.myQueue()获取。

MessageQueue类注释如下:

/**
 * Low-level class holding the list of messages to be dispatched by a
 * {@link Looper}.  Messages are not added directly to a MessageQueue,
 * but rather through {@link Handler} objects associated with the Looper.
 *
 * <p>You can retrieve the MessageQueue for the current thread with
 * {@link Looper#myQueue() Looper.myQueue()}.
 */

Handler中调用了MessageQueue对象的enqueueMessage函数,将Message对象发送到队列中。

Handler中:

    public final boolean sendMessageAtFrontOfQueue(@NonNull Message msg) {
        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, 0);
    }
    
    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);
    }

MessageQueue中:

    boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }

        synchronized (this) {
            if (msg.isInUse()) {
                throw new IllegalStateException(msg + " This message is already in use.");
            }

            if (mQuitting) {
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w(TAG, e.getMessage(), e);
                msg.recycle();
                return false;
            }

            msg.markInUse();
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
            if (p == null || when == 0 || when < p.when) {//队列头
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                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;
    }

Handler

Handler的实际应用就是UI线程与其他线程之间的切换。

创建

Handler有多个构造函数,主要是设置三个参数Looper对象,Callback对象,布尔类型async。Callback对象主要涉及消息的处理,async表示是否设置同步屏障。

public Handler(@NonNull Looper looper)
public Handler(@NonNull Looper looper, @Nullable Callback callback)
public Handler(boolean async) 
public Handler(@Nullable Callback callback, boolean async)
public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async)

消息传递

通过sendMessage发送一个Message对象,或通过post方法提交一个Runable对象。
而post函数只是将Runable对象封装到Message对象中的callback函数。最终还是调用sendMessagedDelayed函数的历程去处理。
从这里我们定位到了在Looper的loop函数中Message对象的target是Handler对象,看看dispatchMessage函数。

public void dispatchMessage(@NonNull Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}

从dispatchMessage函数可以看出对消息处理的优先级。

消息Message对象msg自带的Runable对象callback。也就是我们通过post函数投递的Runable对象会最先被处理。
优先级排第二就是我们在创建Handler对象时,设置的全局回调Callback对象mCallback。
优先级最低的,也是最常用的,重载handleMessage函数,该函数默认是空实现。

sendMessage与obtainMessage

public final boolean sendMessage(@NonNull Message msg); //传入一个Message参数,进行排队发送到handleMessage
public final Message obtainMessage(); //返回值是一个Message,一般搭配sendToTarget使用
有多个重载版本,就是构建传入参数的不同产出不同的Message
public final Message obtainMessage(int what);   //带指定what的Message
public final Message obtainMessage(int what, @Nullable Object obj);//带指定what和obj的Message
public final Message obtainMessage(int what, int arg1, int arg2);//带指定what arg1 arg2的Message
public final Message obtainMessage(int what, int arg1, int arg2, @Nullable Object obj);带指定what arg1 arg2 obj的Message搭配使用就是 obtainMessage(xx).sendToTarget(); //实现和sendMessage相同的功能

obtainMessage会利用内部的message池,如果池中有可用message,就不重新new分配。参考Message的构造函数

参考资料

Android消息机制的原理及源码解析

Android Handler 消息机制

Android的消息机制Handler

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1701037.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

20232937文兆宇 2023-2024-2 《网络攻防实践》实践十一报告

20232937文兆宇 2023-2024-2 《网络攻防实践》实践十一报告 1.实践内容 木马是一种带有恶意性质的远程控制软件。木马一般分为客户端和服务器端&#xff0c;客户端是本地使用的各种命令的控制台&#xff0c;而服务器端则是要给别人运行&#xff0c;只有运行过服务器端的计算机…

工具:Visual Studio Code

一、VSCode生成exe 二、在vs中断点调试 如果没效果需要安装如下与unity相连接的插件 三、注释 1、代码注释 注释和取消都是都是同一个命令&#xff1a;选中代码&#xff0c;然后按住CtrlShift/ 2、方法或类注释 /// 四、导航 五、将变量注释展示到解释面板 1、直接显示 [Too…

YOLOv8: RuntimeError: DataLoader worker (pid(s) xxxxx) exited unexpectedly

遇到错误&#xff1a; 一、 raise RuntimeError(DataLoader worker (pid(s) {}) exited unexpectedly.format(pids_str)) RuntimeError: DataLoader worker (pid(s) 4252, 17184) exited unexpectedly二、OSError: [WinError 1455] 页面文件太小&#xff0c;无法完成操作。 处…

有趣的css - 水波纹按钮

大家好&#xff0c;我是 Just&#xff0c;这里是「设计师工作日常」&#xff0c;今天分享的是一个好看有质感的水波纹按钮。 最新文章通过公众号「设计师工作日常」发布。 目录 整体效果核心代码html 代码css 部分代码 完整代码如下html 页面css 样式页面渲染效果 整体效果 &a…

【C++语言】继承:类特性的扩展,重要的类复用!

【C语言】继承&#xff0c;更进一步的复用 ✨精美思维导图奉上继承1. 继承的相关概念&#xff1a;2. 继承的定义&#xff1a;&#xff08;1&#xff09;定义格式&#xff1a;&#xff08;2&#xff09;访问限定符和继承方式&#xff1a;&#xff08;3&#xff09;默认继承方式&…

取代或转型?人工智能对软件测试的影响(内附工具推荐)

在当今快速发展的数字环境中&#xff0c;从移动App到基于Web的平台&#xff0c;软件已成为我们日常生活和工作不可或缺的一部分。然而&#xff0c;随着软件系统变得越来越复杂&#xff0c;如何确保其质量和可靠性已成为开发人员和测试人员所面临的一大重要挑战。 这就是软件测…

强化学习,第 3 部分:蒙特卡罗方法

文章目录 一、介绍二、关于此文章三、无模型方法与基于模型的方法四、V函数估计4.1 基本概念4.2 V-功能 五、Q 函数估计5.1 V函数概念5.2 优势5.3 Q函数 六、勘探与勘探的权衡七、结论 一、介绍 从赌场到人工智能&#xff1a;揭示蒙特卡罗方法在复杂环境中的强大功能    强化…

生命在于学习——Python人工智能原理(2.1)

二、机器学习 1、机器学习的定义 机器学习是指从有限的观测数据中学习出具有一般性的规律&#xff0c;并利用这些规律对未知数据进行预测的方法&#xff0c;通俗的讲&#xff0c;机器学习就是让计算机从数据中进行自动学习&#xff0c;得到某种知识。 传统的机器学习主要关注…

深度强化学习 Actor-Critic演员评论家 PPO

将策略(Policy Based)和价值(Value Based)相结合的方法&#xff1a;Actor-Critic算法&#xff0c;在强化学习领域最受欢迎的A3C算法&#xff0c;DDPG算法&#xff0c;PPO算法等都是AC框架。 一、Actor-Critic算法简介 Actor-Critic从名字上看包括两部分&#xff0c;演员(Actor…

Geoserver发布shp图层服务的样式控制及样式生成方式

在利用geoserver发布视频图层服务时&#xff0c;shp图层的样式可以在QGis文件中进行编辑&#xff1b;shp文件编辑后&#xff0c;需要导出样式文件&#xff0c;并在geoserver中进行注册&#xff0c;发布时对应shp图层文件时&#xff0c;需要选中对应样式&#xff0c;加载图层服务…

WorkPlus移动应用平台集成单点登录,实现统一门户解决方案

随着企业数字化转型的深入&#xff0c;移动办公已经成为企业提高工作效率和员工协作的重要途径。为了更好地管理企业移动应用&#xff0c;提升员工体验&#xff0c;简化登录流程&#xff0c;许多企业开始采用集成单点登录技术的企业移动应用平台&#xff0c;实现统一门户的目标…

实验室课程|基于SprinBoot+vue的实验室课程管理系统(源码+数据库+文档)

实验室课程管理系统 目录 基于SprinBootvue的实验室课程管理系统 一、前言 二、系统设计 三、系统功能设计 1管理员功能模块 2学生功能模块 3教师功能模块 四、数据库设计 五、核心代码 六、论文参考 七、最新计算机毕设选题推荐 八、源码获取&#xff1a; 博主介…

PMP考试通关秘籍

考试大纲 考试大纲&#xff1a;考察维度3 个&#xff08;人、过程、商业环境&#xff09;&#xff1b;更加贴近真实项目趋势&#xff1b;侧重点从做事到关注人&#xff1b;对于项目经理的软技能要求更高&#xff0c;匹配 PM 能力模型。 人员&#xff08;42%&#xff09;&…

55页PDF|人工智能通用大模型(ChatGPT)的进展、风险与应对(附下载)

&#x1f449;获取方式&#xff1a; &#x1f61d;有需要的小伙伴&#xff0c;可以保存图片到wx扫描二v码免费领取【保证100%免费】&#x1f193;

3D技术的应用领域

3D技术在现代科技和工业中有广泛的应用&#xff0c;其涵盖的领域非常广泛&#xff0c;从娱乐到医学&#xff0c;再到制造业和建筑&#xff0c;3D技术正在改变我们理解和互动的方式。以下是一些主要的应用领域。北京木奇移动技术有限公司&#xff0c;专业的软件外包开发公司&…

k8s devops实战教程+生产实践+可就业

k8s devops实战教程 简介教程涉及到内容教程获取学习教程后的收货助学群 简介 越来越多的企业应用云原生化&#xff0c;催生很多应用的部署方式也发生了很多变化。 从物理机部署应用过度到虚机部署应用再到应用容器化&#xff0c;从单应用再到服务拆分为微服务&#xff0c;靠人…

linux查看是否被入侵(一)

1、查看当前系统状态 [rootbastion-IDC ~]#top #一般挖矿等病毒点用CPU比较大 2、查看当前登录用户(w\who) 3、检查系统日志 检查系统错误登陆日志&#xff0c;统计IP重试次数 [rootbastion-IDC ~]# lastb 4、查看近期用户登录情况 [rootkvm01 ~]# last -n 5 #-n 5 表示…

element el-table表格表头某一列表头文字或者背景修改颜色

效果如下 整体代码 &#xff0c;具体方法在最下面&#xff01; <el-table v-loading"listLoading" :data"sendReceivList" element-loading-text"Loading" border fit ref"tableList" :header-cell-class-name"addClass&quo…

揭秘APP广告变现的高效秘诀:如何让你的APP更赚钱?

在数字化时代&#xff0c;APP已成为人们获取信息、娱乐休闲的重要平台。对于许多内容创作者来说&#xff0c;如何通过APP实现盈利&#xff0c;是一个亟待解决的问题。而APP广告变现项目&#xff0c;正是其中一种备受关注的盈利模式。那么&#xff0c;如何有效地利用APP广告变现…

安泰电子:功率放大器的选择方法有哪些

选择适合的功率放大器是实现电子系统中的关键步骤之一。以下是一些选择功率放大器的常用方法和考虑因素&#xff1a; 功率需求&#xff1a;首先确定你的系统需要多大的功率输出。功率输出需求通常由被驱动设备的功率要求决定。计算出所需功率后&#xff0c;选择一个具有适当功率…