直接上代码就是干
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);
这样就可以捕捉全局异常了