ANR概念
Android ANR全称是Application No Responding,即应用无响应。如果主线程即UI线程在规定时间没有处理完相应工作便会发生ANR,而具体来说便是以下四类事件
KeyDispatchTimeout:输入和触摸事件在5s内未得到响应
BroadcastTimeout:BroadcastReceiver广播的onReceiver方法在规定时间(前台10s,后台60s)未处理完
ServiceTimeout:Service服务在规定时间(前台20s,后台200s)未成功启动
ProcessContentProviderPublishTimeOutLocked:ContentProvider的publish在10s内未处理完
这里贴一下这些时间的源码定义
// How long we wait until we timeout on key dispatching.
static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
// How long we allow a receiver to run before giving up on it.
static final int BROADCAST_FG_TIMEOUT = 10*1000; // 前台
static final int BROADCAST_BG_TIMEOUT = 60*1000; // 后台
// How long we wait for a service to finish executing.
static final int SERVICE_TIMEOUT = 20*1000; // 前台
// How long we wait for a service to finish executing.
static final int SERVICE_BACKGROUND_TIMEOUT = SERVICE_TIMEOUT * 10; // 后台
// How long we wait for an attached process to publish its content providers
// before we decide it must be hung.
static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT = 10*1000;
而ANR的具体触发原理可以看这篇博客理解Android ANR的触发原理,后续再跟着这篇博客进一步学习ANR触发机制源码
当ANR发生时如何定位原因呢
当ANR发生时,Android会在Loacat中打印日志,内容包括
导致ANR的类名及所在包名,例如MainActivity,org.wolf.anrtest
发生ANR的进程名称及ID,例如org.wolf.anrtest,8645
ANR的类型(即发生原因),例如Input dispatching time out,则属于KeyDispatchTimeout类型
系统中活跃进程的CPU占有率,例如1.8% 8645/org.wolf.anrtest:0.8% user+0.5% kernel/faults:8215 minor 16 major.
并且会生成/data/anr/traces.txt文件记录更多详细信息