程序出现异常的时候,有时候并不会弹出异常对话框,而是直接退出了,没有任何迹象找不到解决就麻烦了,都不知道怎么找,很慌。为了能够捕捉到程序的异常,我们需要加一个全局异常的捕捉代码,当软件无故退出的时候,这时候就能发现异常出现的具体位置。
//首先创建全局异常类继承 UncaughtExceptionHandler,
public class ExecptionHandler implements Thread.UncaughtExceptionHandler {
private static ExecptionHandler execptionHandler = null;
private ExecptionHandler() {
}
//这个方法是要在application里面调用的,分为一级一级,一级一级调
public static ExecptionHandler getInstance(){
if (execptionHandler == null){
synchronized (ExecptionHandler.class){
if (execptionHandler == null){
execptionHandler = new ExecptionHandler();
}
}
}
return execptionHandler;
}
//在application调用,第三级
public void setDefaultUnCachExceptionHandler(){
//设置应用默认的全局异常捕获器
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
Log.d("myTag","程序出现异常"+throwable);
}
}
在自己定义的application里面按照上面的一级一级调.
public class App extends Application {
@Override
public void onCreate() {
ExecptionHandler.getInstance().setDefaultUnCachExceptionHandler();
}
}
之后在清单文件中调用这个application,就完成了