Is there a way to register a global error handler that will prevent the application from crashing? Crash reports are described here: How to get crash data from the Android app? . I thought it was necessary to expand these solutions for use in the context of the application, so that I could redirect to specific reporting activities? But not sure if the application context is valid at this point when there is a crash message?
But how can you redirect the user to a global error message? Crash activity? Is there a high-level way to register an error handler that will catch all errors and prevent a crash? Is there a way to register such a handler so that it prevents or survives a crash and then redirects the user to a specific activity that will display the corresponding error message?
Here is my modification to the error handler:
1) Just pass applicationContext to constructor as ctx
2) add the reportError(stackTrace) method to transfer control to the error message page
private void reportError(String stackTrace){ Intent i = new Intent(ctx, DisplayErrorActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.setAction("DISPLAY_ERROR_ACTIVITY"); Bundle b = new Bundle(); b.putString("STACKTRACE", stackTrace); i.putExtras(b); try{ Log.d("MyErrorHandler","reportError ctx="+ctx); ctx.startActivity(i); } catch (Exception e) { Exception ex = e; e.printStackTrace(); } }
And reportError below:
public void uncaughtException(Thread t, Throwable e) { Log.d("MyUncoughtExceptionHandler", "uncoughtException ctx="+ctx); String timestamp=getDateTime(); final Writer result = new StringWriter(); final PrintWriter printWriter = new PrintWriter(result); e.printStackTrace(printWriter); String stacktrace = result.toString(); printWriter.close(); String filename = timestamp + ".stacktrace"; Log.d("MyexceptionHanlder","UncoughtException: "+stacktrace); if (localPath != null) { writeToFile(stacktrace, filename); } if (url != null) { sendToServer(stacktrace, filename); } reportError(stacktrace);
If you leave a comment defaultUEH , a normal defaultUEH dialog will appear. Without it, a blank screen. Log indicates that ErrorMessageActivity forcibly closed along with the process.
To check, I just put the div on zero in the main activity creation method right after registering the error handler with the stream. If I had a try-catch over this, it would not crash, but the global error handler did not seem to prevent a crash. Checked ctx and it seems valid in a debugger.