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

Android IdleHandler闲时加载

在之前的文章里,我们讲过关于handler的一些使用和原理。

Android Handler全使用

Android Handler原理源码全解析

今天讲一个系统预留的一个handler,IdleHandler,有了它,可以让我们在系统闲时进行一些预加载或者事务处理。

使用方式

Looper.myQueue().addIdleHandler(new IdleHandler() {@Overridepublic boolean queueIdle() {//具体的业务逻辑return false;}
}

需要注意的是,这里的返回值,可以为true也可以为false。

区别在于,return false代表该闲时任务仅执行一次。return true代表只要系统闲,就会反复执行多次。

原理

在MessageQueue.java中,有idleHandler的添加与移除

/*** Callback interface for discovering when a thread is going to block* waiting for more messages.*/
public static interface IdleHandler {/*** Called when the message queue has run out of messages and will now* wait for more.  Return true to keep your idle handler active, false* to have it removed.  This may be called if there are still messages* pending in the queue, but they are all scheduled to be dispatched* after the current time.*/boolean queueIdle();
}/*** Add a new {@link IdleHandler} to this message queue.  This may be* removed automatically for you by returning false from* {@link IdleHandler#queueIdle IdleHandler.queueIdle()} when it is* invoked, or explicitly removing it with {@link #removeIdleHandler}.** <p>This method is safe to call from any thread.** @param handler The IdleHandler to be added.*/
public void addIdleHandler(@NonNull IdleHandler handler) {if (handler == null) {throw new NullPointerException("Can't add a null IdleHandler");}synchronized (this) {mIdleHandlers.add(handler);}
}/*** Remove an {@link IdleHandler} from the queue that was previously added* with {@link #addIdleHandler}.  If the given object is not currently* in the idle list, nothing is done.** <p>This method is safe to call from any thread.** @param handler The IdleHandler to be removed.*/
public void removeIdleHandler(@NonNull IdleHandler handler) {synchronized (this) {mIdleHandlers.remove(handler);}
}

在MessageQueue的next方法中

Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after
// quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {return null;
}int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {if (nextPollTimeoutMillis != 0) {Binder.flushPendingCommands();}nativePollOnce(ptr, nextPollTimeoutMillis);synchronized (this) {// Try to retrieve the next message. Return if found.final long now = SystemClock.uptimeMillis();Message prevMsg = null;Message msg = mMessages;if (msg != null && msg.target == null) {// Stalled by a barrier. Find the next asynchronous message// in the queue.// 这里执行的操作是忽略所有的同步消息, 知道找出queue中的异步消息// 我理解是这个的同步消息会造成线程的阻塞, 所以忽略同步的消息do {prevMsg = msg;msg = msg.next;} while (msg != null && !msg.isAsynchronous());}// 走到这一步, 有两种可能,// 一种是遍历到队尾没有发现异步消息,// 另一种是找到queue中的第一个异步消息if (msg != null) {// 找到queue中的第一个异步消息if (now < msg.when) {// Next message is not ready. Set a timeout to wake up// when it is ready.// 没有到消息的执行时间nextPollTimeoutMillis = (int) Math.min(msg.when - now,Integer.MAX_VALUE);} else {// Got a message.// 当前消息到达可以执行的时间, 直接返回这个msgmBlocked = false;if (prevMsg != null) {prevMsg.next = msg.next;} else {mMessages = msg.next;}msg.next = null;if (DEBUG)Log.v(TAG, "Returning message: " + msg);msg.markInUse();return msg;}} else {// 遍历到队尾, 没有发现异步消息或者没有消息了// No more messages.nextPollTimeoutMillis = -1;}// Process the quit message now that all pending messages have// been handled.// 检查当前的线程是否退出if (mQuitting) {dispose();return null;}// If first time idle, then get the number of idlers to run.// Idle handles only run if the queue is empty or if the first// message// in the queue (possibly a barrier) is due to be handled in the// future.// 如果queue中没有msg, 或者msg没到可执行的时间,// 那么现在线程就处于空闲时间了, 可以执行IdleHandler了if (pendingIdleHandlerCount < 0&& (mMessages == null || now < mMessages.when)) {// pendingIdleHandlerCount在进入for循环之前是被初始化为-1的// 并且没有更多地消息要进行处理pendingIdleHandlerCount = mIdleHandlers.size();}if (pendingIdleHandlerCount <= 0) {// No idle handlers to run. Loop and wait some more.// 如果没有IdleHandler要进行处理, 则直接进入下次循环mBlocked = true;continue;}if (mPendingIdleHandlers == null) {mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];}mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);}// Run the idle handlers.// We only ever reach this code block during the first iteration.// 退出同步块, 接下来就可以执行IdleHandler的相关操作了for (int i = 0; i < pendingIdleHandlerCount; i++) {final IdleHandler idler = mPendingIdleHandlers[i];mPendingIdleHandlers[i] = null; // release the reference to the// handlerboolean keep = false;try {keep = idler.queueIdle();} catch (Throwable t) {Log.wtf(TAG, "IdleHandler threw exception", t);}if (!keep) {// 如果之前addIdleHandler中返回为false,// 就在执行完这个IdleHandler的callback之后, 将这个idler移除掉synchronized (this) {mIdleHandlers.remove(idler);}}}// Reset the idle handler count to 0 so we do not run them again.// 全部执行完, 重新设置这个值为0, 以便下次可以再次执行pendingIdleHandlerCount = 0;// While calling an idle handler, a new message could have been// delivered// so go back and look again for a pending message without waiting.nextPollTimeoutMillis = 0;
}
}

从代码,可以看出,判断闲时的逻辑,即可以处理idleHandler的时机是:

如果queue中没有msg, 或者msg没到可执行的时间, 此时线程就处于空闲时间了,可以执行IdleHandler了

相关文章:

  • 《Python机器学习原理与算法实现》学习笔记
  • redis—List列表
  • MySQL:主从复制
  • 【项目】玩具租赁博客测试报告
  • 每日一题(LeetCode)----二叉树-- 二叉树的右视图
  • 【智慧门店】东胜物联蓝牙网关助力解决方案商,推动汽车后市场企业智能化升级
  • Java:基本类型及它们的封装类
  • 复试 || 就业day05(2023.12.31)算法篇
  • SpringCloud(H版alibaba)框架开发教程,使用eureka,zookeeper,consul,nacos做注册中心——附源码(1)
  • IntelliJ IDEA [插件 MybatisX] mapper和xml间跳转
  • 【Spring Security】AuthenticationFailureHandler 用户认证失败后处理
  • 数据特征工程 | PSO粒子群算法的特征选择原理及python代码实现
  • web component - 使用HTML Templates和Shadow DOM构建现代UI组件
  • [BUG]Datax写入数据到psql报不能序列化特殊字符
  • C# MVC +Layui侧边导航栏的收缩及展开
  • “寒冬”下的金三银四跳槽季来了,帮你客观分析一下局面
  • 【vuex入门系列02】mutation接收单个参数和多个参数
  • CSS实用技巧
  • Javascript基础之Array数组API
  • Markdown 语法简单说明
  • mysql外键的使用
  • PAT A1092
  • webpack+react项目初体验——记录我的webpack环境配置
  • weex踩坑之旅第一弹 ~ 搭建具有入口文件的weex脚手架
  • 搞机器学习要哪些技能
  • 前端技术周刊 2018-12-10:前端自动化测试
  • 让你成为前端,后端或全栈开发程序员的进阶指南,一门学到老的技术
  • 扫描识别控件Dynamic Web TWAIN v12.2发布,改进SSL证书
  • 微信小程序上拉加载:onReachBottom详解+设置触发距离
  • 怎样选择前端框架
  • ​DB-Engines 12月数据库排名: PostgreSQL有望获得「2020年度数据库」荣誉?
  • # 手柄编程_北通阿修罗3动手评:一款兼具功能、操控性的电竞手柄
  • (¥1011)-(一千零一拾一元整)输出
  • (2)空速传感器
  • (2024最新)CentOS 7上在线安装MySQL 5.7|喂饭级教程
  • (C++17) optional的使用
  • (java版)排序算法----【冒泡,选择,插入,希尔,快速排序,归并排序,基数排序】超详细~~
  • (Oracle)SQL优化技巧(一):分页查询
  • (Redis使用系列) SpirngBoot中关于Redis的值的各种方式的存储与取出 三
  • (分享)一个图片添加水印的小demo的页面,可自定义样式
  • (五)Python 垃圾回收机制
  • (五)网络优化与超参数选择--九五小庞
  • (续)使用Django搭建一个完整的项目(Centos7+Nginx)
  • (原創) 是否该学PetShop将Model和BLL分开? (.NET) (N-Tier) (PetShop) (OO)
  • (自用)learnOpenGL学习总结-高级OpenGL-抗锯齿
  • .net framework profiles /.net framework 配置
  • .net 重复调用webservice_Java RMI 远程调用详解,优劣势说明
  • .net获取当前url各种属性(文件名、参数、域名 等)的方法
  • .php文件都打不开,打不开php文件怎么办
  • [ CTF ] WriteUp- 2022年第三届“网鼎杯”网络安全大赛(朱雀组)
  • [ 手记 ] 关于tomcat开机启动设置问题
  • [<死锁专题>]
  • [AIGC] SQL中的数据添加和操作:数据类型介绍
  • [ASP.NET MVC]Ajax与CustomErrors的尴尬
  • [BFS广搜]迷阵