Search code examples
androidfirebasefirebase-crash-reporting

Deal with Firebase crash reporting and custom Application class with custom UncaughtExceptionHandler


My Android app currently uses a custom UncaughtExceptionHandler that aims to capture any crash, and schedules an app restart for several seconds in the future with AlarmManager before manually calling Process.killProcess(Process.myPid()) to avoid Android's Force Close popup as in my app's use case, the user will not be able to interact with the device to tap "ok" on the FC dialog and restart the app.

Now, I'd like to integrate with Firebase Crash reports, but I fear wrong behaviors, so here are my questions:

  1. How should I make my code so my custom UncaughtExceptionHandler passes the exception to Firebase Crash Report before killing it's process? Would calling Thread.getDefaultUncaughtExceptionHandler() give me the Firebase Crash report UncaughtExceptionHandler so I can just call uncaughtException(...) on it?
  2. May Process.killProcess(Process.myPid()) prevent Firebase Crash reporting library to do it's reporting work? Would Firebase have started it's crash report in a separated process before it's uncaughtException(...) returns? Does Firebase own UncaughtExceptionHandler calls back to Android default's UncaughtExceptionHandler, showing the FC dialog?
  3. May Process.killProcess(Process.myPid()) kill Firebase Crash Reporting process in addition to the default process?
  4. How can my custom Application class detect if it is instantiated in Firebase Crash Reporting process? Treating both processes the same way would probably lead to inconsistent states.

Thanks to anyone that tries to help me!


Solution

  • After some testing, I finally found a way to both ensure my app restarts properly after an UncaughtException. I attempted three different approaches, but only the first, which is my original code, with just a little tweak to pass the uncaught Throwable to `FirebaseCrash, and ensure it is considered as a FATAL error.

    The code that works:

    final UncaughtExceptionHandler crashShield = new UncaughtExceptionHandler() {
    
        private static final int RESTART_APP_REQUEST = 2;
    
        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            if (BuildConfig.DEBUG) ex.printStackTrace();
            reportFatalCrash(ex);
            restartApp(MyApp.this, 5000L);
        }
    
        private void reportFatalCrash(Throwable exception) {
            FirebaseApp firebaseApp = FirebaseApp.getInstance();
            if (firebaseApp != null) {
                try {
                    FirebaseCrash.getInstance(firebaseApp)
                            .zzg(exception); // Reports the exception as fatal.
                } catch (com.google.firebase.crash.internal.zzb zzb) {
                    Timber.wtf(zzb, "Internal firebase crash reporting error");
                } catch (Throwable t) {
                    Timber.wtf(t, "Unknown error during firebase crash reporting");
                }
            } else Timber.wtf("no FirebaseApp!!");
        }
    
        /**
         * Schedules an app restart with {@link AlarmManager} and exit the process.
         * @param restartDelay in milliseconds. Min 3s to let the user got in settings force
         *                     close the app manually if needed.
         */
        private void restartApp(Context context, @IntRange(from = 3000) long restartDelay) {
            Intent restartReceiver = new Intent(context, StartReceiver_.class)
                    .setAction(StartReceiver.ACTION_RESTART_AFTER_CRASH);
            PendingIntent restartApp = PendingIntent.getBroadcast(
                    context,
                    RESTART_APP_REQUEST,
                    restartReceiver,
                    PendingIntent.FLAG_ONE_SHOT
            );
            final long now = SystemClock.elapsedRealtime();
            // Line below schedules an app restart 5s from now.
            mAlarmManager.set(ELAPSED_REALTIME_WAKEUP, now + restartDelay, restartApp);
            Timber.i("just requested app restart, killing process");
            System.exit(2);
        }
    };
    Thread.setDefaultUncaughtExceptionHandler(crashShield);
    

    Explanation of why and unsuccessful attempts

    It's weird that the hypothetically named reportFatal(Throwable ex) method from FirebaseCrash class has it's name proguarded while being still (and thankfully) public, giving it the following signature: zzg(Throwable ex).

    This method should stay public, but not being obfuscated IMHO.

    To ensure my app works properly with multi-process introduced by Firebase Crash Report library, I had to move code away from the application class (which was a great thing) and put it in lazily loaded singletons instead, following Doug Stevenson's advice, and it is now multi-process ready.

    You can see that nowhere in my code, I called/delegated to the default UncaughtExceptionHandler, which would be Firebase Crash Reporting one here. I didn't do so because it always calls the default one, which is Android's one, which has the following issue:

    All code written after the line where I pass the exception to Android's default UncaughtExceptionHandler will never be executed, because the call is blocking, and process termination is the only thing that can happen after, except already running threads.

    The only way to let the app die and restart is by killing the process programmatically with System.exit(int whatever) or Process.kill(Process.myPid()) after having scheduled a restart with AlarmManager in the very near future.

    Given this, I started a new Thread before calling the default UncaughtExceptionHandler, which would kill the running process after Firebase Crash Reporting library would have got the exception but before the scheduled restart fires (requires magic numbers). It worked on the first time, removing the Force Close dialog when the background thread killed the process, and then, the AlarmManager waked up my app, letting it know that it crashed and has a chance to restart.

    The problem is that the second time didn't worked for some obscure and absolutely undocumented reasons. The app would never restart even though the code that schedules a restart calling the AlarmManager was properly run.

    Also, the Force Close popup would never show up. After seeing that whether Firebase Crash reporting was included (thus automatically enabled) or not didn't change anything about this behavior, it was tied to Android (I tested on a Kyocera KC-S701 running Android 4.4.2).

    So I finally searched what Firebase own UncaughtExceptionHandler called to report the throwable and saw that I could call the code myself and manage myself how my app behaves on an uncaught Throwable.

    How Firebase could improve such scenarios Making the hypothetically named reportFatal(Throwable ex) method non name-obfuscated and documented, or letting us decide what happens after Firebase catches the Throwable in it's UncaughtExceptionHandler instead of delegating inflexibly to the dumb Android's default UncaughtExceptionHandler would help a lot.

    It would allow developers which develop critical apps that run on Android to ensure their app keep running if the user is not able to it (think about medical monitoring apps, monitoring apps, etc).

    It would also allow developers to launch a custom activity to ask users to explain how it occurred, with the ability to post screenshots, etc.

    BTW, my app is meant to monitor humans well-being in critical situations, hence cannot tolerate to stop running. All exceptions must be recovered to ensure user safety.