一.ANR的种类
1.1 ANR定义
Application Not Responding:即应用无响应
如果应用程序主线程在超时时间内对输入事件没有处理完毕,或者对特定操作没有执行完毕,就会出现ANR
(主线程在特定的时间内没有做完特定的事情)
1.2.ANR类型
1) KeyDispatchTimeout :
主要类型按键或触摸事件,input事件在5S内没有处理完成发生ANR,关键Log:Reason: Input dispatching timed out xxxx
2)ServiceTimeout
Service主线程处理耗时,前台Service在20s内,后台Service在200s内没有处理完成发生ANR,关键Log:Timeout executing service:/executing service XXX
3)BroadcastTimeout
前台广播在10S内,后台广播在60s内没有被所有接收器处理完成发生ANR,关键Log:Timeout of broadcast XXX/Receiver during timeout:XXX/Broadcast of XXX
4)ProcessContentProviderPublishTimedOutLocked
ContentProvider publish在10s内没有处理完成发生ANR,关键log:timeout publishing content providers
1.3.常见的原因
A.主线程耗时操作,如复杂的layout,庞大的for循环,IO等。
B.主线程被子线程同步锁block
C.主线程被Binder 对端block
D.Binder被占满导致主线程无法和SystemServer通信
E.得不到系统资源(CPU/RAM/IO)
二.ANR的原理简化
2.0 ANR dialog显示过程
2.1 KeyDispatchTimeout
InpuntManagerService会起两个线程InputReader线程和InputDispatcherThread,InputDispatcherThread线程会由reader线程wake,起来后就threadloop不断循环读取input事件。
2.2 ServiceTimeout
2.3 BroadcastTimeout
2.4 ContentProvider PublishTimedout
三.总结
附上上面使用draw.io绘制的流程图原稿以及下面详细流程图的uml文件:
https://pan.baidu.com/s/1tp0Gc2GZQXNysut9hkejIA
anr_simplify.xml 是上面的流程图原稿,使用draw.io导入即可
uml文件使用安装plantuml插件的intellij或AndroidStudio打开即可
如有问题或需要提醒自己注意的读者可自行添加
详细过程:
1.ANR dialog显示过程
2.InputDispatch timeout
3.Service timeout
4.Broadcast timeout
5.ContentProvider publish timeout
网友评论