首先我们写的是一个捕获全局异常、
- 为了更好的完善我们的项目,通常需要对产品不停的迭代维护,计时的收集用户使用过程中发生的异常信息就显得非常重要。市面上有一些第三方工具提供该功能:例如:腾讯的Bugly、友盟统计等。
但是有时间为了减少我们的apk的大小或公司要求,会禁止使用这些第三方工具,所以我们需要自己提供这个简单的功能。
当程序发生异常终止时,如果我们没有对其进行异常捕获处理,系统会调用该线程组的默认异常捕获处理器。我们想要对应用全局的异常进行捕获,实现思路就是自己写一个捕获器去替换系统默认的,然后对设备信息、版本信息、异常信息进行收集并上传到服务器进行分析。
Thread.UncaughtExceptionHandler接口
这时我们需要创建一个类实现这个接口、Thread.UncaughtExceptionHandler
重写他的异常处理的方法
把我们的类构造私有化给单例使用
下面就是我们全局捕获异常的代码,第三方的在官方文档中有配置应用的具体步骤,此时我们的异常全局捕获异常就写完了,第三方可能服务器有点慢,bug不能及时捕获到,有个延迟的时间,并不是代码写错了!
public class MyUnCatchExceptionHandler implements Thread.UncaughtExceptionHandler {
private static final String TAG = "MyUnCatch==========";
private static MyUnCatchExceptionHandler instance;
private Context context;//备用
private Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler;
private MyUnCatchExceptionHandler() {
}
public static MyUnCatchExceptionHandler getInstance() {
if (instance == null) {
instance = new MyUnCatchExceptionHandler();
}
return instance;
}
public void init(Context context) {
this.context = context;
defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread t, Throwable e) {
// TODO: 2019/3/28 收集异常信息
/**
* 异常类型
* 异常时间
* 手机型号
* 手机品牌
* 系统版本
* 。。。。
*/
// TODO: 2019/3/28 上传服务器
//如果系统提供了处理器,那么交给系统处理
if (defaultUncaughtExceptionHandler != null) {
defaultUncaughtExceptionHandler.uncaughtException(t, e);
} else {
//如果我们自己处理,一般来讲,直接杀死进程即可
android.os.Process.killProcess(android.os.Process.myPid());
}
Log.d(TAG, "uncaughtException: ");
}
}