整体架构
触摸屏幕的时候,Linux内核往设备节点写数据
EventHub会监听设备节点文件
InputReader无限循环,从EventHub中读取事件,加工后把事件放入InputDispatcher队列
InputDispatcher无限循环,从InputDispatcher中取出事件,找到合适的Window,把事件写入这个Window的InputChannel
随后串口端的Looper会被唤醒
派发架构
以下是3个队列的流转流程,简单记为A、B、C队列
原理
简而言之,并不是第一次发起点击事件就会报ANR的
发起一次后就不管了
只有当后面发起了,且检测到前一次超时了,这个时候才算ANR
这个时候可以再深思一下,什么时候,会超时
先明确一个概念,输入事件的处理,作为Handler中的一个msg
然后超时其实有2个因素:
1、输入事件msg前可能还有另外的msg没有处理完
2、输入事件msg自身执行的时间
所以得出公式:ANR = preMessageTime + inputMessageTime
侧面也反映一个道理,输入事件超时,不一定因为输入事件太耗时,可能是其他msg的影响,也可能是两者的共同作用
因此有时候看到ANR堆栈并不从onClick发起也不要太过惊奇
如何定位ANR?
发生ANR时,系统会输出2个比较重要的信息
- longMsg
- 堆栈
堆栈是最友好的信息,但是它不一定准,很多时候你会看到不相关甚至是nativePollOnce这样的正常堆栈(不准的原因是无法精确确保AMS打印堆栈时机和ANR代码处时机一致,毕竟在2个进程,而且逻辑上还是通信上都有一些时差)
所以longMsg就显得很重要
Service、ContentProvider、Broadcast的原理是某个生命周期执行超时,longMsg会输出具体的堆栈和生命周期方法
我们可以找到对应的生命周期方法,给其method做trace分析,即可定位得八九不离十
而输入事件的longMsg则要复杂得多,所以下面展开对longMsg的分析
longMsg分析
1、Waiting because no window has focus but there is a focused application that may eventually add a window when it finishes starting up.
InputChannel在onResume后创建,所以很可能onCreate、onStart、onResume执行耗时逻辑,会引起这一点
2、Waiting because the [targetType] window is paused.
窗口暂停
3、Waiting because the [targetType] window’s input channel is not registered with the input dispatcher. The window may be in the process of being removed.
窗口为连接,窗口所在的进程可能正在被移除
4、Waiting because the [targetType] window’s input connection is [Connection.Status]. The window may be in the process of being removed.
窗口连接已死亡,窗口所在的进程可能正在被移除
5、Waiting because the [targetType] window’s input channel is full. Outbound queue length: [outboundQueue长度]. Wait queue length: [waitQueue长度].
窗口连接已满
6、Waiting to send key event because the [targetType] window has not finished processing all of the input events that were previously delivered to it. Outbound queue length: [outboundQueue长度]. Wait queue length: [waitQueue长度].
点击事件超时
7、Waiting to send non-key event because the [targetType] window has not finished processing certain input events that were delivered to it over 500ms ago. Wait queue length: [waitQueue长度]. Wait queue head age: [等待时长].
触摸事件超时
其中2,3,4,5目前没发现触发条件,可能是比较极端的情况,很少见到
1,6,7是比较清楚的,但是6,7又得不到任何有用的结论
综上只有1的情况,可以得知,很可能是Activity生命周期超时引起的
后记
学习自
http://gityuan.com/2019/04/06/android-anr/
http://gityuan.com/2017/01/01/input-anr/
有什么写得错误、让人费解或遗漏的地方,希望可以不吝赐教,我会马上更改