Android ANR机制

大致有四种类型,下面逐一介绍:

一.输入事件无响应ANR

调用过程:

(InputDispatcher#) dispatchMotionLocked --> findFocusedWindowTargetsLocked--> onANRLocked --> doNotifyANRLockedInterruptible -->
(InputDispatcherPolicyInterface#)mPolicy->notifyANR --> (NativeInputManager(:public InputDispatcherPolicyInterface)#)notifyANR -->
(InputManagerService#) notifyANR --> (InputManagerCallback: WindowManagerCallbacks#)mWindowManagerCallbacks.notifyANR( token, reason) -->
(AMS#)mService.mAmInternal.inputDispatchingTimedOut(windowState.mSession.mPid, aboveSystem, reason) --> (ProcessRecord#)proc.appNotResponding(activityShortComponentName, aInfo,parentShortComponentName, parentProcess, aboveSystem, annotation);

部分源码:

int32_t InputDispatcher::findFocusedWindowTargetsLocked(...) {
    ...
    if(focusedWindowHandle==null){
        // If there is no currently then drop the event. 
        handleTargetsNotReadyLocked{
            if(currentTime >= currentTime +DEFAULT_INPUT_DISPATCHING_TIMEOUT){
                //如果超过DEFAULT_INPUT_DISPATCHING_TIMEOUT也就是5s    
                onANRLocked();
            }
        }
    } 
    ...
}
(ProcessRecord#) void appNotResponding(String activityShortComponentName, ApplicationInfo aInfo,String parentShortComponentName, WindowProcessController parentProcess,boolean aboveSystem, String annotation) {
    ...
    //部分情况只标记不处理,比如开关机过程中的输入事件
    // 记录anr日志
    ActivityManagerService.dumpStackTraces:{...
        final File tracesDir = new File(“/data/anr/anr_xx”);
    }
    //是否是静默ANR(一般情况都会弹出ANR对话框,除非已经配置了不让弹出对话框,这种情况直接在后台进行杀死进程的操作)
    //如果是静默ANR:直接杀掉进程
    kill();
    //否则,弹出ANR对话框
    (AppErrors#) mAppErrors.handleShowAnrUi(msg){
        ...
        anrDialog = new AppNotRespondingDialog;anrDialog.show();
        //选择强制关闭杀掉进程
        mService.killAppAtUsersRequest(mProc, AppNotRespondingDialog.this);
        //选择等待,会等待APP相应并上报给AMS更新lastANR等相关信息
        mService.mServices.scheduleServiceTimeoutLocked(app);
    }
}

小结:

  1. 当输入事件派发时超过5S没有获取到目标(当前焦点)窗口,且当前应用进程未结束,(比如输入事件时应用进程主线程阻塞时间超过5S);
  2. 输入事件的派发顺序:(SS#)InputDispatcher线程 --> InputMangerService --> WindowMangerService --> (APP#)PhoneWindow -->
    ViewRootImpl --> View;

二.广播处理时间过久

调用过程:

(BroadcastQueue#) processNextBroadcastLocked() -->
-->1)if ((numReceivers > 0) && (now > r.dispatchTime + (2 * mConstants.TIMEOUT * numReceivers)) --> broadcastTimeoutLocked(false) --> (AppNotResponding#)run() --> (ProcessRecord#)appNotResponding();
-->2)setBroadcastTimeoutLocked --> mHandler.sendMessageAtTime(mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this), timeoutTime) --> broadcastTimeoutLocked(true) ...

部分源码:

BroadcastQueue#

static final int BROADCAST_FG_TIMEOUT = 10*1000;
static final int BROADCAST_BG_TIMEOUT = 60*1000;


(BroadcastQueue#) void processNextBroadcastLocked(){
    // First, deliver any non-serialized broadcasts right away. 首先处理并行广播,并行广播没有ANR的问题
    while (mParallelBroadcasts.size() > 0) {
        for (int i=0; i<N; i++) {
                    Object target = r.receivers.get(i);
            deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false, i);
        }
    }
    int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
    if ((numReceivers > 0) &&  (now > r.dispatchTime + (2 * mConstants.TIMEOUT * numReceivers)){
        //如果广播处理的总时间大于2 * mConstants.TIMEOUT * numReceivers, 则直接作为广播处理超时ANR处理       
        broadcastTimeoutLocked(false);  
    }
    if (! mPendingBroadcastTimeoutMessage) {
        long timeoutTime = r.receiverTime + mConstants.TIMEOUT; 
        setBroadcastTimeoutLocked (timeoutTime);
    }
}

(BroadcastQueue#)void broadcastTimeoutLocked(boolean fromMsg){
     mHandler.post(new AppNotResponding(app, anrMessage));
}

(BroadcastQueue$AppNotResponding:Thread#)void run(){
    mApp.appNotResponding(null, null, null, null, false, mAnnotation);//ProcessRecord#appNotResponding 同type1
}

(BroadcastQueue#)void setBroadcastTimeoutLocked(long timeoutTime){
    //预备一个广播处理超时ANR消息处理,延迟timeoutTime发送,在receiver处理完会调用cancelBroadcastTimeoutLocked方法,remove预备的广播处理超时ANR处理。     
    //什么时候执行cancelBroadcastTimeoutLocked?当广播结束会(BroadcastReceiver#).sendFinished ---> (AMS#) finishReceiver -->  r.queue.finishReceiverLocked  --> (BroadcastQueue#) r.queue.processNextBroadcastLocked --> (BroadcastQueue#) cancelBroadcastTimeoutLocked()取消预备处理ANR的消息
    Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
    mHandler.sendMessageAtTime(msg, timeoutTime);
    mPendingBroadcastTimeoutMessage = true;
}

小结:

  1. 并行无序广播处理时间不受ANR管制;
  2. 广播处理总时间大于2 * mConstants.TIMEOUT * numReceivers 会产生ANR;
  3. 单个广播处理时间大于(前台10S,后台60S)产生ANR;
    PS:BroadcastQueue负责广播分发管理。

三.Service ANR:

调用过程:

(AMS#)startService -->

  1. (ActiveServices#)realStartServiceLocked --> bumpServiceExecutingLocked -->(ActivityThread#)app.thread.scheduleCreateService(r, r.serviceInfo,mAm.compatibilityInfoForPackage(r.serviceInfo.applicationInfo) --> service.onCreate();
  2. (ActiveServices#)requestServiceBindingLocked --> bumpServiceExecutingLocked --> (ActivityThread#)r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,r.app.getReportedProcState()) --> (s.onBind(data.intent); or s.onRebind(data.intent);
  3. (ActiveServices#)sendServiceArgsLocked --> bumpServiceExecutingLocked --> (ActivityThread#)r.app.thread.scheduleServiceArgs(r, slice); --> s.onStartCommand()
  4. (ActiveServices#)bringDownServiceLocked --> bumpServiceExecutingLocked --> (ActivityThread#)r.app.thread.scheduleUnbindService(r,ibr.intent.getIntent()); --> s.onUnbind(data.intent);
  5. (ActiveServices#)removeConnectionLocked --> bumpServiceExecutingLocked --> (ActivityThread#)s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent()); --> s.onUnbind(data.intent);
    //bumpServiceExecutingLocked启动ANR机制
    bumpServiceExecutingLocked --> scheduleServiceTimeoutLocked --> mAm.mHandler.sendMessageDelayed(mAm.mHandler.obtainMessage(ActivityManagerService.SERVICE_TIMEOUT_MSG),proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT)
    --> (AMS#) handle --> (ActiveServices#)serviceTimeout(proc) --> proc.appNotResponding();...(同type1)
    //以上调用表明在Service的onCreate、onStartCommand、onStart、onBind、onUnbind,这几个方法都有ANR处理超时机制
    //当Service的onCreate、onStartCommand、onStart等方法执行完成后,通过 (ActiveServices#)serviceDoneExecutingLocked方法取消之前预备ANR处理消息。

部分源码:

// 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;

(ActiveServices#)void bumpServiceExecutingLocked(){
    // For b/34123235: Services within the system server won't start until SystemServer does Looper.loop(), so we shouldn't try to start/bind to them too early in the boot process. However, since there's a little point of showing the ANR dialog in that case, let's suppress the timeout until PHASE_THIRD_PARTY_APPS_CAN_START. (Note there are multiple services start at PHASE_THIRD_PARTY_APPS_CAN_START too, which technically could also trigger this timeout if there's a system server that takes a long time to handle PHASE_THIRD_PARTY_APPS_CAN_START, but that shouldn't happen.)if(mAm.mBootPhase < SystemService.PHASE_THIRD_PARTY_APPS_CAN_START){timeoutNeeded = false} else{timeoutNeeded = true}//在SS的启动阶段不用ANR机制
    if(timeoutNeeded){
        scheduleServiceTimeoutLocked(r.app);
    }
}
    
(ActiveServices#)void scheduleServiceTimeoutLocked(){
    //无论是startService还是bindService都会调用scheduleServiceTimeoutLocked预备一个ANR的处理超时消息,延时发送 
    // 前台服务20s,后台服务200s,service相应方法调用完成后通过调用serviceDoneExecutingLocked取消预备的ANR消息;
    Message msg = mAm.mHandler.obtainMessage(
    ActivityManagerService.SERVICE_TIMEOUT_MSG);
    msg.obj = proc;
    mAm.mHandler.sendMessageDelayed(msg,proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
} 

//若在ANR超时时间内完成业务取消,则不会产生ANR
(ActiveServices#)void serviceDoneExecutingLocked(){
    mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app);
}

小结:

  1. Service的onCreate、onStartCommand、onStart、onBind、onRebind方法都有ANR机制,一旦处理超时就会抛出ANR异常。

四.ContentProvider Timeout

调用过程:

(ContentProviderClient#) query/insert/delete/update等函数中会在业务处理前调用beforeRemote函数:延时mAnrTimeout后发出ANR处理超时的消息,在这些query等函数业务处理后调用afterRemote取消预备发送的ANR消息。
mAnrTimeout值可通过mProviderClient.setDetectNotResponding(long timeout)函数进行设置:0表示无限期,不采取ANR行动。
(ContentProviderClient#)beforeRemote() --> (ContentResolver#) mContentResolver.appNotRespondingViaProvider(mContentProvider); -->
(ActivityThread#)mMainThread.appNotRespondingViaProvider(icp.asBinder()) --> (AMS#)ActivityManager.getService().appNotRespondingViaProvider(prc.holder.connection) -->
(ProcessRecord)conn.provider.proc.appNotResponding(null, null, null, null, false, "ContentProvider not responding");

部分源码:

(ContentProviderClient#)void  beforeRemote(){
    sAnrHandler.postDelayed(mAnrRunnable, mAnrTimeout);
}
(ContentProviderClient#)void afterRemote() {
    if (mAnrRunnable != null) {
        ///insert/delete/update等函数中会在处理后调用afterRemote取消预备ANR处理超时的消息
            sAnrHandler.removeCallbacks(mAnrRunnable);
    }
}

小结:

  1. 通过ContentProviderClient#setDetectNotResponding(long timeout)函数可以自主设置触发ANR的时间,timeout表示允许挂起调用的持续时间,在远程提供者被认为是无响应的时间,也就是ANR的超时时间, 0表示无限期,不采取ANR行动。
    2.ContentProvider默认是无ANR超时期限的,不采取ANR处理;
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,826评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,968评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,234评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,562评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,611评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,482评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,271评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,166评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,608评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,814评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,926评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,644评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,249评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,866评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,991评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,063评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,871评论 2 354

推荐阅读更多精彩内容