0

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?

1''
  • 26,823
  • 32
  • 143
  • 200
  • If you're thinking along the lines of replacing the default ANR screen - no. – Shark Jul 16 '13 at 15:26
  • 2
    i think this is relevant http://stackoverflow.com/questions/9751088/how-do-i-display-a-dialog-in-android-without-an-activity-context – chancea Jul 16 '13 at 15:32
  • @chancea Thanks for the link, but these solutions seem to require a background Service as the context, instead of an Activity. – 1'' Jul 16 '13 at 16:54
  • @Shark This isn't the Application Not Responding screen, it's the screen that occurs when there's an exception. – 1'' Jul 19 '13 at 22:38

1 Answers1

0

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.

1''
  • 26,823
  • 32
  • 143
  • 200