Multiple process to catch uncaught exception? - android

I am developing a module that will be installed on multiple app. On of our client expressed concern about the potential of our module crashing making his app crash. I want to find a way to catch all uncaught exceptions that my module can throw. The module is composed of a service and 2-3 activities who have very little communication with the main app.
To catch those exceptions thrown by a handful of classes, and only those classes, what whould be the best option ? I have considered using Thread.UncaughtExceptionHandler which catch all exception thrown by a thread and putting all thoses classes in a separate process (with the android:process attribute), but I was told that using multiple processes can impact performance and battery usage. Is it possible to start a service and multiple activities in a separate thread without having to rewrite them all ?

You can implement an uncaught exception handler from your library. It will handle the uncaught exceptions that got triggered from threads started from your library.
Don't forget to pass it to the DefaultUncaughtExceptionHandler.
If the app implemented its own UncaughtExceptionHandler it will handle it as well.

Related

Report all Android crashes to own API

I am in a situation where I cannot use third party Crash reporting platform (Crashalytics ...etc)
So, I started to use self developed Rest API to receive crash reports from mobile app.
However, I can only send handled crashes so far by using try-catch
How can I handle all crashes thrown by my mobile app even those which are not in my try-catch clauses
Just like Crashlytics which can catch all crashes and sends them to Firebase without placing try-catch
Have a look at Thread.UncaughtExceptionHandler
from the docs :
When a thread is about to terminate due to an uncaught exception the
Java Virtual Machine will query the thread for its
UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler()
and will invoke the handler's uncaughtException method, passing the
thread and the exception as arguments. If a thread has not had its
UncaughtExceptionHandler explicitly set, then its ThreadGroup object
acts as its UncaughtExceptionHandler. If the ThreadGroup object has no
special requirements for dealing with the exception, it can forward
the invocation to the default uncaught exception handler.
using this, you can get all threads and all exceptions, which you can then report to any API you'd like
you can find examples of how it was implemented
here and here
There is a library which you can use called ACRA , its an open source library you can check its code , or you can directly use their library and configure it to hit your api
#AcraHttpSender(uri = "http://yourserver.com/yourscript",
basicAuthLogin = "yourlogin", // optional
basicAuthPassword = "y0uRpa$$w0rd", // optional
httpMethod = HttpSender.Method.POST)
public class MyApplication extends Application {

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:
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?
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?
May Process.killProcess(Process.myPid()) kill Firebase Crash Reporting process in addition to the default process?
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!
If you kill the process in your exception handler, you will not be able to receive crashes. It will interfere with the ability to persist the crash for either immediate or delayed transmission. It will possibly interfere with any library that has registered uncaught exception handlers that behave well.
In fact, Process.killProcess(Process.myPid()) is very much an anti-pattern for Android development. Android apps should not be concerned at all with the overall lifecycle if the process that hosts the app. The fact that Android manages the process for you is an optimization designed for the benefit of the users.
I strongly recommend, for uncaught exceptions in your app, to simply let the app die as it normally would. Masking the proper effect of the crash is like sweeping dirt under a rug. You might be resolving a short term problem, but what really needs to happen is the normal logging and handling of the error so you can fix it.
Don't depend on the fact that Firebase Crash Reporting transmits exceptions in another process. That other process will be removed in the full non-beta release.
The best situation for your Application subclass is to not depend at all which process it's operating. In fact, the Android team at Google does not recommend use of Application subclasses at all since it only leads to trouble for multi-process apps. If you must use an Application subclass, it should expect to run within multiple processes.
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.

How does ACRA catch all of an app's exceptions?

Do you know how ACRA - the Android Crash reporting framework - works under the hood?
How does it hook-in to catch exceptions and errors? Is it using some global try/catch block to detect errors?
And does it affect performance and battery life by doing this?
ACRA works by setting up a default exception handler on the main thread. You can see that in the source code here:
mDfltExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
It sets itself as the default uncaught exception handler at this point. Java will call this handler if there are any Exceptions that are thrown that are never caught by any try/catch block.
Since it's not really an active daemon or process, but rather part of your code (assuming you call ACRA.init()), it doesn't actually impact performance or battery life at all.

Unhandled exception not caught by global exceptionhandler

I got an android app where I set a global exception handler as described here:
Using Global Exception Handling on android
When I'm forcing an exception then I see that it is catched by the handler.
But from time to time I'm still experiencing device freezes when running the app.
The app uses a lot of different threads. But as far as I understand, this should have no influence.
Are there some known limitations on android regarding global exception handling, where exception are not handled by the global handler?
Thanks

ACRA make it boring if there are many exceptions thrown

I use ACRA in my android application. It's very useful but sometimes boring.
Sometimes, there are several asynchronous tasks running in the background. And for season, all of them failed(e.g. can't connect to internet). ACRA will show the toast message again and again, and refused to exit.
Is it able to let ACRA just catch the first exception? Or just show the toast message once?
Update
add a demo: https://github.com/freewind/android-acra-multi-reports
There are 4 activities in this project. The last one will throw exception and each previous activity will throw exception in onActivityResult. You can see ACRA will report many times before exiting.
That sounds to me like you should actually catch some exceptions and don't let all of them bubble up.
ACRA registers a Thread.UncaughtExceptionHandler on the main thread. Here all uncaught exceptions (as the handler's name suggests) get processed. Usually that means that the application is about to crash and ACRA will do its reporting magic. ACRA uses several Threads itself to do its work and will wait until everything is finished before it actually kills the application's process. So I'd guess that if there are coming a lot of exceptions, ACRA is just so busy to process them that it won't come to the point were it would kill the process.
You could register your own implementation of UncaughtExceptionHandler to catch exceptions and decide when to hand them through to ACRA and when to do something else. If I'm not mistaken, ACRA will call through to the UncaughtExceptionHandler that has been registered before the ACRA init. So you could also try to chain those handlers.

Categories

Resources