2023年11月29日发(作者:)

安卓Java崩溃的捕获和⽇志记录

Android的两种崩溃

Android 崩溃分为 Java 崩溃和 Native崩溃两种。

Java崩溃的知识点

Java崩溃.png

Java崩溃的原因

简单来说,Java崩溃就是在Java代码中,出现了未被捕获的异常,导致应⽤程序异常退出。

其中Error和RuntimeException是unchecked exceptions,编译器默认⽆法通过对其处理。其余checkedexceptions,需要我们在代码中

try-catch。

崩溃的捕捉

UncaughtExceptionHandler

先来看⼀下这个接⼝的作⽤

/**

* Interface for handlers invoked when a Thread abruptly

* terminates due to an uncaught exception.

*

When a thread is about to terminate due to an uncaught exception

* the Java Virtual Machine will query the thread for its

* UncaughtExceptionHandler using

* {@link #getUncaughtExceptionHandler} and will invoke the handler's

* uncaughtException method, passing the thread and the

* exception as arguments.

* If a thread has not had its UncaughtExceptionHandler

* explicitly set, then its ThreadGroup object acts as its

* UncaughtExceptionHandler. If the ThreadGroup object

/**

* Handle application death from an uncaught exception. The framework

protected static final void commonInit() {

if (DEBUG) Slog.d(TAG, "Entered RuntimeInit!");

其实实现⽅法⽹上都⼤同⼩异,主要是对异常捕获后的处理机制不⼀致。⼀般会通过储存崩溃⽇志并上报这种⽅案去解决。这⾥先基础实现崩溃⽇

志⽂件的存储。

⼀个崩溃⽇志应该包括的基本信息有:

崩溃原因和栈记录

⽇期和APP版本信息

private void dumpToFile(Thread thread, Throwable ex) throws IOException {

File file = null;

PrintWriter printWriter = null;

String crashTime = (new Date(tTimeMillis()));

String dirPath = shLogPath(mContext);

File dir = new File(dirPath);

if (!()) {

boolean ok = ();

if (!ok) {

return;

}