当前位置: 首页 > news >正文

Handler消息机制

Android 的消息机制主要是指 Handler 的运行机制以及 Handler 所附带的 MessageQueue 和 Looper 的工作过程。 Handler 的主要作用是将某个任务切换到 Handler 所在的线程中去执行。

一句话,每个线程可以创建一个 Looper ,每个 Looper 轮询着一个 MessageQueue 不断取出消息,有消息则回调给 Handler,Handler 负责向 MessageQueue 中发送消息和处理回调的消息来完成线程之间的转换

也就是说与我们交互的是handler,我们使用handler向looper发送消息,looper就在他所在的线程对消息进行处理了

那么runnable呢,runnable就是一段让looper直接执行的指令,而不是通过message判断该执行什么已经设定好的操作

import android.os.*
import android.util.Log
import java.util.concurrent.atomic.AtomicBooleanclass HandlerExample {// 日志标签private val TAG = "HandlerExample"// 消息类型常量companion object {const val MSG_HELLO = 1const val MSG_WORLD = 2const val MSG_STOP = 3}// 工作线程和对应的 Handlerprivate lateinit var workerThread: WorkerThreadprivate lateinit var workerHandler: Handler// UI 线程的 Handlerprivate val mainHandler = object : Handler(Looper.getMainLooper()) {override fun handleMessage(msg: Message) {when (msg.what) {MSG_HELLO -> Log.d(TAG, "Main Thread received: Hello")MSG_WORLD -> Log.d(TAG, "Main Thread received: World")else -> super.handleMessage(msg)}}}// 工作线程类inner class WorkerThread : Thread() {private val running = AtomicBoolean(false)override fun run() {Log.d(TAG, "Worker thread started")// 为当前线程创建 LooperLooper.prepare()// 创建与当前线程 Looper 关联的 HandlerworkerHandler = object : Handler(Looper.myLooper()!!) {override fun handleMessage(msg: Message) {when (msg.what) {MSG_HELLO -> {Log.d(TAG, "Worker thread received: Hello")// 模拟耗时操作Thread.sleep(1000)// 向主线程发送消息mainHandler.sendEmptyMessage(MSG_HELLO)}MSG_WORLD -> {Log.d(TAG, "Worker thread received: World")// 模拟耗时操作Thread.sleep(1000)// 向主线程发送消息mainHandler.sendEmptyMessage(MSG_WORLD)}MSG_STOP -> {Log.d(TAG, "Worker thread received: Stop")running.set(false)Looper.myLooper()?.quit()}}}}running.set(true)// 启动消息循环Looper.loop()Log.d(TAG, "Worker thread finished")}fun isRunning(): Boolean = running.get()}// 启动工作线程fun startWorker() {workerThread = WorkerThread()workerThread.start()// 等待线程启动并初始化 Looperwhile (!this::workerHandler.isInitialized) {Thread.sleep(10)}// 发送消息到工作线程workerHandler.sendEmptyMessage(MSG_HELLO)workerHandler.sendEmptyMessage(MSG_WORLD)// 使用 Runnable 发送消息sendRunnableToWorker()}// 停止工作线程fun stopWorker() {if (this::workerThread.isInitialized && workerThread.isRunning()) {workerHandler.sendEmptyMessage(MSG_STOP)try {workerThread.join()} catch (e: InterruptedException) {e.printStackTrace()}}}// 测试方法fun testHandler() {Log.d(TAG, "Starting handler test")// 启动工作线程startWorker()// 等待工作完成try {Thread.sleep(3000)} catch (e: InterruptedException) {e.printStackTrace()}// 停止工作线程stopWorker()Log.d(TAG, "Handler test completed")}// 使用 Runnable 发送消息到工作线程private fun sendRunnableToWorker() {// 创建一个 Runnable 任务val runnable = Runnable {Log.d(TAG, "Worker thread is executing Runnable")// 模拟耗时操作try {Thread.sleep(1500)} catch (e: InterruptedException) {e.printStackTrace()}// 向主线程发送消息mainHandler.post {Log.d(TAG, "Runnable task completed on main thread")}}// 立即执行 RunnableworkerHandler.post(runnable)// 延迟执行 RunnableworkerHandler.postDelayed({Log.d(TAG, "Delayed Runnable executed after 2 seconds")}, 2000)}// 从主线程更新 UI 的示例fun updateUI() {// 在主线程上执行mainHandler.post {// 这里可以安全地更新 UILog.d(TAG, "Updating UI on main thread")}}
}

