一、 背景
是否有这种情况,测试发现了个crash的bug,找到研发,但是研发复现不出来...
二、解决方案
在App Crash的时候,利用CrashHandler捕获异常,将异常信息输出在屏幕上
public class CrashHandler implements Thread.UncaughtExceptionHandler {
public static void init(Context context) {
Thread.UncaughtExceptionHandler exceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
if (exceptionHandler != null
&& exceptionHandler.getClass().getName().startsWith("当前类的package name")) {
return;
}
Thread.setDefaultUncaughtExceptionHandler(new CrashHandler(context));
}
private Context mContext;
private CrashHandler(Context context) {
this.mContext = context;
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
//128kb-1
int maxStackTraceSize = 131071;
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
String stackTraceString = sw.toString();
if (stackTraceString.length() > maxStackTraceSize) {
String disclaimer = " [stack trace too large]";
stackTraceString = stackTraceString.substring(0, maxStackTraceSize - disclaimer.length()) + disclaimer;
}
// 在另外一个进程 打开Activity
Intent intent = new Intent(mContext.getApplicationContext(), ExceptionActivity.class);
intent.putExtra(ExtraName.CRASH_MESSEAG, stackTraceString);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
mContext.startActivity(intent);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(10);
}
}
- 注意点:
- ExceptionActivity 必须在另外一个进程,在manifest里设置即可
三、结语
- 赠人玫瑰手留余香
- 如果对您有帮助,请点赞支持我~~