安卓全局异常捕捉

直接上代码就是干

public class ExceptionCapture implements Thread.UncaughtExceptionHandler {

    private static  ExceptionCapture exceptionCapture;
    private Context context;
    private Thread.UncaughtExceptionHandler defaultExceptionHander;

    public ExceptionCapture() {
    }


    public static ExceptionCapture getInstance(){
        if(exceptionCapture == null){
            synchronized (ExceptionCapture.class){
                if(exceptionCapture == null){
                    exceptionCapture=new ExceptionCapture();
                }
            }
        }
        return exceptionCapture;
    }

    /**
     * 替换默认的异常捕获类
     * @param context
     */
    public void init(Context context){
        this.context=context;
        defaultExceptionHander=Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        if(!handleEcxception(e)&&defaultExceptionHander!=null){
            //未处理交由系统处理
            defaultExceptionHander.uncaughtException(t,e);
        }else {
            //已处理结束进程
            Process.killProcess(Process.myPid());
            System.exit(1);
        }
    }


    private boolean handleEcxception(Throwable ex){
        if(ex == null){
            return false;
        }
        //记录设备信息,异常
        SaveDeviceInfo(ex);
        return true;
    }

    private void SaveDeviceInfo(Throwable ex) {
        //获取异常类型
        String info=ex.toString();
        Log.e("info","-->"+info);
        StackTraceElement[] stackTraceElement=ex.getStackTrace();
        //获取异常具体发送行号
        for (StackTraceElement error:stackTraceElement) {
            Log.e("error","-->"+error.toString());
        }
        //获取设备信息,系统版本,手机品牌
        String brand=Build.BRAND;       //品牌
        String model=Build.MODEL;       //型号
        int SDK=Build.VERSION.SDK_INT;  //获取系统版本
        Log.e("INFO","brand:"+brand+" model:"+model+" SDK:"+SDK);
        //这儿自己保存相关异常信息/发送异常到后台服务器

    }
}

好了异常捕捉类定义完成,只要在Application中初始化就可以了

ExceptionCapture exceptionCapture=ExceptionCapture.getInstance();
exceptionCapture.init(this);

这样就可以捕捉全局异常了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值