package com.ubugtrack import android.content.Context import android.content.pm.PackageManager import android.os.Build import java.io.File import java.io.PrintWriter import java.io.StringWriter import java.net.HttpURLConnection import java.net.URI import java.net.URLEncoder import kotlin.concurrent.thread import kotlin.system.exitProcess /** * www.ubugtrack.com - Crash Reporter for Android in Kotlin, version 2 * Sends the uncaught exceptions of an app (Android 5.0+) to the Crash Reporter of a uBugtrack project. * Same behavior as CrashReporter.java: use one or the other. * * In Application.onCreate(): * CrashReporter.init("YOUR_CRASH_KEY", this) * * AndroidManifest.xml needs: * * The crash is saved first, then sent: a crash that could not be sent (no network) * is sent at the next launch. Then the app ends as usual: Android's crash dialog, * Play Console vitals and the other crash reporters still see the crash. */ object CrashReporter { private const val ENDPOINT = "https://ubugtrack.com/crashdump.php" private const val TIMEOUT_MS = 4000 private const val PENDING_FOLDER = "ubugtrack_crashes" private const val MAX_PENDING = 5 private var installed = false /** * Call it once, in Application.onCreate(). endpoint: only to send to another uBugtrack server (tests). */ @JvmStatic @JvmOverloads @Synchronized fun init(projectKey: String, context: Context, endpoint: String = ENDPOINT) { if (installed) return installed = true val application = context.applicationContext ?: context val handler = Handler( projectKey = projectKey, endpoint = endpoint, appVersion = versionName(application), pendingFolder = File(application.noBackupFilesDir, PENDING_FOLDER), previous = Thread.getDefaultUncaughtExceptionHandler(), ) Thread.setDefaultUncaughtExceptionHandler(handler) handler.sendPendingLater() } @Suppress("DEPRECATION") private fun versionName(context: Context): String = try { val manager = context.packageManager // getPackageInfo(String, Int) is deprecated since Android 13 (API 33) val info = if (Build.VERSION.SDK_INT >= 33) { manager.getPackageInfo(context.packageName, PackageManager.PackageInfoFlags.of(0)) } else { manager.getPackageInfo(context.packageName, 0) } // The server ignores a report without version info.versionName?.takeIf { it.isNotEmpty() } ?: "unknown" } catch (error: Exception) { "unknown" } private class Handler( private val projectKey: String, private val endpoint: String, private val appVersion: String, private val pendingFolder: File, private val previous: Thread.UncaughtExceptionHandler?, ) : Thread.UncaughtExceptionHandler { override fun uncaughtException(crashedThread: Thread, error: Throwable) { try { val body = formBody(error) val saved = save(body) // No network on the main thread: another thread sends it, a few seconds at most val sender = thread(name = "ubugtrack-crash") { if (post(body)) saved?.delete() } sender.join(TIMEOUT_MS + 1000L) } catch (ignored: Throwable) { // The crash reporter must never hide the crash } finally { if (previous != null) previous.uncaughtException(crashedThread, error) else exitProcess(1) } } private fun formBody(error: Throwable): String { val trace = StringWriter() error.printStackTrace(PrintWriter(trace)) val fields = linkedMapOf( "project_key" to projectKey, "logtitle" to error.toString(), "logfull" to trace.toString(), "device" to Build.DEVICE, "manufacturer" to Build.MANUFACTURER, "model" to Build.MODEL, "fingerprint" to Build.FINGERPRINT, "appversion" to appVersion, ) return fields.entries.joinToString("&") { (key, value) -> URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(value.orEmpty(), "UTF-8") } } fun post(body: String): Boolean { var connection: HttpURLConnection? = null return try { val bytes = body.toByteArray(Charsets.UTF_8) connection = (URI.create(endpoint).toURL().openConnection() as HttpURLConnection).apply { connectTimeout = TIMEOUT_MS readTimeout = TIMEOUT_MS requestMethod = "POST" doOutput = true setFixedLengthStreamingMode(bytes.size) setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8") } connection.outputStream.use { it.write(bytes) } connection.responseCode in 200..299 } catch (error: Exception) { false } finally { connection?.disconnect() } } // Crashes not sent yet, kept in the app files (not backed up) private fun save(body: String): File? = try { if (!pendingFolder.isDirectory) pendingFolder.mkdirs() // Only the last ones val files = pendingFolder.listFiles()?.sortedBy { it.name }.orEmpty() files.take(maxOf(0, files.size - MAX_PENDING + 1)).forEach { it.delete() } File(pendingFolder, "${System.currentTimeMillis()}.crash").apply { writeBytes(body.toByteArray(Charsets.UTF_8)) } } catch (error: Exception) { null } fun sendPendingLater() { thread(isDaemon = true, name = "ubugtrack-pending") { pendingFolder.listFiles()?.forEach { file -> val body = try { file.readText(Charsets.UTF_8) } catch (error: Exception) { null } // If it fails, it is sent again at the next launch if (body == null || post(body)) file.delete() } } } } }