Skip to content

Instantly share code, notes, and snippets.

@NezSpencer
Created January 12, 2020 11:57
Show Gist options
  • Save NezSpencer/8f22a1059f8904af1cb77dd62c246328 to your computer and use it in GitHub Desktop.
Save NezSpencer/8f22a1059f8904af1cb77dd62c246328 to your computer and use it in GitHub Desktop.
This crashHandler shows the crash logs on the device when the app crashes
import androidx.fragment.app.FragmentActivity
class LoggerCrashHandler(private val app: FragmentActivity) : Thread.UncaughtExceptionHandler {
private val defaultUEH: Thread.UncaughtExceptionHandler? =
Thread.getDefaultUncaughtExceptionHandler()
override fun uncaughtException(t: Thread, e: Throwable) {
var arr = e.stackTrace
var report = "$e\n\n"
report += "--------- Stack trace ---------\n\n"
for (item in arr) {
report += " $item\n"
}
report += "-------------------------------\n\n"
// If the exception was thrown in a background thread inside
// AsyncTask, then the actual exception can be found with getCause
report += "--------- Cause ---------\n\n"
val cause = e.cause
if (cause != null) {
report += "$cause\n\n"
arr = cause.stackTrace
for (log in arr) {
report += " $log\n "
}
}
report += "-------------------------------\n\n"
CrashActivity.startActivity(report, app)
defaultUEH?.uncaughtException(t, e)
}
}
@NezSpencer
Copy link
Author

To use, Hook up to your desired activity by adding this after onCreate: Thread.setDefaultUncaughtExceptionHandler(LoggerCrashHandler(this))
credit: https://stackoverflow.com/a/59653258/5604736

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment