Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I intercept an app crash and do something immediately when one occurs?

Tags:

android

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
}
like image 435
Kaloyan Roussev Avatar asked Mar 14 '14 11:03

Kaloyan Roussev


People also ask

What happens when an application crashes?

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.


2 Answers

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 Exceptions.

like image 189
Dmitry Zaytsev Avatar answered Oct 04 '22 07:10

Dmitry Zaytsev


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.

like image 26
scottt Avatar answered Oct 04 '22 09:10

scottt