How to track App-crash in Android?

I would say it is a million dollar question, since there is no call back to trace app crashes in Android. I had spent much time on figuring out this. But any how, two of my colleagues found a way to trace it (it’s great!!). Here am sharing it as a reference to all.

Step 1 :

Application class is the first to be executed during app launch. Hence we chose to track App-crash in it. The code below, returns the default exception handler that’s executed when uncaught exception terminates a thread.

Thread.UncaughtExceptionHandler defaultSystemHandler = Thread.getDefaultUncaughtExceptionHandler();

Step 2 :

The code below, sets the default uncaught exception handler. This handler is invoked in case any Thread dies due to an un handled exception.

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
try {
System.out.println("Ouch !crashed !!!!"); // do your stuff here
if (defaultSystemHandler != null) {
defaultSystemHandler.uncaughtException(thread, ex); // pass the terminating thread and exception to defaultSystemHandler
} else {
android.os.Process.killProcess(android.os.Process.myPid()); // kill app like iOS when crashed
}
} catch (Exception e) {
e.printStackTrace();
defaultSystemHandler.uncaughtException(thread, ex); // pass the terminating thread and exception to defaultSystemHandler
}
}
});

That’s it.!
Happy coding!

--

--