I created a custom exception handler in a class extending Application, using Thread.setDefaultUncaughtExceptionHandler
, to print uncaught exceptions' stack traces to a file. I'd like it to also display a custom error popup to the user, rather than the default "Unfortunately, [application] has stopped" message.
The following method creates an AlertDialog which returns to the main menu when clicked. It can be run even on background threads.
void alert(final String msg) {
final Activity activity = (Activity) getContext();
activity.runOnUiThread(new Runnable() {
public void run() {
new AlertDialog.Builder(activity)
.setCancelable(false)
.setMessage(msg)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
activity.startActivity(new Intent(activity, MainMenu.class));
}
})
.show();
}
});
}
However, the AlertDialog requires that the current activity be known. To use this method with an exception handler, I could keep a pointer to the current activity in the Application class, which is reset in each Activity's onResume()
method, but I'm concerned about leaking memory.
What is a preferable way to bring up an AlertDialog when an uncaught exception is thrown?
To get the default error popup, handle the exception and then execute the default uncaught exception handler:
final Thread.UncaughtExceptionHandler defaultHandler =
Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
doCustomHandlingHere();
defaultHandler.uncaughtException(t,e);
}
});
To get a custom error popup, I believe you would have to set the default uncaught exception handler for each activity separately. See this post for details.