美文网首页
Android ANR机制

Android ANR机制

作者: Amber_9 | 来源:发表于2023-10-15 01:39 被阅读0次

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

    一.输入事件无响应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处理;

    相关文章

      网友评论

          本文标题:Android ANR机制

          本文链接:https://www.haomeiwen.com/subject/mkctidtx.html