转载请注明出处:http://blog.csdn.net/fishle123/article/details/50823358
我们的应用不可避免的会发生crash,如果是在调试阶段,我们可以使用Logcat查看异常信息。但是如果应用发布之后呢?如果在用户那边crash了,如果我们可以捕获这些crash信息,那么对我们定位crash原因并修复问题是很有帮助的。应用crash即可能是Java层的异常导致的,也可能是native层导致,下面分别来看一下该如何处理。
1 Java层的未捕获异常处理
先来看一下Java层的crash信息收集吧。要想捕获Java层的crash信息并不难,Android已经提供了接口来帮助我们监控系统的未捕获的异常:使用Thread.setDefaultUncaughtExceptionHandler就可以让我们轻松的监控应用的任何意外crash。
首先来看一下Thread.setDefaultUncaughtExceptionHandler这个方法:
/**
* Sets the default uncaught exception handler. This handler is invoked in
* case any Thread dies due to an unhandled exception.
*
* @param handler
* The handler to set or null.
*/
public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler handler) {
Thread.defaultUncaughtHandler = handler;
}
从Thread.setDefaultUncaughtExceptionHandler这个方法的注释就可以看到:当进程内(因为Thread.defaultUncaughtHandler 是一个静态变量,因此对整个进程内的所有线程有效)的任何线程发生未捕获异常时,会调用这里设置的handler。那我们看一下UncaughtExceptionHandler 这个类吧:
/**
* Implemented by objects that want to handle cases where a thread is being
* terminated by an uncaught exception. Upon such termination, the handler
* is notified of the terminating thread and causal exception. If there is
* no explicit handler set then the thread's group is the default handler.
*/
public static interface UncaughtExceptionHandler {
/**
* The thread is being terminated by an uncaught exception. Further
* exceptions thrown in this method are prevent the remainder of the
* method from executing, but are otherwise ignored.
*
* @param thread the thread that has an uncaught exception
* @param ex the exception that was thrown
*/
void uncaughtException(Thread thread, Throwable ex);
}
从源码可以看出,UncaughtExceptionHandler 其实是一个接口,它只定义了一个方法uncaughtException(Thread thread, Throwable ex),当线程因为遇到未捕获异常而终止的时候就会调用这个方法。
如果我们想要捕获应用的crash信息,那