Android如何捕获应用的crash信息

转载请注明出处: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信息,那

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值