In your application class you can initialize for an unhandled exception. The callback method will have an throwable object. From this object we can get the crash log data and then the same data to be written to the file.
Application Class:
public class MyApplication extends Application {
// uncaught exception handler variable
private UncaughtExceptionHandler defaultUEH;
public MyApplication() {
defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
// setup handler for uncaught exception
Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);
}
// handler listener
private Thread.UncaughtExceptionHandler _unCaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
//To write the crash log data to file
AppUtil.getInstance().writeActivityLogToFile(true,
getErrorMessgae(ex));
// re-throw critical exception further to the os (important) to handle
defaultUEH.uncaughtException(thread, ex);
// System.exit(2);
}
};
/**
* To get the crash log message from throwable object
*
* @param e
* - throwable exception object
* @return - the crash log
*/
private String getErrorMessgae(Throwable e) {
StackTraceElement[] stackTrackElementArray = e.getStackTrace();
String crashLog = e.toString() + "\n\n";
crashLog += "--------- Stack trace ---------\n\n";
for (int i = 0; i < stackTrackElementArray.length; i++) {
crashLog += " " + stackTrackElementArray[i].toString() + "\n";
}
crashLog += "-------------------------------\n\n";
// If the exception was thrown in a background thread inside
// AsyncTask, then the actual exception can be found with getCause
crashLog += "--------- Cause ---------\n\n";
Throwable cause = e.getCause();
if (cause != null) {
crashLog += cause.toString() + "\n\n";
stackTrackElementArray = cause.getStackTrace();
for (int i = 0; i < stackTrackElementArray.length; i++) {
crashLog += " " + stackTrackElementArray[i].toString()
+ "\n";
}
}
crashLog += "-------------------------------\n\n";
return crashLog;
}
}
Declare your application class in your manifest in the following tag:
<application
android:name=".application.FleetLOCApplication"
......>