CrashHandler--程序异常退出处理

前言UncaughtExceptionHandler实现自己的UncaughtExceptionHandler遇到的问题结尾前言       作为一个android开发,经常遇到crash情况。原因各种各样,即使是经过了测试的大量检测,但是到用户手上还是会遇到闪退。这和android设备的碎片...
摘要由CSDN通过智能技术生成

前言

       作为一个android开发,经常遇到crash情况。原因各种各样,即使是经过了测试的大量检测,但是到用户手上还是会遇到闪退。这和android设备的碎片化有关,也和使用时的环境有关,比如弱网,比如高铁频繁切换小区等等。然而我们不能让用户帮我们抓取log,那要怎么才能知道为什么闪退了呢?


UncaughtExceptionHandler

       幸运的是:安卓已经帮我们想好了解决问题的接口(UncaughtExceptionHandler)。从名称上就知道这是用来处理没有捕捉到的野生Exception的。平时我们try catch的Exception的那就叫捕捉到的。看一下UncaughtExceptionHandler的源码:

public interface UncaughtExceptionHandler {
   
   /**
    * Method invoked when the given thread terminates due to the
    * given uncaught exception.
    * <p>Any exception thrown by this method will be ignored by the
    * Java Virtual Machine.
    * @param t the thread
    * @param e the exception
    */
   void uncaughtException(Thread t, Throwable e);
}

代码很简单,这是一个接口,并且只有一个方法。当出现未捕捉的exception时,系统会回调这个方法。具体实现在ThreadGroup.javauncaughtException:

public void uncaughtException(Thread t, Throwable e) {
    if (parent != null) {
        parent.uncaughtException(t, e);
    } else {
        Thread.UncaughtExceptionHandler ueh =
            Thread.getDefaultUncaughtExceptionHandler(); //获取当前默认的UncaughtExceptionHandler
        if (ueh != null) {
            ueh.uncaughtException(t, e); //此处回调uncaughtException()方法
        } else if (!(e instanceof ThreadDeath)) {
            System.err.print("Exception in thread \""
                             + t.getName() + "\" ");
            e.printStackTrace(System.err);
        }
    }
}

实现自己的UncaughtExceptionHandler

       从上面的源码分析我们知道,只要我们重写一个类实现UncaughtExceptionHandler接口,替换当前线程的默认UncaughtExceptionHandler对象就行。系统为我们提供了方法Thread.getDefaultUncaughtExceptionHandler()Thread.setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler u)


public class CrashHandler implements Thread.UncaughtExceptionHandler {
   
    private static final String TAG = CrashHandler.class.getSimpleName();
    private static CrashHandler INSTANCE = new CrashHandler();
    private Context mContext;
    private Thread.UncaughtExceptionHandler mDefaultExceptionHandler;

    @Override
    public void uncaughtException(Thread t, Throwable e) {
  //当发生exception时候会回调该方法
        dumpToSDCard(t, e);
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值