Android 深入理解 ANR 触发原理:Service

Android中的StatsLog 在看NFC代码时,有一个直接找找不到的类叫NfcStatsLog,查看Android.bp发现有这么一段: genrule { name: "statslog-Nfc-java-gen", tools: ["stats-log-api-gen"], cmd: "$(location stats-log-api-gen) --java $(out) --module nfc --javaPackage com.android.nfc" + " --javaClass N... 阅读详情
AI摘要

本文详细解析了ANR(应用未响应)在Android中的原因,重点关注ServiceTimeout,服务启动过程,以及ANR触发条件和系统处理机制。涵盖了前台服务与后台服务的区别、服务超时后的ANR处理流程和日志输出。

一、概述

       ANR(Application Not responding),是指应用程序未响应,Android系统对于一些事件需要在一定的时间范围内完成,如果超过预定时间能未能得到有效响应或者响应时间过长,都会造成ANR。一般地,这时往往会弹出一个提示框,告知用户当前xxx未响应,用户可选择继续等待或者Force Close,并不是所有的ANR都会有提示框,文字后面会给出答案

那么哪些场景会造成ANR呢?

  • Service Timeout:比如前台服务在20s内未执行完成,后台服务60s未完成;
  • BroadcastQueue Timeout:比如前台广播在10s内未执行完成,后台广播200s未完成
  • ContentProvider Timeout:内容提供者,在publish过超时10s;
  • InputDispatching Timeout: 输入事件分发超时5s,包括按键和触摸事件。

二、Service Timeout的情况:

  2.1 

Service Timeout是位于”ActivityManager”线程中的AMS.MainHandler收到SERVICE_TIMEOUT_MSG消息时触发。

对于Service有两类:

  • 对于前台服务,则超时为SERVICE_TIMEOUT = 20s;

  • 对于后台服务,则超时为SERVICE_BACKGROUND_TIMEOUT = 200s

由变量ProcessRecord.execServicesFg来决定是否前台启动

2.2 startService

   其中在Service进程attach到system_server进程的过程中会调用realStartServiceLocked()方法

 private final void realStartServiceLocked(ServiceRecord r,
            ProcessRecord app, boolean execInFg) throws RemoteException {
        if (app.thread == null) {
            throw new RemoteException();
        }
        if (DEBUG_MU)
            Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
                    + ", ProcessRecord.uid = " + app.uid);
        r.setProcess(app);
        r.restartTime = r.lastActivity = SystemClock.uptimeMillis();

        final boolean newService = app.services.add(r);
		//
        bumpServiceExecutingLocked(r, execInFg, "create");
        mAm.updateLruProcessLocked(app, false, null);
        updateServiceForegroundLocked(r.app, /* oomAdj= */ false);
        mAm.updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_START_SERVICE);

        boolean created = false;
        try {
            if (LOG_SERVICE_START_STOP) {
                String nameTerm;
                int lastPeriod = r.shortInstanceName.lastIndexOf('.');
                nameTerm = lastPeriod >= 0 ? r.shortInstanceName.substring(lastPeriod)
                        : r.shortInstanceName;
                EventLogTags.writeAmCreateService(
                        r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid);
            }
            StatsLog.write(StatsLog.SERVICE_LAUNCH_REPORTED, r.appInfo.uid, r.name.getPackageName(),
                    r.name.getClassName());
            synchronized (r.stats.getBatteryStats()) {
                r.stats.startLaunchedLocked();
            }
            mAm.notifyPackageUse(r.serviceInfo.packageName,
                                 PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
            app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
			//进入ActivityThread,启动service ,ActivityThread是什么呢?所有通过zygote 孵化出来的APP进程启动入口,APP进程孵化出来会执行ActivityThread.main.
            app.thread.scheduleCreateService(r, r.serviceInfo,
                    mAm.compatibilityInfoForPackage(r.serviceInfo.applicationInfo),
                    app.getReportedProcState());
            r.postNotification();
            created = true;
			.......
		}

  上述代码有两个方法比较重要:bumpServiceExecutingLocked和scheduleCreateService,bumpServiceExecutingLocked方法最终会调用 mAm.mHandler.sendMessageDelayed(msg,
                proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT); 发送一个延时message。所以ANR的计时时间就是在bumpServiceExecutingLocked。scheduleCreateService方法是开始把代码挂载到进程中。

private final void bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why) {
        if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, ">>> EXECUTING "
                + why + " of " + r + " in app " + r.app);
        else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, ">>> EXECUTING "
                + why + " of " + r.shortInstanceName);

        // 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.)
        boolean timeoutNeeded = true;
        if ((mAm.mBootPhase < SystemService.PHASE_THIRD_PARTY_APPS_CAN_START)
                && (r.app != null) && (r.app.pid == android.os.Process.myPid())) {

            Slog.w(TAG, "Too early to start/bind service in system_server: Phase=" + mAm.mBootPhase
                    + " " + r.getComponentName());
            timeoutNeeded = false;
        }

        long now = SystemClock.uptimeMillis();
        if (r.executeNesting == 0) {
            r.executeFg = fg;
            ServiceState stracker = r.getTracker();
            if (stracker != null) {
                stracker.setExecuting(true, mAm.mProcessStats.getMemFactorLocked(), now);
            }
            if (r.app != null) {
                r.app.executingServices.add(r);
                r.app.execServicesFg |= fg;
                if (timeoutNeeded && r.app.executingServices.size() == 1) {
                    scheduleServiceTimeoutLocked(r.app);
                }
            }
        } else if (r.app != null && fg && !r.app.execServicesFg) {
            r.app.execServicesFg = true;
            if (timeoutNeeded) {
                scheduleServiceTimeoutLocked(r.app);
            }
        }
        r.executeFg |= fg;//executeFg 判断是否前后进程的依据
        r.executeNesting++;
        r.executingStart = now;//记录service的启动时间
    }
 void scheduleServiceTimeoutLocked(ProcessRecord proc) {
        if (proc.executingServices.size() == 0 || proc.thread == null) {
            return;
        }
        Message msg = mAm.mHandler.obtainMessage(
                ActivityManagerService.SERVICE_TIMEOUT_MSG);
        msg.obj = proc;
		//发生延时message  SERVICE_TIMEOUT_MSG
        mAm.mHandler.sendMessageDelayed(msg,
                proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
        /// M: ANR Debug Mechanism
        mAm.mAnrManager.sendServiceMonitorMessage();
    }

2.3 remove  SERVICE_TIMEOUT_MSG

  那在什么地方会remove  SERVICE_TIMEOUT_MSG?  按我们理解应该是servcie  在执行oncreate的时候吧。结果也是

 private void handleCreateService(CreateServiceData data) {
        // If we are getting ready to gc after going to the background, well
        // we are back active so skip it.
        unscheduleGcIdler();

        LoadedApk packageInfo = getPackageInfoNoCheck(
                data.info.applicationInfo, data.compatInfo);
        Service service = null;
        try {
            java.lang.ClassLoader cl = packageInfo.getClassLoader();
            service = packageInfo.getAppFactory()
                    .instantiateService(cl, data.info.name, data.intent);
        } catch (Exception e) {
            if (!mInstrumentation.onException(service, e)) {
                throw new RuntimeException(
                    "Unable to instantiate service " + data.info.name
                    + ": " + e.toString(), e);
            }
        }

        try {
            if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);

            ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
            context.setOuterContext(service);
//创建Application对象
            Application app = packageInfo.makeApplication(false, mInstrumentation);
            service.attach(context, this, data.info.name, data.token, app,
                    ActivityManager.getService());
            service.onCreate(); //调用服务onCreate()方法
            mServices.put(data.token, service);
            try {
			//移除  SERVICE_TIMEOUT_MSG
                ActivityManager.getService().serviceDoneExecuting(
                        data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
            } catch (RemoteException e) {
                throw e.rethrowFromSystemServer();
            }
        } catch (Exception e) {
            if (!mInstrumentation.onException(service, e)) {
                throw new RuntimeException(
                    "Unable to create service " + data.info.name
                    + ": " + e.toString(), e);
            }
        }
    }
 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
        synchronized(this) {
            if (!(token instanceof ServiceRecord)) {
                Slog.e(TAG, "serviceDoneExecuting: Invalid service token=" + token);
                throw new IllegalArgumentException("Invalid service token");
            }
            mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
        }
    }
 private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying,
            boolean finishing) {
        if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "<<< DONE EXECUTING " + r
                + ": nesting=" + r.executeNesting
                + ", inDestroying=" + inDestroying + ", app=" + r.app);
        else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
                "<<< DONE EXECUTING " + r.shortInstanceName);
        r.executeNesting--;
        if (r.executeNesting <= 0) {
            if (r.app != null) {
                if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
                        "Nesting at 0 of " + r.shortInstanceName);
                r.app.execServicesFg = false;
                r.app.executingServices.remove(r);//service执行完毕就移除。service的添加是在bumpServiceExecutingLocked方法中执行的。
                if (r.app.executingServices.size() == 0) {
                    if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
                            "No more executingServices of " + r.shortInstanceName);
					
//移除SERVICE_TIMEOUT_MSG		                    

mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app);
                    
