从Android中的线程中捕获所有异常

时间:2017-07-14 20:35:49

标签: java android

我想捕获活动类中任何语句引起的异常,以便我可以防止任何崩溃。无法测试应用程序可能使用的所有可能方案。我想在应用程序中提供一个警告对话框或带有按钮的文本框来报告问题,但不希望应用程序崩溃。有没有办法做到这一点?

我通过使用构造函数在类级别尝试了Throwing Exception,但这没有帮助。尝试Catch不能对每个语句都这样做,那么什么可以成为一个好的反崩溃解决方案,可以捕获整个活动类的异常?

2 个答案:

答案 0 :(得分:1)

从主线程,例如onCreate()

Thread thread = Thread.currentThread();
thread.setUncaughtExceptionHandler(uncaughtExceptionHandler);

答案 1 :(得分:1)

是的,你可以这样做创建一个ExceptionHandler类并收集崩溃记录..

 public class ExceptionHandler implements
        Thread.UncaughtExceptionHandler {
    private final Activity myContext;
    private final String LINE_SEPARATOR = "\n";

    public ExceptionHandler(Activity context) {
        myContext = context;
    }

    public void uncaughtException(Thread thread, Throwable exception) {
        StringWriter stackTrace = new StringWriter();
        exception.printStackTrace(new PrintWriter(stackTrace));
        StringBuilder errorReport = new StringBuilder();
        errorReport.append("************ CAUSE OF ERROR ************\n\n");
        errorReport.append(stackTrace.toString());

        errorReport.append("\n************ DEVICE INFORMATION ***********\n");
        errorReport.append("Brand: ");
        errorReport.append(Build.BRAND);
        errorReport.append(LINE_SEPARATOR);
        errorReport.append("Device: ");
        errorReport.append(Build.DEVICE);
        errorReport.append(LINE_SEPARATOR);
        errorReport.append("Model: ");
        errorReport.append(Build.MODEL);
        errorReport.append(LINE_SEPARATOR);
        errorReport.append("Id: ");
        errorReport.append(Build.ID);
        errorReport.append(LINE_SEPARATOR);
        errorReport.append("Product: ");
        errorReport.append(Build.PRODUCT);
        errorReport.append(LINE_SEPARATOR);
        errorReport.append("\n************ FIRMWARE ************\n");
        errorReport.append("SDK: ");
        errorReport.append(Build.VERSION.SDK);
        errorReport.append(LINE_SEPARATOR);
        errorReport.append("Release: ");
        errorReport.append(Build.VERSION.RELEASE);
        errorReport.append(LINE_SEPARATOR);
        errorReport.append("Incremental: ");
        errorReport.append(Build.VERSION.INCREMENTAL);
        errorReport.append(LINE_SEPARATOR);

        Intent intent = new Intent(myContext, CrashActivity.class); //start a new activity to show error message
        intent.putExtra("error", errorReport.toString());
        myContext.startActivity(intent);

        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(10);
    }
}

现在,在MainActivity中使用以下命令初始化ExceptionHandler:

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
    setContentView(R.layout.activity_main);
}