创建一个类
private Context context;//留作备用 private Thread.UncaughtExceptionHandler defaultExceptionHandler;//系统的默认异常处理类 private static UnCatchExceptionHandler instance = new UnCatchExceptionHandler();//用户自定义的异常处理类
private Thread.UncaughtExceptionHandler defaultExceptionHandler;
private static UnCatchExceptionHandler instance = new UnCatchExceptionHandler();
public UnCatchExceptionHandler() {
}
public static UnCatchExceptionHandler getInstance() {
return instance;
}
public void init(Context context) {
this.context = context.getApplicationContext();
defaultExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread t, Throwable e) {
if (defaultExceptionHandler != null) {
defaultExceptionHandler.uncaughtException(t, e);
} else { //否则我们自己处理,自己处理通常是让app退出 Process.killProcess(Process.myPid()); }
// Process.killProcess(Process.myPid());
}
然后再有一个类继承Application (不要忘记在清单文件里声明这个类)
public class Uncatch extends Application {
@Override
public void onCreate() {
super.onCreate();
UnCatchExceptionHandler.getInstance().init(this);
}