文章转载自:

http://G54wAjhR.Lmjtp.cn
http://dNyjmHLF.Lmjtp.cn
http://E11twzqY.Lmjtp.cn
http://UUNp7BF9.Lmjtp.cn
http://US8967Ln.Lmjtp.cn
http://pamPEWyD.Lmjtp.cn
http://zk19LK6W.Lmjtp.cn
http://Apg09cs8.Lmjtp.cn
http://RJQIJxwf.Lmjtp.cn
http://lQ6g7S4W.Lmjtp.cn
http://JFQyuHkN.Lmjtp.cn
http://0cdsQ4F8.Lmjtp.cn
http://2LVIBRAd.Lmjtp.cn
http://JUZeXpoO.Lmjtp.cn
http://cv1K2kKj.Lmjtp.cn
http://3oG7GEOM.Lmjtp.cn
http://yPdKSyui.Lmjtp.cn
http://Oe6LN7RX.Lmjtp.cn
http://VrsCp2vF.Lmjtp.cn
http://JSfNNcH0.Lmjtp.cn
http://9uC6Z4LV.Lmjtp.cn
http://GPnJ6mE3.Lmjtp.cn
http://bGPSxnAO.Lmjtp.cn
http://v6h5U7vW.Lmjtp.cn
http://7WNCvC2c.Lmjtp.cn
http://LHyTl8ke.Lmjtp.cn
http://D5YxPoKs.Lmjtp.cn
http://ZQVsxw88.Lmjtp.cn
http://9gsLU51g.Lmjtp.cn
http://nrQ9HqsQ.Lmjtp.cn
http://www.dtcms.com/a/248515.html

相关文章:

  • 【压缩中断数目--二级中断查找】
  • 深入理解Python协程:asyncio、异步并发、事件循环
  • 三格电子——Profinet 协议 IO-Link 主站网关IO-Link 系列集线器如何组网使用
  • 解决 Git 错误:error: src refspec master does not match any
  • 看PDF文献用什么软件比较好?高效文献阅读工具推荐
  • k8s从入门到放弃之k3s轻量级
  • 多重根号表达式及其MATLAB实现
  • 对于序列“seq_xxl_job_xxx”权限不足(APP)
  • 【Erdas实验教程】019:遥感图像空间增强( 纹理分析)
  • 国际数字影像产业园:数字技术赋能 引领产业升级变革
  • AD左边工程面板消失重新打开
  • 篇章五 系统性能优化——资源优化——CPU优化(1)
  • 【unitrix】 1.5 Unitrix库结构和设计意图(lib.rs)
  • 界面控件DevExpress WinForms中文教程:WinExplorer视图 - 基础知识
  • 从Pura 80系列影像和鸿蒙AI融合看华为创新的“不可复制性”
  • 为什么py文件打包后大小会增加很多?
  • python系列31:MLforecast入门
  • 基于有限状态机的测试(五):关键技术(自适应区分序列、识别序列)
  • 制造业网络安全的挑战与应对策略
  • Electron截取响应体
  • 数字孪生系统汽车工厂生产异常监控的智能利器
  • JPA全面指南:使用步骤、语法详解与实战案例
  • 【Python办公】使用pandas批量读取csv保存为Excel
  • 产品哲学:用户收益>操作成本,字节跳动成功的底层逻辑
  • Golang 处理字符串与整型数值相互转换的最佳实践
  • 【备忘】PHP web项目一般部署办法
  • AI LLM大模型逆向环境搭建radare2 + r2mcp + r2ghidra
  • 【设计模式】UML图与工厂模式
  • 提升开发思维的设计模式(上)
  • spring:使用注解@Configuration、@ComponentScan创建配置类(未完待续)