Android全局异常捕捉处理

主要介绍三种异常的处理:

1. 原生处理(实现UncaughtExceptionHanlder接口)
2. 腾讯bugly 的crash 上报
3. umeng统计错误上报

1.原生处理(实现UncaughtExceptionHanlder接口)

Thread.UncaughtExceptionHandler作用:
用来处理在程序中未被捕获的异常。(如果程序中已经自己设置了try{}catch,则不会执行这个方法)。
实现方式:

  1. 定义异常捕获类:

新建MyCrashHandler 实现UncaughtExptionHandler接口:

public class MyCrashHandler implements Thread.UncaughtExceptionHandler {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        //在这里处理异常信息
    }
}
  1. 将得到的异常数据保存到本地(也可以上传服务器,这里根据需求自行解决)
/**
* 保存错误信息到文件中
* @param ex
*/
private void saveCrashInfoToFile(Throwable ex) {
    Writer writer = new StringWriter();
    PrintWriter printWriter = new PrintWriter(writer);
    ex.printStackTrace(printWriter);
    Throwable exCause = ex.getCause();
    while (exCause != null) {
        exCause.printStackTrace(printWriter);
        exCause =exCause.getCause();
    }
    printWriter.close();

    long timeMillis = System.currentTimeMillis();
    //错误日志文件名称
    String fileName = "crash-" + timeMillis + ".log";
    //判断sd卡可正常使用
    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
      //文件存储位置
      String path = Environment.getExternalStorageDirectory().getPath() + "/crash_logInfo/";
      File fl = new File(path);
       //创建文件夹
        if(!fl.exists()) {
            fl.mkdirs();
        }
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(path + fileName);
            fileOutputStream.write(writer.toString().getBytes());
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

配置读写权限:

<!-- 往SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- 从SDCard读入数据权限 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  1. 将该异常类设置为系统默认异常处理类,然后出现异常时,则该类会处理异常。
//设置该类为系统默认处理类
Thread.setDefaultUncaughtExceptionHandler(this);
  1. 在Application中使用:
MyCrashHandler mycrashHandler = new MyCrashHandler();
Thread.setDefaultUncaughtExceptionHandler(mycrashHandler);

第3步可以放到Application中,也可以在自身类里初始化好。这里只讲述思路。

到这里为止,就已经完成了全局捕获器的创建和调用,如果出现未捕获的异常,异常信息就会保存到sd卡内。这样就方便我们的查找。

当然上面的代码只是讲解思路,所以使用的时候,我们需要补充和完善,比如bug信息文件里添加手机信息,在保存到本地后将文件上传服务器等等操作,这些都可以根据需求自行完善。这里贴出我自己使用的一部分代码。

public class MyCrashHandler implements Thread.UncaughtExceptionHandler {

    private Context mContext;
	 //本类实例
    private static MyCrashHandler myCrashHandler;
    //系统默认的uncatchException
    private Thread.UncaughtExceptionHandler mDefaultException;

  
	//保证只有一个实例
    private MyCrashHandler(){}

	 //单例模式
    public static synchronized MyCrashHandler newInstance() {
        if(myCrashHandler == null)
            myCrashHandler = new MyCrashHandler();
        return myCrashHandler;
    }

    /**
     * 初始化
     * @param context
     */
    public void init(Context context){
        mContext = context;
        //系统默认处理类
        mDefaultException = Thread.getDefaultUncaughtExceptionHandler();
        //设置该类为系统默认处理类
        Thread.setDefaultUncaughtExceptionHandler(this);
    }



    @Override
    public void uncaughtException(Thread t, Throwable e) {
        if(!handleExample(e) && mDefaultException != null) { //判断异常是否已经被处理
            mDefaultException.uncaughtException(t, e);
        }else {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            //退出程序
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
        }
    }

    /**
     * 提示用户出现异常
     * 将异常信息保存
     * @param ex
     * @return
     */
    private boolean handleExample(Throwable ex) {
        if(ex == null)
            return false;

        new Thread(() -> {
            Looper.prepare();
            Toast.makeText(mContext, "很抱歉,程序出现异常,即将退出", Toast.LENGTH_SHORT).show();
            Looper.loop();
        }).start();

        //手机设备参数信息
        collectDeviceInfo(mContext);
        saveCrashInfoToFile(ex);
        return true;
    }

    /**
     * 设备信息
     * @param mContext
     */
    private void collectDeviceInfo(Context mContext) {


    }


    /**
     * 保存错误信息到文件中
     * @param ex
     */
    private void saveCrashInfoToFile(Throwable ex) {
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable exCause = ex.getCause();
        while (exCause != null) {
            exCause.printStackTrace(printWriter);
            exCause = exCause.getCause();
        }
        printWriter.close();

        long timeMillis = System.currentTimeMillis();
        //错误日志文件名称
        String fileName = "crash-" + timeMillis + ".log";
        //判断sd卡可正常使用
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //文件存储位置
            String path = Environment.getExternalStorageDirectory().getPath() + "/crash_logInfo/";
            File fl = new File(path);
            //创建文件夹
            if(!fl.exists()) {
                fl.mkdirs();
            }
            try {
                FileOutputStream fileOutputStream = new FileOutputStream(path + fileName);
                fileOutputStream.write(writer.toString().getBytes());
                fileOutputStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2.腾讯bugly 的crash 上报

参考:
https://blog.csdn.net/wjj1996825/article/details/83068482
https://www.cnblogs.com/baiqiantao/p/9145809.html#%E8%85%BE%E8%AE%AFBugly
官网:
https://bugly.qq.com/docs/user-guide/instruction-manual-android/?v=20200312155538

3. umeng统计错误上报

umeng统计集成成功后,会自动包含错误统计
参考:
https://www.jianshu.com/p/d93767c806e3
umeng官网:
https://developer.umeng.com/?spm=0.0.0.0.9EfFZE#2_3

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值