android - 使用 UncaughtExceptionHandler 捕获异常但显示崩溃对话框

标签 android exception crash uncaughtexceptionhandler

我已经实现了一个 ExceptionHandler 来防止应用程序启动崩溃的 Activity,并且它可以正常工作。 我的问题是它不再显示错误对话框。 这是异常处理程序的代码:

public class MyExceptionHandler implements
    java.lang.Thread.UncaughtExceptionHandler {
private final Context myContext;
private final Class<?> myActivityClass;

public MyExceptionHandler(Context context, Class<?> c) {

    myContext = context;
    myActivityClass = c;
}

public void uncaughtException(Thread thread, Throwable exception) {

    StringWriter stackTrace = new StringWriter();
    exception.printStackTrace(new PrintWriter(stackTrace));
    System.err.println(stackTrace);// You can use LogCat too
    Intent intent = new Intent(myContext, myActivityClass);
    String s = stackTrace.toString();
    //you can use this String to know what caused the exception and in which Activity
    intent.putExtra("uncaughtException",
            "Exception is: " + stackTrace.toString());
    intent.putExtra("stacktrace", s);
    myContext.startActivity(intent);
    //for restarting the Activity
    Process.killProcess(Process.myPid());
    System.exit(0);
}
}

有人知道如何在重新启动应用程序之前显示正常的黑色崩溃对话框吗?

提前致谢!

最佳答案

我已经找到解决办法了。 问题是:

 Intent intent = new Intent(myContext, myActivityClass);
String s = stackTrace.toString();
//you can use this String to know what caused the exception and in which Activity
intent.putExtra("uncaughtException",
        "Exception is: " + stackTrace.toString());
intent.putExtra("stacktrace", s);
myContext.startActivity(intent);

删除了startActivity,解决了对话框的问题,并且仍然按预期重新启动了应用程序。

编辑:

对话框提示但只是因为数据丢失而发生了第二次崩溃,所以这个答案不正确...

关于android - 使用 UncaughtExceptionHandler 捕获异常但显示崩溃对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32465598/

相关文章:

java - java类/异常表的最大大小

android - Android 应用程序崩溃后向服务器发送日志文件

ios - NSObjectInaccessibleException',原因 : 'CoreData could not fulfill a fault

windows - 使用 IF 批量过滤多个结果

android - 我在android中的模型需要为单例吗?

android - 如何在不调用 api 的情况下显示数据?

android - NullPointerException 使用模拟上下文创建 AppCompatImageView

Android:旋转后保留Webview内容

android 两个对话框-按下后退按钮时如何返回到上一个对话框

c++ - 处理来自 DLL 的异常