How do I handle uncaught exceptions and then delegate handling back to the system?

Viewed 557

I want to send a firebase crash report for every uncaught exception in my app but I also want to Android system to show the "App has stopped responding" dialog. How do I go about this?? I already have an UncaughtException handler that sends the firebase crash report. My issue now is letting Android handle the rest of the process.

1 Answers

The uncaught exception can be delegated back to system by storing the old exception handler and passing uncaught exceptions to it.

First create an Application class as below:

public class Controller extends Application {

    private static Thread.UncaughtExceptionHandler defaultHandler;

    @Override
    public void onCreate() {
        super.onCreate();
        if (defaultHandler == null) {
            defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        }
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                FirebaseCrash.report(e); //or whatever
                defaultHandler.uncaughtException(t, e); //this will show crash dialog.
            }
        });
    }

}

Then use this class as application in the manifest as:

<application
    android:name=".Controller"
    ... />
Related