I'm currently working on a pretty big music app. And for some reason, my app randomly closes, without any error message.
I catch uncaught exceptions in the project using the following code:
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {...});
but even if it works every time for obvious exceptions, I don't catch any error when the app closes by itself. Also, it's not device related, since I tried on 10 differents devices of different brands with different versions of Android.
My question is: has anyone experienced something similar and if yes, what was the solution of your problem? Or, in other words: is there any case where an Android app can close by itself without any error (and without using System.exit())
I know it's not a very specific question, but since I have no idea where it comes from, I can't do any better so far.
The default uncaught handler yo are overriding are the responsible to display the error to the user, the solution is to have a reference to the old one and call it on yours as follow:
final Thread.UncaughtExceptionHandler appDefault = Thread.GetDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
// DO STUFF BEFORE APP CRASHES
appDefault.uncaughtException(t, e); // call later, so the app crashes as default
}});
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));
I am having an issue with what I believe is a memory leak.
Here are the reasons why:
I know that my app takes a lot of RAM, I see it on the graph in Android Studio
I sometimes get out of memory exceptions on my phone
I did a beta test and some users apps crashes, however some dont. Interestingly enough, a friend with an LG G4 (4 years or so old) is not having any issues and another friend with a Pixel 2 XL couldnt get the app open, it would crash on the main activity.
Sometimes when people would close the app and try to use the app switcher, the app switcher itself would crash. But once they would remove my app everything went to normal
If they tried to delete the app, it would crash the moment it would come up to the screen. Ex: They would go ahead and go to setting....until they reached the uninstall page. They scrolled down to my app and once the screen registered it was my app settings crashed. And the message read Setting is not responding, or something along those lines.
But here is my issue:
I checked all images and none are over 20kb large, as I read the limit is close to 600kb
I checked for leaks using the android studio built in function and nothing came up.
I changed all context calls to getApplicationContext()
I used LeakCanary and it only found an 8 mb leak that was happening. And that leak was on a locations class that I believe is androids.
Could that really be the problem?
Another potential issue, I am not sure how dumb I will sound but I havn't been using any threads. I started using them to open new activities for example:
final Handler handler = new Handler(Looper.getMainLooper());
new Thread(new Runnable() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
Intent open = new Intent(MainActivity.this, className);
startActivity(open);
}
});
}
}).start();
But I havnt seen any difference in performance.
But besides that, everything is working off the main thread.
I am not sure how bad of a habit that is.
Any advice will surely help me!
Thank you!
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.
Is there a way to catch, in one place, all "uncaught" exceptions and let the app continue?
I see I can use setUncaughtExceptionHandler to do some logging and whatever, but the app will still terminate. I want something where I can log an exception, tell the user his action failed, and let him keep going (try something else).
Thanks.
No. I'm not sure why you'd want it. Catch Exceptions from methods that are known to throw them, and test your code to avoid Exceptions such as NullPointerException. That's the way to write good code.
Sorry to revisit such an old thread but since there's no proper answer to it I felt obliged to provide a solution.
Add this to the activity that opens every time the app is used (MainActivity for example) -
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
Log.e("Exception"+Thread.currentThread().getStackTrace()[2],paramThrowable.getLocalizedMessage());
}
});
What it does is that it sets a default handler for uncaught exceptions and doesn't quit the app when one pops up. However, with great power comes great responsibility. I don't recommend you use this as a way to escape the responsibility of catching exceptions in your code (by using a try-catch for example). Test your code to make it as bug-free as possible before launch.
I have an app that is running pretty stably (no more crashes actually), but as everybody knows your program crashes as soon as it gets in the hands of somebody else :D
What I would like is to find a(all) the place(s) where I can put a try{}catch(){} to be able catch and control what happens when the app crashes unexpectedly (display a better message, send log, possible recovery...)
I know its surely not that simple but still it would be good if there was a way to catch most of them.
(for example there is a small bug in GLSurfaceView that when it is being closed causes sometimes to crash because of an EGL swap buffer)
any ideas?
You should take a look at this article: http://stuffthathappens.com/blog/2007/10/07/programmers-notebook-uncaught-exception-handlers/
But be careful when using this, you might mask errors in your application and if you resort to this to just pretend your app is working, you're doing it wrong :)
Here's a really lazy way to catch any given exception:
try {
//do some stuff here
} catch (Throwable e) {
//handle exception here
}
This is useful if you have no idea what's going to be thrown. Consequently, it's not going to be very helpful for any kind of recovery. This is something I wouldn't use beyond the testing period of development.