此时可以在uncaughtException()方法中做日志收集和上传工作。
为什么出现异常了,程序会停止运行呢?
这个问题需要了解下Android 的异常处理机制,在我们未设置Thread.UncaughtExceptionHandler之前,系统会默认设置一个,具体我们参考下ZygoteInit.zygoteInit()
public static final Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges,
String[] argv, ClassLoader classLoader) {
if (RuntimeInit.DEBUG) {
Slog.d(RuntimeInit.TAG, “RuntimeInit: Starting application from zygote”);
}
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, “ZygoteInit”);
RuntimeInit.redirectLogStreams();
RuntimeInit.commonInit();
ZygoteInit.nativeZygoteInit();
return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,
classLoader);
}
protected static final void commonInit() {
if (DEBUG) Slog.d(TAG, “Entered RuntimeInit!”);
/*
-
set handlers; these apply to all threads in the VM. Apps can replace
-
the default handler, but not the pre handler.
*/
LoggingHandler loggingHandler = new LoggingHandler();
RuntimeHooks.setUncaughtExceptionPreHandler(loggingHandler);
Thread.setDefaultUncaughtExceptionHandler(new KillApplicationHandler(loggingHandler));
…
}
可以看到在ZygoteInit.zygoteInit()中已经设置了setDefaultUncaughtExceptionHandler(),而ZygoteInit是进程初始化的过程。 Thread.setDefaultUncaughtExceptionHandler(new KillApplicationHandler(loggingHandler));
当程序出现异常会回调到KillApplicationHandler.uncaughtException(Thread t, Throwable e)
@Override
public void uncaughtException(Thread t, Throwable e) {
try {
ensureLogging(t, e);
// Don’t re-enter – avoid infinite loops if crash-reporting crashes.
if (mCrashing) return;
mCrashing = true;
// Try to end profiling. If a profiler is running at this point, and we kill the
// process (below), the in-memory buffer will be lost. So try to stop, which will
// flush the buffer. (This makes method trace profiling useful to debug crashes.)
if (ActivityThread.currentActivityThread() != null) {
ActivityThread.currentActivityThread().stopProfiling();
}
// Bring up crash dialog, wait for it to be dismissed
ActivityManager.getService().handleApplicationCrash(
mApplicationObject, new ApplicationErrorReport.ParcelableCrashInfo(e));
} catch (Throwable t2) {
if (t2 instanceof DeadObjectException) {
// System process is dead; ignore
} else {
try {
Clog_e(TAG, “Error reporting crash”, t2);
} catch (Throwable t3) {
// Even Clog_e() fails! Oh well.
}
}
} finally {
// Try everything to make sure this process goes away.
Process.killProcess(Process.myPid());
System.exit(10);
}
}
直接观察finally
中,调用了 Process.killProcess(Process.myPid()); System.exit(10);
,触发了进程结束逻辑,也就导致了程序停止运行。
如果出现了异常,程序一定会停止运行么?
-
首先我们需要定一下停止运行的概念是啥,一般主要有两种情况。
-
- 程序进程退出(对标常说的闪退)
-
- 程序进程存续,但是点击无响应用户事件(对标ANR)
第一个问题很好理解,就是我们上述过程的进程退出,我们主要研究第二种情况,进程存续但是无法响应用户事件。
这里我先要普及个小知识点,Android系统为啥能响应来自各种(人为/非人为)的事件?
- 这里就要涉及Handler的概念了,其实整个操作系统的运行全部依赖Handler Message Looper这套机制,所有的行为全部会组装成一个个的Message消息,然后Looper开启一个for循环(死循环)取出一个个Message交给Handler处理,而Hander处理完成进行了响应,我们的行为也就得到了应答,影响的越快我们就会认为系统越流畅。
这里不过多描述Handler机制,有需要的可以看下我这篇已经授权给 鸿洋 的博客,那真叫一个粗暴,保证你一会就搞明白整个流程。
OK,我们回来继续扯为啥进程存续,却无法响应用户的事件呢?其实刚刚描述Handler的时候已经说到了。 就是出现了异常,导致主线程的Looper已经退出循环了
,都退出循环了还怎么响应你。
以上2种情况分析清楚了,那我们着重说下怎么解决这两种问题,先整第一种。
出现异常,怎么防止进程退出? 上述已经说到,进程退出,实际是默认的KillApplicationHandler.uncaughtException()
调用了Process.killProcess(Process.myPid()); System.exit(10)
。 防止退出,不让调用KillApplicationHandler.uncaughtException()
不就可以了?
做法跟我们本文开头描述的一样,我们只需要自己实现一个Thread.UncaughtExceptionHandler类,并在Application初始化就可以了
class MyCrashHandler : Thread.UncaughtExceptionHandler {
override fun uncaughtException(t: Thread, e: Throwable) {
Log.e(“e”, “Exception:” + e.message);
}
fun init() {
Thread.setDefaultUncaughtExceptionHandler(this)
}
}
以上逻辑设置了Thread默认的UncaughtExceptionHandler,所以再出现崩溃的时候会调用到 ThreadGroup.uncaughtException()
,再处理异常就会到我们自己实现的MyCrashHandler了,所以也就不会退出进程了。
public void uncaughtException(Thread t, Throwable e) {
if (parent != null) {
parent.uncaughtException(t, e);
} else {
Thread.UncaughtExceptionHandler ueh =
Thread.getDefaultUncaughtExceptionHandler();
if (ueh != null) {
ueh.uncaughtException(t, e);
} else if (!(e instanceof ThreadDeath)) {
System.err.print("Exception in thread “”
- t.getName() + “” ");
e.printStackTrace(System.err);
}
}
}
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数初中级安卓工程师,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年最新Android移动开发全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频
如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注Android)
资源分享
点击:
**《Android架构视频+BAT面试专题PDF+学习笔记》**即可免费获取
网上学习 Android的资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。希望这份系统化的技术体系对大家有一个方向参考。
[外链图片转存中…(img-1VYkQtRJ-1710576128803)]
[外链图片转存中…(img-9tbV907i-1710576128803)]
[外链图片转存中…(img-42YY8khT-1710576128803)]
点击:
**《Android架构视频+BAT面试专题PDF+学习笔记》**即可免费获取
网上学习 Android的资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。希望这份系统化的技术体系对大家有一个方向参考。
2020年虽然路途坎坷,都在说Android要没落,但是,不要慌,做自己的计划,学自己的习,竞争无处不在,每个行业都是如此。相信自己,没有做不到的,只有想不到的。祝大家2021年万事大吉。