/// M: ANR Debug Mechanism
                    mAm.mAnrManager.removeServiceMonitorMessage();
                } else if (r.executeFg) {
                    // Need to re-evaluate whether the app still needs to be in the foreground.
                    for (int i=r.app.executingServices.size()-1; i>=0; i--) {
                        if (r.app.executingServices.valueAt(i).executeFg) {
                            r.app.execServicesFg = true;
                            break;
                        }
                    }

service ANR的触发原理很简单,那么思考一个问题,什么样的情况下会触发servcieANR?

答:1.执行代码块的时候Timeout,意思就是,startservcie 到service.oncreate 这段时间超时,比较常见的可能性是oncreate 里面执行比较耗时的代码,或者死锁。2 还有一种情况是机器性能有关,就是当cpu使用率比较高的时候,拿不到或者分配的cpu 时间片段比较小。导致执行超时,这部分就得看trace的打印或者cpuinfo信息。

 

2.4 发生ANR的情况

    思考两个问题:1 如果发生了ANR ,系统会怎么反应,做哪些动作。2.如果发生了ANR系统会输出哪些log,我们从哪些log能判断此时系统是ANR的情况。

    

final class MainHandler extends Handler {
        public MainHandler(Looper looper) {
            super(looper, null, true);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case GC_BACKGROUND_PROCESSES_MSG: {
                synchronized (ActivityManagerService.this) {
                    performAppGcsIfAppropriateLocked();
                }
            } break;
            case SERVICE_TIMEOUT_MSG: {
                /// M: ANR Debug Mechanism @{
                if (mAnrManager.delayMessage(mHandler, msg, SERVICE_TIMEOUT_MSG,
                        ActiveServices.SERVICE_TIMEOUT))
                    return; /// @}
                mServices.serviceTimeout((ProcessRecord)msg.obj);
            } break;
			
void serviceTimeout(ProcessRecord proc) {
        String anrMessage = null;
        synchronized(mAm) {
            if (proc.isDebugging()) {
                // The app's being debugged, ignore timeout.
                return;
            }
            if (proc.executingServices.size() == 0 || proc.thread == null) {
                return;
            }
            final long now = SystemClock.uptimeMillis();
			//区分前台服务还是后台服务
            final long maxTime =  now -
                    (proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
            ServiceRecord timeout = null;
            long nextTime = 0;
			// sr.executingStart是表示servcie 启动的时间,这个时间的赋值是 bumpServiceExecutingLocked 函数里面 r.executingStart = now;
			//proc.executingServices 启动的服务是什么时候被添加到proc.executingServices里面呢?bumpServiceExecutingLocked  r.app.executingServices.add(r);
			//serviceDoneExecutingLocked  r.app.executingServices.remove(r);
            for (int i=proc.executingServices.size()-1; i>=0; i--) {
                ServiceRecord sr = proc.executingServices.valueAt(i);
                if (sr.executingStart < maxTime) {
                    timeout = sr;找到timeout的servcie
                    break;
                }
                if (sr.executingStart > nextTime) {
                    nextTime = sr.executingStart;
                }
            }
			
			//如果有timeout的进程那么就生成anrMessage  最后appNotResponding
            if (timeout != null && mAm.mProcessList.mLruProcesses.contains(proc)) {
                Slog.w(TAG, "Timeout executing service: " + timeout);
                StringWriter sw = new StringWriter();
                PrintWriter pw = new FastPrintWriter(sw, false, 1024);
                pw.println(timeout);
                timeout.dump(pw, "    ");
                pw.close();
                mLastAnrDump = sw.toString();
                mAm.mHandler.removeCallbacks(mLastAnrDumpClearer);
                mAm.mHandler.postDelayed(mLastAnrDumpClearer, LAST_ANR_LIFETIME_DURATION_MSECS);
                anrMessage = "executing service " + timeout.shortInstanceName;
            } else {
                  //如果没有找到timeout的service,那么在nextTime+SERVICE_TIMEOUT时间后再发送SERVICE_TIMEOUT_MSG广播。
                Message msg = mAm.mHandler.obtainMessage(
                        ActivityManagerService.SERVICE_TIMEOUT_MSG);
                msg.obj = proc;
                mAm.mHandler.sendMessageAtTime(msg, proc.execServicesFg
                        ? (nextTime+SERVICE_TIMEOUT) : (nextTime + SERVICE_BACKGROUND_TIMEOUT));
            }
        }

        if (anrMessage != null) {//当找到timeout的service时前面创建好的anrMessage ,把这个anrMessage 交给 proc.appNotResponding处理
            proc.appNotResponding(null, null, null, null, false, anrMessage);
        }
    }
 void appNotResponding(String activityShortComponentName, ApplicationInfo aInfo,
            String parentShortComponentName, WindowProcessController parentProcess,
            boolean aboveSystem, String annotation) {
        ArrayList<Integer> firstPids = new ArrayList<>(5);
        SparseArray<Boolean> lastPids = new SparseArray<>(20);
       
	   //如果有调用ActivityManager.getService().setActivityController方法,也就是自定义发生ANR时,用户处理,那么系统就不做处理,并且杀死进程。
        mWindowProcessController.appEarlyNotResponding(annotation, () -> kill("anr", true));

        long anrTime = SystemClock.uptimeMillis();
        if (isMonitorCpuUsage()) {
            mService.updateCpuStatsNow();//更新CPU的状态
        }

        synchronized (mService) {
            // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
            if (mService.mAtmInternal.isShuttingDown()) {//正在执行关机流程
                Slog.i(TAG, "During shutdown skipping ANR: " + this + " " + annotation);
                return;
            } else if (isNotResponding()) {//相同的进程已经处理过ANR的问题了。
                Slog.i(TAG, "Skipping duplicate ANR: " + this + " " + annotation);
                return;
            } else if (isCrashing()) {//APP crash ,已经被杀死。
                Slog.i(TAG, "Crashing app skipping ANR: " + this + " " + annotation);
                return;
            } else if (killedByAm) {//被AMS杀死,那么什么情况会被AMS杀死呢?内存不足的时候,或者发生了OOM的情况下。AMS 会根据Adj的值来杀死进程,特别是后台进程。
                Slog.i(TAG, "App already killed by AM skipping ANR: " + this + " " + annotation);
                return;
            } else if (killed) {//进程已经死掉,比如之前的  mWindowProcessController.appEarlyNotResponding(annotation, () -> kill("anr", true));
                Slog.i(TAG, "Skipping died app ANR: " + this + " " + annotation);
                return;
            }
			

            // In case we come through here for the same app before completing
            // this one, mark as anring now so we will bail out.
            setNotResponding(true);

            // Log the ANR to the event log.
			//输出Event log   关键字是am_anr 
            EventLog.writeEvent(EventLogTags.AM_ANR, userId, pid, processName, info.flags,
                    annotation);

            // Dump thread traces as quickly as we can, starting with "interesting" processes.
            firstPids.add(pid);//收集进程pid,为后续的dump打印做准备。

            // Don't dump other PIDs if it's a background ANR
			//如果是后台进程就不做处理。
            if (!isSilentAnr()) {
                int parentPid = pid;
                if (parentProcess != null && parentProcess.getPid() > 0) {
                    parentPid = parentProcess.getPid();
                }
                if (parentPid != pid) firstPids.add(parentPid);

                if (MY_PID != pid && MY_PID != parentPid) firstPids.add(MY_PID);

                for (int i = getLruProcessList().size() - 1; i >= 0; i--) {
                    ProcessRecord r = getLruProcessList().get(i);
                    if (r != null && r.thread != null) {
                        int myPid = r.pid;
                        if (myPid > 0 && myPid != pid && myPid != parentPid && myPid != MY_PID) {
                            if (r.isPersistent()) {
                                firstPids.add(myPid);
                                if (DEBUG_ANR) Slog.i(TAG, "Adding persistent proc: " + r);
                            } else if (r.treatLikeActivity) {
                                firstPids.add(myPid);
                                if (DEBUG_ANR) Slog.i(TAG, "Adding likely IME: " + r);
                            } else {
                                lastPids.put(myPid, Boolean.TRUE);
                                if (DEBUG_ANR) Slog.i(TAG, "Adding ANR proc: " + r);
                            }
                        }
                    }
                }
            }
        }

        final ProcessRecord parentPr = parentProcess != null
                ? (ProcessRecord) parentProcess.mOwner : null;

        /// M: ANR Debug Mechanism
		//如果ANRManager处理了,后续就不处理。谷歌的AnrManage.startAnrDump 是没有任何实现方式,所以这部分由各个芯片厂商来自己定义。
		//mtk会开启persist.vendor.anr.enhancement这个属性值来是否自己处理,一般情况是不开启。所以正常情况走谷歌ANR处理流程
        if (mService.mAnrManager.startAnrDump(mService, this, activityShortComponentName, aInfo,
                parentShortComponentName, parentPr, aboveSystem, annotation, getShowBackground(),
                anrTime))
            return;

        // Log the ANR to the main log.
		//ANR log信息的保存。
        StringBuilder info = new StringBuilder();
        info.setLength(0);
        info.append("ANR in ").append(processName);
        if (activityShortComponentName != null) {
            info.append(" (").append(activityShortComponentName).append(")");
        }
        info.append("\n");
        info.append("PID: ").append(pid).append("\n");
        if (annotation != null) {
            info.append("Reason: ").append(annotation).append("\n");
        }
        if (parentShortComponentName != null
                && parentShortComponentName.equals(activityShortComponentName)) {
            info.append("Parent: ").append(parentShortComponentName).append("\n");
        }

        ProcessCpuTracker processCpuTracker = new ProcessCpuTracker(true);

        // don't dump native PIDs for background ANRs unless it is the process of interest
        String[] nativeProcs = null;
		//如果是后台进程,就不dump natvie pid 信息。
        if (isSilentAnr()) {
            for (int i = 0; i < NATIVE_STACKS_OF_INTEREST.length; i++) {
                if (NATIVE_STACKS_OF_INTEREST[i].equals(processName)) {
                    nativeProcs = new String[] { processName };
                    break;
                }
            }
        } else {
            nativeProcs = NATIVE_STACKS_OF_INTEREST;
        }

        int[] pids = nativeProcs == null ? null : Process.getPidsForCommands(nativeProcs);
        ArrayList<Integer> nativePids = null;

        if (pids != null) {
            nativePids = new ArrayList<>(pids.length);
            for (int i : pids) {
                nativePids.add(i);
            }
        }

        // For background ANRs, don't pass the ProcessCpuTracker to
        // avoid spending 1/2 second collecting stats to rank lastPids.
		//开始输出ANR信息到data/anr/trace.txt 文件。,trace.txt 这个文件名称的格式是:anr_yyyy-MM-dd-HH-mm-ss-SSS  ,具体的实现方式可以看AMS  createAnrDumpFile方法
        File tracesFile = ActivityManagerService.dumpStackTraces(firstPids,
                (isSilentAnr()) ? null : processCpuTracker, (isSilentAnr()) ? null : lastPids,
                nativePids);

        String cpuInfo = null;
        if (isMonitorCpuUsage()) {
            mService.updateCpuStatsNow();//更新cpu信息
            synchronized (mService.mProcessCpuTracker) {
                cpuInfo = mService.mProcessCpuTracker.printCurrentState(anrTime);
            }
            info.append(processCpuTracker.printCurrentLoad());
            info.append(cpuInfo);
        }

        info.append(processCpuTracker.printCurrentState(anrTime));

        Slog.e(TAG, info.toString());//打印cpu trace 信息。
        if (tracesFile == null) {//如果创建data/anr/trace.txt的文件失败的话,就杀死进程
            // There is no trace file, so dump (only) the alleged culprit's threads to the log
            Process.sendSignal(pid, Process.SIGNAL_QUIT);
        }

        StatsLog.write(StatsLog.ANR_OCCURRED, uid, processName,
                activityShortComponentName == null ? "unknown": activityShortComponentName,
                annotation,
                (this.info != null) ? (this.info.isInstantApp()
                        ? StatsLog.ANROCCURRED__IS_INSTANT_APP__TRUE
                        : StatsLog.ANROCCURRED__IS_INSTANT_APP__FALSE)
                        : StatsLog.ANROCCURRED__IS_INSTANT_APP__UNAVAILABLE,
                isInterestingToUserLocked()
                        ? StatsLog.ANROCCURRED__FOREGROUND_STATE__FOREGROUND
                        : StatsLog.ANROCCURRED__FOREGROUND_STATE__BACKGROUND,
                getProcessClassEnum(),
                (this.info != null) ? this.info.packageName : "");
				
       //把信息添加到DropBoxManager ,这个时候在main log中能看到 DropBoxManager输出的ANR信息
        mService.addErrorToDropBox("anr", this, processName, activityShortComponentName,
                parentShortComponentName, parentPr, annotation, cpuInfo, tracesFile, null);

        if (mWindowProcessController.appNotResponding(info.toString(), () -> kill("anr", true),
                () -> {
                    synchronized (mService) {
                        mService.mServices.scheduleServiceTimeoutLocked(this);
                    }
                })) {
            return;
        }

        synchronized (mService) {
            // mBatteryStatsService can be null if the AMS is constructed with injector only. This
            // will only happen in tests.
            if (mService.mBatteryStatsService != null) {
                mService.mBatteryStatsService.noteProcessAnr(processName, uid);//通知BatteryStatsService
            }

            if (isSilentAnr() && !isDebugging()) {//如果是后台进程就直接杀死,不会有弹框的情况
                kill("bg anr", true);
                return;
            }

            // Set the app's notResponding state, and look up the errorReportReceiver
            makeAppNotRespondingLocked(activityShortComponentName,
                    annotation != null ? "ANR " + annotation : "ANR", info.toString());

            // mUiHandler can be null if the AMS is constructed with injector only. This will only
            // happen in tests.
			//发送handle 弹出一个AppNotResponding 的对话框。
            if (mService.mUiHandler != null) {
                // Bring up the infamous App Not Responding dialog
                Message msg = Message.obtain();
                msg.what = ActivityManagerService.SHOW_NOT_RESPONDING_UI_MSG;
                msg.obj = new AppNotRespondingDialog.Data(this, aInfo, aboveSystem);

                mService.mUiHandler.sendMessage(msg);
            }
        }
    }
 public boolean appNotResponding(String info, Runnable killAppCallback,
            Runnable serviceTimeoutCallback) {
        Runnable targetRunnable = null;
        synchronized (mAtm.mGlobalLock) {
            if (mAtm.mController == null) {
                return false;
            }

            try {
                // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
                int res = mAtm.mController.appNotResponding(mName, mPid, info);
                if (res != 0) {
                    if (res < 0 && mPid != MY_PID) {
                        targetRunnable = killAppCallback;
                    } else {
                        targetRunnable = serviceTimeoutCallback;
                    }
                }
            } catch (RemoteException e) {
                mAtm.mController = null;
                Watchdog.getInstance().setActivityController(null);
                return false;
            }
        }
        if (targetRunnable != null) {
            targetRunnable.run();
            return true;
        }
        return false;
    }
public static File dumpStackTraces(ArrayList<Integer> firstPids,
            ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids,
            ArrayList<Integer> nativePids) {
        ArrayList<Integer> extraPids = null;

        Slog.i(TAG, "dumpStackTraces pids=" + lastPids + " nativepids=" + nativePids);//输出sys log .

        // Measure CPU usage as soon as we're called in order to get a realistic sampling
        // of the top users at the time of the request.
		//如果是后台进程processCpuTracker=null,也就是后台进程的情况不输出CPU信息
        if (processCpuTracker != null) {
            processCpuTracker.init();
            try {
                Thread.sleep(200);
            } catch (InterruptedException ignored) {
            }

            processCpuTracker.update();

            // We'll take the stack crawls of just the top apps using CPU.
            final int N = processCpuTracker.countWorkingStats();
            extraPids = new ArrayList<>();
            for (int i = 0; i < N && extraPids.size() < 5; i++) {
                ProcessCpuTracker.Stats stats = processCpuTracker.getWorkingStats(i);
                if (lastPids.indexOfKey(stats.pid) >= 0) {
                    if (DEBUG_ANR) Slog.d(TAG, "Collecting stacks for extra pid " + stats.pid);

                    extraPids.add(stats.pid);
                } else {
                    Slog.i(TAG, "Skipping next CPU consuming process, not a java proc: "
                            + stats.pid);
                }
            }
        }

        final File tracesDir = new File(ANR_TRACE_DIR);//创建data/anr 文件。
        // Each set of ANR traces is written to a separate file and dumpstate will process
        // all such files and add them to a captured bug report if they're recent enough.
        maybePruneOldTraces(tracesDir);

        // NOTE: We should consider creating the file in native code atomically once we've
        // gotten rid of the old scheme of dumping and lot of the code that deals with paths
        // can be removed.
        File tracesFile = createAnrDumpFile(tracesDir);//创建anr_yyyy-MM-dd-HH-mm-ss-SSS 格式文件
        if (tracesFile == null) {
            return null;
        }

        dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, nativePids, extraPids);
        return tracesFile;
    }
	
	
	 public static void dumpStackTraces(String tracesFile, ArrayList<Integer> firstPids,
            ArrayList<Integer> nativePids, ArrayList<Integer> extraPids) {

        Slog.i(TAG, "Dumping to " + tracesFile);//输出sys log 

        // We don't need any sort of inotify based monitoring when we're dumping traces via
        // tombstoned. Data is piped to an "intercept" FD installed in tombstoned so we're in full
        // control of all writes to the file in question.

        // We must complete all stack dumps within 20 seconds.
        long remainingTime = 20 * 1000;

        // First collect all of the stacks of the most important pids.
		//输出java 进程的trace 信息到tracesFile
        if (firstPids != null) {
            int num = firstPids.size();
            for (int i = 0; i < num; i++) {
                Slog.i(TAG, "Collecting stacks for pid " + firstPids.get(i));
                final long timeTaken = dumpJavaTracesTombstoned(firstPids.get(i), tracesFile,
                                                                remainingTime);

                remainingTime -= timeTaken;
                if (remainingTime <= 0) {
                    Slog.e(TAG, "Aborting stack trace dump (current firstPid=" + firstPids.get(i) +
                           "); deadline exceeded.");
                    return;
                }

                if (DEBUG_ANR) {
                    Slog.d(TAG, "Done with pid " + firstPids.get(i) + " in " + timeTaken + "ms");
                }
            }
        }

        // Next collect the stacks of the native pids
		//输出native 进程的trace 信息到tracesFile
        if (nativePids != null) {
            for (int pid : nativePids) {
                Slog.i(TAG, "Collecting stacks for native pid " + pid);
                final long nativeDumpTimeoutMs = Math.min(NATIVE_DUMP_TIMEOUT_MS, remainingTime);

                final long start = SystemClock.elapsedRealtime();
                Debug.dumpNativeBacktraceToFileTimeout(
                        pid, tracesFile, (int) (nativeDumpTimeoutMs / 1000));
                final long timeTaken = SystemClock.elapsedRealtime() - start;

                remainingTime -= timeTaken;
                if (remainingTime <= 0) {
                    Slog.e(TAG, "Aborting stack trace dump (current native pid=" + pid +
                        "); deadline exceeded.");
                    return;
                }

                if (DEBUG_ANR) {
                    Slog.d(TAG, "Done with native pid " + pid + " in " + timeTaken + "ms");
                }
            }
        }

        // Lastly, dump stacks for all extra PIDs from the CPU tracker.
        if (extraPids != null) {
            for (int pid : extraPids) {
                Slog.i(TAG, "Collecting stacks for extra pid " + pid);

                final long timeTaken = dumpJavaTracesTombstoned(pid, tracesFile, remainingTime);

                remainingTime -= timeTaken;
                if (remainingTime <= 0) {
                    Slog.e(TAG, "Aborting stack trace dump (current extra pid=" + pid +
                            "); deadline exceeded.");
                    return;
                }

                if (DEBUG_ANR) {
                    Slog.d(TAG, "Done with extra pid " + pid + " in " + timeTaken + "ms");
                }
            }
        }
        Slog.i(TAG, "Done dumping");//输出完毕。
    }
  private static synchronized File createAnrDumpFile(File tracesDir) {
        if (sAnrFileDateFormat == null) {
            sAnrFileDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS");
        }

        final String formattedDate = sAnrFileDateFormat.format(new Date());
        final File anrFile = new File(tracesDir, "anr_" + formattedDate);

        try {
            if (anrFile.createNewFile()) {
                FileUtils.setPermissions(anrFile.getAbsolutePath(), 0600, -1, -1); // -rw-------
                return anrFile;
            } else {
                Slog.w(TAG, "Unable to create ANR dump file: createNewFile failed");
            }
        } catch (IOException ioe) {
            Slog.w(TAG, "Exception creating ANR dump file:", ioe);
        }

        return null;
    }

 

看完上面的代码对刚才提的两个问题已经找到答案,再总结一下

一、 如果发生了ANR ,系统会怎么反应:1.判断是前台进程还是后台进程,如果是前台进程判断超时时间是否大于SERVICE_TIMEOUT(20s),如果是后台进程判断超时时间是否大于SERVICE_BACKGROUND_TIMEOUT(200s)。如果时间没到的话就, mAm.mHandler.sendMessageAtTime(msg, proc.execServicesFg? (nextTime+SERVICE_TIMEOUT)  (nextTime + SERVICE_BACKGROUND_TIMEOUT))。

                                                              2.如果超时,不管是前台进程还是后台进程。创建anrMessage,输出 Slog.w(TAG, "Timeout executing service: " + timeout);把anrMessage给proc.appNotResponding处理。

                                                            3.如果用户有调用ActivityManager.getService().setActivityController,也就是用户自定义处理ANR信息的情况,杀死进程kill("anr", true)。

                                                            4.更新CPU的状态,一些特殊情况下不会输出data/anr/trace 文件,具体情况看前面的代码说明。

                                                            5.输出Event log   关键字是am_anr 

                                                            6 对后台进程会做一些特殊处理,不输出cpu信息,以及pid的trace信息。

                                                            7.如果芯片厂商有自定义了ANRManager 的情况:如果ANRManager处理了,后续就不处理,包括data/anr/trace和弹框。谷歌的AnrManage.startAnrDump 是没有任何实现方式,所以这部分由各个芯片厂商来自己定义。mtk会开启persist.vendor.anr.enhancement这个属性值来是否自己处理,一般情况是不开启。所以正常情况走谷歌ANR处理流程

                                                           8 开始输出ANR信息到data/anr/trace.txt 文件。,trace.txt 这个文件名称的格式是:anr_yyyy-MM-dd-HH-mm-ss-SSS  ,具体的实现方式可以看AMS  createAnrDumpFile方法   

                                                          9 如果是后台进程就直接杀死,不会有弹框的情况。如果是前台进程,发送handle ,弹出一个AppNotResponding 的对话框。

所以在上面需要注意几点信息:1.不是所有的ANR都会有data/anr/trace生成,当用户自己处理ANR的时候,还有trace文件创建失败的情况。2.后台进程是不会有弹框的,会被直接杀死。而且后台进程没有相应的PID trace信息。

 

 

二、.如果发生了ANR系统会输出哪些log,我们从哪些log能判断此时系统是ANR的情况:

                                        1 .   Slog.w(TAG, "Timeout executing service: " + timeout);TAG:ActivityManager

                                        2.   EventLog.writeEvent(EventLogTags.AM_ANR, userId, pid, processName, info.flags,
                    annotation); 这个log的输出在某些情况是不会输出的,用户定义了ANR的处理。还有就是另外几种情况,isShuttingDown ,isNotResponding ,isCrashing ,killedByAm,killed

                                       3. 生成 data/anr/文件,里面保存了一些pid的trace 信息以及cpu信息。

                                      4.DropBoxManager也会输出一些anr的trace信息。

                                     5 如果是前台进程还会有一个AppNotRespondingDialog。

   

 

 

 

 

 

 

Android-Service-ANR-的监控机制,看完这篇彻底明白了 Service 的 Anr监控机制都由那些重量级角色参与 Service 的 Anr监控机制的建立流程是怎样的 Service 的 Anr监控机制的实现原理是什么 我们一般启动一个Service,会调用startService(),我们追进去发现,调用这句话的其实是ContextImpl这个类。ContextImpl前面我们已经讲过了,是Context的子类,跟ContextWrapper是兄弟关系。然后,它调用自己的startServiceCommon()跨进程调用到sys_server进程中的Act. 阅读详情

相关推荐

[Android S] statsd 统计log信息流程

Android S: statsd 统计log信息流程 参考文档: https://source.android.google.cn/devices/architecture/modular-system/statsd https://www.dazhuanlan.com/ostrichmyself/topics/1301914 移动端 Statsd In android 9 (1) https://blog.csdn.net/ho_mgx/article/details/113486753 Android

月山知了的博客 5715

发生ANR之后的事情

触发ANR条件 Service Timeout:前台服务20s内未完成执行,后台服务超过200s BroadcastQueue Timeout:前台广播在10s内未完成,后台广播超过60s未完成 ContentProvider Timeout:内容提供者,在publish过超时10s InputDispatching Timeout: 输入事件分发超时5s,包括按键和触摸事件 对应最后执行ANR记录

我叫王菜鸟 1412

彻底理解Android ANR机制 一篇就够了

不论从事安卓应用开发,还是安卓系统研发,应该都遇到应用无响应(ANR,Application Not Responding)问题,当应用程序一段时间无法及时响应,则会弹出ANR对话框,让用户选择继续等待,还是强制关闭。绝大多数人对ANR的了解仅停留在主线程耗时或CPU繁忙会导致ANR。面试过无数的候选人,几乎没有人能真正从系统级去梳理清晰ANR的来龙去脉,比如有哪些路径会引发ANR?有没有可能主线程不耗时也出现ANR?如何更好的调试ANR?

a546036242的博客 5522

线上应用故障排查之一:高CPU占用

一个应用占用CPU很高,除了确实是计算密集型应用之外,通常原因都是出现了死循环。 (友情提示:本博文章欢迎转载,但请注明出处:hankchen,http://www.blogjava.net/hankchen) 以我们最近出现的一个实际故障为例,介绍怎么定位和解决这类问题。 根据top命令,发现PID为28555的Java进程占用CPU高达200%,出现故障。 通过ps aux |...

经验不在于年限,在于积累---专注互联网软件开发 2119

关于Android中ANR的详解

前言 关于ANR,以前只知道Activity、BroadCastReceiver、Service三种组件的ANR时限、一般采用哪些方式避免ANR、以及通过data/anr/traces.txt去分析ANR原因,感觉好像这就够用了。 但是,前几天看源码的时候,脑海里突然跳出一个问题: ANR是怎么判断的5秒还是10秒? 这个问题迅速扩大为一连串问题: ANR的时间定义在哪些文件里? ANR是怎么计时的? 是谁在监控ANR? 所有的ANR都会弹窗吗? traces.txt能记录多少内容? A

1 461

国土变更调查中六类拓扑错误的成因分析与高效修复实践

本文深入分析了国土变更调查中六类拓扑错误的成因,包括边界不一致和不规则图形等常见问题,并提出了高效的自动化修复实践。通过智能咬合算法、引力-斥力平衡模型等核心技术,显著提升了修复效率,节省人工质检时间70%。文章还分享了实战中的避坑指南和黄金法则,为相关从业人员提供了宝贵经验。

weixin_29202213的博客 360

深入理解 Android ANR 触发原理以及信息收集过程

一、概述 作为 Android 开发者,相信大家都遇到过 ANR。那么为什么会出现 ANR 呢,ANR 之后系统都做了啥。文章将对这个问题详细解说。 ANR(Application Not responding),是指应用程序未响应,Android系统对于一些事件需要在一定的时间范围内完成,如果超过预定时间能未能得到有效响应或者响应时间过长,都会造成ANR。一般地,这时往往会弹出一个提示框,告知用户当前xxx未响应,用户可选择继续等待或者Force Close。 那么哪些场景会造成ANR呢? S

转载和创作优秀的博客 1259

WRF和WPS模型在Ubuntu系统上的安装与常见问题解决指南

本文详细介绍了在Ubuntu系统上安装WRF和WPS模型的完整教程,涵盖系统环境配置、依赖库安装、源代码编译以及常见问题的解决方案。重点解决了WPS编译中intmath.f文件的修改、环境变量设置和编译器兼容性等关键难点,帮助用户高效部署气象研究与预报模型。

weixin_29213525的博客 386

Android12的ANR解析

调用到ProcessErrorStateRecord.appNotResponding来弹出无响应弹出。或者dump操作啥的,就是平时见到的ANR。case 1: 失去焦点时间(mNoFocusedWindowTimeoutTime)过长。case 2: 连接过期,触发ANR, onAnrLocked(connection)处理postCommandLocked写入的 mCommandQueue。捕获 ANR 时 InputDispatcher 状态的记录。向mCommandQueue中写入数据。

zion--6135的博客 1625

如何用Lmcache+vllm优化KVcache存储?CPU与SSD性能实测对比

本文通过实测对比,详细介绍了如何利用Lmcache+vLLM将大模型推理中的KV Cache卸载至CPU内存或SSD硬盘,以解决长上下文场景下的GPU显存瓶颈。测试数据显示,CPU卸载方案在首字延迟(TTFT)上显著优于SSD方案,但SSD方案在存储成本上更具优势。文章提供了完整的配置指南、性能数据分析和生产环境选型建议。

fire9的博客 1003

Pyhon在振动信号处理中的高级应用(一):振动信号特征(时域、频域)提取

文章目录一、概述二、算法原理2.1 时域统计特征三、python代码实现 一、概述 二、算法原理   这里我们借鉴西安交通大学机械学院雷教授的论文《Fault diagnosis of rotating machinery based on multiple ANFIS combination with GAs》相关研究成果。雷教授在论文中共列举了4类共24种振动信号的时域和频域特征。 2.1 时域统计特征 p1=∑n=1Nx(n)NP2=∑n=1N(x(n)−p1)2N−1p3=(∑n=1N∣x(n)∣N

白银时代的博客 1万+

ANR原理及分析

分析ANR步骤 确定ANR基本信息 先搜索am_anr 确定ANR时间点,进程id ,以及什么类型ANR,等待了多久等 03-04 13:45:03.781 1000 1199 14667 I am_anr : [0,2900,com.android.systemui,551042573**,Input dispatching timed ou**t (StatusBar, b49ba2b StatusBar (server) is not responding. Waited 8001ms for Mot

xiaoyantan的博客 4395

即插即用系列(代码实践) | WACV 2024 CSAM:面向各向异性医学图像分割的 2.5D 跨切片注意力模块

文章摘要: 论文《CSAM: A 2.5D Cross-Slice Attention Module for Anisotropic Volumetric Medical Image Segmentation》提出了一种解决医学图像各向异性问题的创新模块CSAM。针对MRI/CT数据中切片间分辨率差异大的挑战,该模块通过2.5D跨切片注意力机制,结合2D卷积的轻量性和3D上下文感知能力。核心包括语义注意力(通道级)、位置注意力(空间级)和跨切片注意力(支持不确定性建模),能在几乎不增加参数量的情况下有效捕捉

分享顶会顶刊论文即插即用模块 119

ANR解决方法研究

前言 不论从事安卓应用开发,还是安卓系统研发,应该都遇到应用无响应(简称ANR)问题,当应用程序一段时间无法及时响应,则会弹出ANR对话框,让用户选择继续等待,还是强制关闭。 绝大多数人对ANR的了解仅停留在主线程耗时或CPU繁忙会导致ANR。面试过无数的候选人,几乎没有人能真正从系统级去梳理清晰ANR的来龙去脉,比如有哪些路径会引发ANR?有没有可能主线程不耗时也出现ANR?如何更好的调试...

zjy764219923的专栏 4223

ADS基础教程23 - 有限元电磁仿真(FEM)可视化操作

一、引言 二、FEM可视化操作流程1.打开可视化界面2.查看介质的网格3.设置网格颜色4.选择网格5.传感器选择6.编辑传感器7.选择频率8.动画 三、总结介绍了在ADS中如何进行FEM仿真场视图操作过程。

XZ_ZC的博客 1824

Allegro格式PCB转换成Pads操作指导

变量:AEX_BIN_ROOT 值:D: MentorGraphics>PADSVX1.2>SDD_HOME>translators>win32bin (值:软件按装的位置,可以是9.5版本,也可以是VX1.0等不同的版本)。变量:HOME 值:C:Users>win7>AppData>Roaming>SPB_Data (这个值是allegro快捷键存放位置器,也可以随意放置在那个盘,我们可以采用默认的路径)。第4步:打开 PADSLayout软件,然后选择导入文件,选择刚刚处理的 allegro文件。

weixin_54787054的博客 3732

ANR的初步分析

Android中ANR的初步分析一、 初识ANR1.1什么是ANR?1.2ANR场景1.3 ANR出现的原因1.4 如何分析ANR二、ANR发生时的log收集三、日志分析3.1 分析 Event Log(如果没有找到该文件可以跳过这一步)3.2 分析 Android Log:看 MainLog(Android Log) 或者 SystemLog 查看 ANR 详细信息(搜索 ANR in),提取有效的信息 (提取有效信息到单独文件中)3.3 分析ANR traces.txt 文件四、ANR分析流程总结4.1

jjx_fight的博客 2102

华为OD机考2025B卷 - 报文响应时间(Java & Python& JS & C++ & C )

华为OD机考2025B卷 - 报文响应时间

算法大师! 8088

深入理解 Android 四大组件之 Service:从原理到实战(含面试题)

Service 是 Android 系统提供的一种后台运行组件,主要用于处理不需要 UI 交互、但需要长时间执行的任务(如网络请求、音乐播放、数据同步等)。无 UI 界面:Service 运行在后台,不直接与用户交互,无法像 Activity 一样加载布局;生命周期长:依赖于应用进程(而非 Activity),只要进程未被销毁,Service 可持续运行;运行线程:默认运行在应用的主线程(UI 线程)中,若需执行耗时操作,必须手动开启子线程(否则会导致 ANR);跨进程通信。

2401_89387076的博客 1530

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

深入理解Handler(四) --- 主线程的Looper为什么不会导致应用的ANR

一、概述 是否了解ANR的产生条件 是否对Android App的进程运行机制有深入了解 是否对Looper的消息机制有深刻的理解 在面试中经常也时常会遇到类似的问题,其实这两个八杆子打不着, 通过这篇文章我们好好捋一捋这两者的概念。 ANR类型 Service Timeout 前台服务 20s 后台服务 200s BroadcaseQueue Timeout 前台广播 10s 后台广播 60s ContentProvider Timeout 10s InputDispatching Tim

soso密斯密斯的博客 2028

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

彻底理解安卓应用无响应机制

转载:http://gityuan.com/2019/04/06/android-anr 引言 不论从事安卓应用开发,还是安卓系统研发,应该都遇到应用无响应(ANR,Application Not Responding)问题,当应用程序一段时间无法及时响应,则会弹出ANR对话框,让用户选择继续等待,还是强制关闭。 绝大多数人对ANR的了解仅停留在主线程耗时或CPU繁忙会导致ANR。面试过无数...

Treasure 2104

安卓应用无响应,你真的了解吗?

引言不论从事安卓应用开发,还是安卓系统研发,应该都遇到应用无响应(简称ANR)问题,当应用程序一段时间无法及时响应,则会弹出ANR对话框,让用户选择继续等待,还是强制关闭...

Gityuan的博客 2000

彻底理解Android应用无响应机制

有了现场信息,可以调试分析,先定位发生ANR时间点,然后查看trace信息,接着分析是否有耗时的message、binder调用,锁的竞争,CPU资源的抢占,以及结合具体场景的上下文来分析,调试手段就需要针对前面说到的message、binder、锁等资源从系统角度细化更多debug信息,这里不再展开,后续再以ANR案例来讲解。因为在向中控系统汇报广播接收者工作执行完成前,该进程的优先级为Foreground级别,高优先级下进程不但不会被杀,而且能分配到更多的CPU时间片,加速完成SP持久化。

xiaokangss的博客 1162
上一篇: Android 深入理解 Watchdog的原理
下一篇: Android 保证进程广播可以发生出去
Bill_xiao
博客等级 码龄10年 171粉丝 48原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值