I would like to be able to intercept app crashes in my app and when one occurs, I'd like to clear the database for example.
Can I have some listener for a crash and have a method like:
onAppCrash() {
// Do some really important stuff
}
When an app crashes, Android terminates the app's process and displays a dialog to let the user know that the app has stopped, as shown in figure 1. An app doesn't need to be running in the foreground for it to crash.
You can use Thread.setDefaultUncaughtExceptionHandler
to catch all unhandled exceptions, which is most often the reason of crash.
You can register this listener in your Application's onCreate
or in any particular Activity - depends on how you are going to resolve exceptions.
Nevertheless, I suggest you to think about this approach a bit more. It's always better to improve quality of you app instead of "catching" all possible Exception
s.
The problem with capturing exceptions globally is in determining what to do next. Since the exception could have been caused anywhere in the app's code (or in the underlying framework) and at any time, it would be nearly impossible to determine what the state of the application is.
It's usually better to put tailored exception handlers around all of the various parts of code that can fail. By doing that, you have more knowledge about the context of each failure and can react according.
For instance, you mention closing a database. If you put tailored handlers around the database calls, you'll likely have an easier time knowing how to resolve the situation. And you could always add a 'finally' block to your database code to make sure the database always get closed, even if there's an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With