声明与初始化SP,自定义异常捕获
继承UncaughtExceptionHandler重写uncaughtException
在里面进行写入文件的操作,每条异常前最好使用分割线和日期作为分隔
可以等待3秒左右直接强退应用
然后再Application里注册
public class BaseException extends RuntimeException {
private static final long serialVersionUID = 8013687806066914955L;
public BaseException() {
super();
}
public BaseException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
}
public BaseException(String detailMessage) {
super(detailMessage);
}
public BaseException(Throwable throwable) {
super(throwable);
}
}
public abstract class BaseCrashHandler implements UncaughtExceptionHandler{
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (handleException(ex)) {
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
System.exit(1);
}
}
public abstract boolean handleException(Throwable ex);
}
public class CrashHandler extends BaseCrashHandler {
private Context context;
public CrashHandler(Context context) {
this.context = context;
}
@Override
public boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(context, "程序异常退出啦撸!!!", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}.start();
saveLog(ex);
return true;
}
private void saveLog(Throwable ex) {
try {
File errorDir = new File(context.getExternalCacheDir().getAbsolutePath() + "/CILogs");
if (!errorDir.exists()) {
errorDir.mkdirs();
}
File errorFile = new File(errorDir, "/crash_log.log");
if (!errorFile.exists()) {
errorFile.createNewFile();
}
OutputStream out = new FileOutputStream(errorFile, true);
out.write(("\n\n-----错误分割线" + DateFormat.format("yyyy年MM月dd日 HH时mm分ss秒 E ", new Date()) + "-----\n\n").getBytes());
PrintStream stream = new PrintStream(out);
ex.printStackTrace(stream);
stream.flush();
out.flush();
stream.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(new CrashHandler(getApplicationContext()));
}
}
网友评论