I'm trying to disable the ACRA bug reporting library for a particular service. I've set up ACRA successfully for my app.
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
// The following line triggers the initialization of ACRA
ACRA.init(this);
}
}
One service uses a library that throws exceptions from time to time but, the situation is so rare that I have no intention of changing my code to catch them, since after crashing the service is restarted immediately and my users don't even notice a problem. Moreover the library will eventually be fixed.
Since I'm using ACRA, every exception is intercepted by ACRA. Is there any way to disable this behaviour for the problematic service only? That service is run as an independent process, doesn't communicate with anything, and the app doesn't suffer at all from its rare problems. I'm also not interested in tracking its bugs because they are not so important for the app's proper behaviour.
I was looking through ACRA documentation but, I didn't find anything helpful.
After reviewing the ACRA documentation and the codebase, it looks like this functionality is not available out-of-the-box.
I think your best bet is to implement your own sender, so you can write some simple logic to filter out all reports that match that library.
Related
I'm seeing a crash come through Crashlytics that I'm unable to reproduce or locate the cause of. The crash only ever happens on Google Pixel devices running Android 12, and the crash always happens in the background.
This is the crash log from Crashlytics:
Fatal Exception: android.app.RemoteServiceException$CannotDeliverBroadcastException: can't deliver broadcast
at android.app.ActivityThread.throwRemoteServiceException(ActivityThread.java:1939)
at android.app.ActivityThread.access$2700(ActivityThread.java:256)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2190)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7870)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
I've looked at similar questions (like this and this) but Crashlytics is showing that these users all have plenty of free memory, and nowhere in our codebase are we calling registerReceiver or sendBroadcast so the solutions in that second question aren't any help.
Based on limited logs I'm pretty sure the crash happens when the user receives a push notification, but I have a Google Pixel 4a running Android 12 and I haven't been able to reproduce it at all when sending myself notifications.
We have a custom FirebaseMessagingService to listen for notifications that we register in the Manifest and a couple of BroadcastReceivers that listen for geofencing updates and utilize WorkManager to do some work when a transition is detected. The only thing that's changed with any of those recently is we updated WorkManager to initialize itself using Android's app startup library, but I'm not sure if that's even relevant since the crash logs give me no information, and if there was a problem with our implementation it wouldn't limit itself to just Pixel devices running Android 12.
Has anyone see this before or is there a bug exclusively on Pixel devices that run Android 12? I've spent hours digging into this and am at a complete loss.
With reference to Android 13, rather than earlier issues on 12, there is a Google tracker issue here, which at the time of writing is assigned but awaiting a meaningful response.
A summary of the issue is that it only occurs on 13, and only on Pixel devices.
CommonsWare has a blog entry on this here, and the only other clue I found anywhere was in the changelog for GrapheneOS, here, which has this line entry:
Sandboxed Google Play compatibility layer: don't report CannotDeliverBroadcastException to the user
We use this Play library and experience the fault, so it's possible Graphene have encountered this and had to put in an OS fix.
Update:
I tentatively believe that we as an app have suppressed this issue, and stopped it polluting our stats.
We set an exception handler to absorb it, which is what GrapheneOS are doing - credit to them.
class CustomUncaughtExceptionHandler(
private val uncaughtExceptionHandler: Thread.UncaughtExceptionHandler) : Thread.UncaughtExceptionHandler {
override fun uncaughtException(thread: Thread, exception: Throwable) {
if (shouldAbsorb(exception)) {
return
}
uncaughtExceptionHandler.uncaughtException(thread, exception)
}
/**
* Evaluate whether to silently absorb uncaught crashes such that they
* don't crash the app. We generally want to avoid this practice - we would
* rather know about them. However in some cases there's nothing we can do
* about the crash (e.g. it is an OS fault) and we would rather not have them
* pollute our reliability stats.
*/
private fun shouldAbsorb(exception: Throwable): Boolean {
return when (exception::class.simpleName) {
"CannotDeliverBroadcastException" -> true
else -> false
}
}
}
We have to operate off class name strings because the CannotDeliverBroadcastException class is hidden and not available to us.
We install this handler early in the Application.onCreate() method, like this:
val defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler()
Thread.setDefaultUncaughtExceptionHandler(
CustomUncaughtExceptionHandler(defaultUncaughtExceptionHandler)
)
I might be a bit premature with this, but so far this has resulted in none of these crashes appearing in Play Console. A few did appear in our other reporting platform, where what is/isn't reported has always varied.
To be clear, I'm not suggesting this is a good approach, or one that you should necessarily take. It requires a client release and it risks masking exceptions not relating to this root cause. Fixing or ignoring this issue at the point of collection is Google's responsibility. However, it has seemingly stopped the impact on our headline reliability statistics, so I thought I'd share it as a possibility.
Our team has noticed a significant downtrend in this crash over the past few months. Possible Google has begun to roll out a fix for Pixel devices. We also have the same crash happening for Pixels running Android 13 and it's also seeing a downtrend. Hopefully others are seeing this as well.
I'm not sure if this will be helpful to anyone, but once we removed WorkManager (which was being initialized via the App Startup library) the crash stopped happening. This was removed alongside a bunch of other code, so I can't say for sure if WorkManager was the problem, if the App Startup library was the problem, or if something else that we removed fixed it.
I received a pre-launch report of my app showing the same problem:
android.app.RemoteServiceException$CannotDeliverBroadcastException: can't deliver broadcast
Device: google Redfin 64-bit only
Android version: Android 13 (SDK 33)
The solution proposed by Rob Pridham fixed the problem. Just in case someone prefers to use Java...
This is the CustomUncaughtExceptionHandler class added to MainActivity:
public static final class CustomUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
private final Thread.UncaughtExceptionHandler uncaughtExceptionHandler;
public void uncaughtException(#NotNull Thread thread, #NotNull Throwable exception) {
Intrinsics.checkNotNullParameter(thread, "thread");
Intrinsics.checkNotNullParameter(exception, "exception");
if (!this.shouldAbsorb(exception)) {
this.uncaughtExceptionHandler.uncaughtException(thread, exception);
}
}
private boolean shouldAbsorb(Throwable exception) {
String var10000 = Reflection.getOrCreateKotlinClass(exception.getClass()).getSimpleName();
if (var10000 != null) {
return "CannotDeliverBroadcastException".equals(var10000);
}
return false;
}
public CustomUncaughtExceptionHandler(#NotNull Thread.UncaughtExceptionHandler uncaughtExceptionHandler) {
super();
Intrinsics.checkNotNullParameter(uncaughtExceptionHandler, "uncaughtExceptionHandler");
this.uncaughtExceptionHandler = uncaughtExceptionHandler;
}
}
This is the code added to Oncreate:
Thread.UncaughtExceptionHandler uncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
assert uncaughtExceptionHandler != null;
Thread.setDefaultUncaughtExceptionHandler(new CustomUncaughtExceptionHandler(uncaughtExceptionHandler));
We're in this situation where our clients use our mobile application offline 95% of the time. At the end of their work day, when they get back to the office, they synchronize all data with our servers while they have network connectivity.
We have ACRA set up with the AcraHttpSender plugin to attempt sending us the crash reports directly, however this usually fails because they're using the application offline and ACRA stores the reports instead.
From what I understand the pending reports will only be sent by ACRA when the application is restarted, through ACRA.init. The problem is the users have no reason to restart the application at the end of their work day (while they have network connectivity). I have to stress that the users are complete tech illiterates, our clients made that clear to us.
So, we would really need to be able to tell ACRA to send us any pending crash reports it has during the short time network connectivity is available. Without user interaction of any kind. I was thinking maybe in the onCreate function of our main activity.
However I've been looking at documentation and other people asking the same question for a while and haven't found anything obvious. Is this possible?
EDIT: This is the current working code with the suggestion made by #F43nd1r and #CommonsWare. It wasn't working for me with 5.4.0, but with 5.5.1 it is.
Gradle
def acraVersion = '5.5.1'
implementation "ch.acra:acra-core-ktx:$acraVersion"
implementation "ch.acra:acra-http:$acraVersion"
implementation "ch.acra:acra-advanced-scheduler:$acraVersion"
implementation "ch.acra:acra-toast:$acraVersion"
Initialization
initAcra {
setBuildConfigClass(BuildConfig::class.java)
setReportFormat(StringFormat.JSON)
plugin<ToastConfigurationBuilder> {
setResText(R.string.acra_crash_text)
setLength(Toast.LENGTH_LONG)
setEnabled(true)
}
plugin<HttpSenderConfigurationBuilder> {
setUri("${BuildConfig.protocol}://${BuildConfig.host}/${BuildConfig.codemrc}/acra")
setHttpMethod(HttpSender.Method.POST)
setBasicAuthLogin("acra")
setBasicAuthPassword("******")
setEnabled(true)
}
plugin<SchedulerConfigurationBuilder> {
setRequiresNetworkType(JobInfo.NETWORK_TYPE_ANY)
setRestartAfterCrash(true)
setResReportSendSuccessToast(R.string.acra_report_sent_text)
setEnabled(true)
}
}
// Turn this on to obtain more messages in the log to debug ACRA
ACRA.DEV_LOGGING = BuildConfig.DEBUG
As #CommonsWare stated in the comments, AdvancedSenderScheduler is the way to go.
Example usage:
implementation "ch.acra:acra-advanced-scheduler:5.5.1"
#AcraScheduler(requiresNetworkType = JobInfo.NETWORK_TYPE_UNMETERED,
requiresBatteryNotLow = true)
In case you're not satisfied with AdvancedSenderScheduler options, you could also register your own SenderScheduler, but that should rarely be necessary.
This problem sounds really weird and it looks is somehow my mistake but isn't
I use crashlytics to keep logs and track exception of the usage of my app
for that i created a lib in the log4j interface which simple calls the crashlytics methods for log events.
On the first version of my lib i add an extra Crashlytics.logException() to every logger.error() in my code. After using it for a while i noticed that this behavior wasn't what i want and I removed the Crashlytics.logException()
BUT CRASHLYTICS KEPT SHOWING EXCEPTIONS ON THAT
I'm really confuse with that and for a long time i thought i was doing something wrong, but after debuging the code thousands of times i came to think that there is something beyond what i see
there is no metion of Crashlytics.logException() in my code, and somehow i still manage to see many errors in my crashlytics dashboard
can someone help me with that?
what events might generate a non-fatal issue on crashlytics dashboard
attach:
- https://pastebin.com/Rbu1ySpd this is the core class of my log lib
- whenever i want to log an even i do `logger.log("something");' in a very log4j way
I'm extremely curious how there is 0 code written within the application and all that is required is to use the library
compile 'com.google.firebase:firebase-crash:9.0.1'
in order to get firebase crash reporting working.
Is the initialization always a one time thing like how the application class' onCreate is always called just once?
What do I do if i want to enable crash reporting only after a certain event?
Update: There is now a comprehensive blog post about how Firebase components initialize.
Firebase Crash Reporting (in addition to other Firebase components) initialize in a ContentProvider that's included into your app automatically. ContentProviders are instantiated first, then your Application subclass, then whatever component was invoked (Activity, Service, BroadcastReciever).
When your project depends on an Android Library project (aar file), all of its manifest entries are merged into your app, so you get this ContentProvider for free simply by declaring declaring the dependency on firebase-crash.
I gave a talk at Google I/O 2016 about how this all works. Jump to 16:22 for the beginning of the content specific to crash reporting.
Unfortunately there is currently no way to programmatically enable or disable crash reporting, but that is coming soon.
So basically when I'm using Firebase Crash Reporting then I'm forced to do initialization in ContentProvider. My app have 2 processes because of this and if I do init in Application.onCreate then it's called twice - once for each process. But other processes don't care about my init code so I don't want to do it twice. So I can use a ContentProvider or check current process name.
Or maybe there is anything else that I'm missing?
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.