在Thread中有个方法
setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler var0)
`
很多人可能没了解过这个东西可以干嘛用, 其实它的作用是可以传入一个 Handler来捕获那些没有被捕获的异常, 比如 app 层面的 crash。 下面提供了一段源码,可以用来捕获并把异常写入到文件中, 当然如果要上报的话也只需要把对应的字符串上报到统计系统就行。
public class ExceptionHandler implements Thread.UncaughtExceptionHandler {
private static final String TAG = "ExceptionHandler";
private static ExceptionHandler mInstance;
private Context mContext;
private SimpleDateFormat mFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
private ExceptionHandler() {
}
public static ExceptionHandler getInstance() {
if(mInstance == null) {
mInstance = new ExceptionHandler();
}
return mInstance;
}
public void init(Context context) {
mContext = context;
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread t, Throwable e) {
try {
Log.d(TAG, "uncaughtException: " + e.getMessage());
File cache = mContext.getExternalCacheDir();
String time = mFormat.format(new Date(System.currentTimeMillis()));
String crashName = "crash_" + time + ".log";
File crash = new File(cache, crashName);
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
e.getCause().printStackTrace(writer);
writer.close();
FileOutputStream fos = new FileOutputStream(crash, true);
fos.write(stringWriter.toString().getBytes());
fos.flush();
fos.close();
System.exit(0);
Process.killProcess(Process.myPid());
} catch (Exception exp) {
Log.e(TAG, "uncaughtException: " + exp.getMessage());
System.exit(0);
Process.killProcess(Process.myPid());
}
}
}
`