// EarnedStats for Android apps (Kotlin and Java, Views and Jetpack Compose). // // EarnedStats.configure(application, "SITE_ID") // in Application.onCreate // EarnedStats.screen("Home") // EarnedStats.track("signup", mapOf("plan" to "pro")) // // Screens are sent as app:///. One random install id, made on first launch and kept only in the // app, makes one install one visitor. No advertising id, no Android id, nothing to ask permission for. package com.earnedstats import android.app.Activity import android.app.Application import android.content.Context import android.content.SharedPreferences import android.content.res.Configuration import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Handler import android.os.Looper import android.util.Log import org.json.JSONArray import org.json.JSONObject import java.net.HttpURLConnection import java.net.URL import java.util.UUID import java.util.concurrent.Executors import java.util.concurrent.TimeUnit object EarnedStats { const val SDK_VERSION = "1.0.0" private const val MAX_QUEUE = 500 private const val MAX_AGE_MS = 48L * 3_600_000 private val CAMPAIGN_KEYS = setOf("utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", "ref", "via") private val executor = Executors.newSingleThreadScheduledExecutor() private val main = Handler(Looper.getMainLooper()) private lateinit var prefs: SharedPreferences private var siteId = "" private var endpoint = "" private var appId = "" private var appVersion: String? = null private var tablet = false private var screenWidth = 0 private var debug = false private var configured = false private val queue = ArrayList() private var pendingCampaign: String? = null private var lastScreen = "/" private var started = 0 private var foregroundSince = 0L private val visitorCallbacks = ArrayList<(String) -> Unit>() /** * Start tracking. Call once in Application.onCreate. * @param siteId the site id from EarnedStats, Settings, Tracking code. * @param host where events are sent; your own domain if you proxy it. * @param appId defaults to the package name. Must match the app id the site was added with (or one in its settings). * @param autoScreens send a screen view for each Activity that opens, named after its class (off for Compose apps, * which call screen() from their navigation). * @param debug log events instead of sending them. */ @JvmStatic @JvmOverloads fun configure( application: Application, siteId: String, host: String = "https://earnedstats.com", appId: String? = null, autoScreens: Boolean = false, debug: Boolean = false, ) { val ctx = application.applicationContext prefs = ctx.getSharedPreferences("earnedstats", Context.MODE_PRIVATE) this.siteId = siteId this.endpoint = host.trimEnd('/') + "/api/event" this.appId = (appId ?: ctx.packageName).lowercase() this.debug = debug this.appVersion = try { @Suppress("DEPRECATION") ctx.packageManager.getPackageInfo(ctx.packageName, 0).versionName } catch (e: Exception) { null } val config = ctx.resources.configuration tablet = (config.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE screenWidth = config.screenWidthDp executor.execute { loadQueue() } configured = true application.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks { override fun onActivityStarted(activity: Activity) { if (started++ == 0) foregroundSince = System.currentTimeMillis() } override fun onActivityStopped(activity: Activity) { if (--started == 0) backgrounded() } override fun onActivityResumed(activity: Activity) { if (autoScreens) screen(activity.javaClass.simpleName.removeSuffix("Activity").ifEmpty { "Main" }) } override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { activity.intent?.data?.let { open(it) } } override fun onActivityPaused(activity: Activity) {} override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {} override fun onActivityDestroyed(activity: Activity) {} }) executor.scheduleWithFixedDelay({ flushNow() }, 10, 10, TimeUnit.SECONDS) } /** A screen view. "Home" is the page /Home, "settings/billing" is /settings/billing. */ @JvmStatic @JvmOverloads fun screen(name: String, params: Map = emptyMap()) { val clean = "/" + name.trim('/', ' ').replace(' ', '-') val query = Uri.Builder().apply { params.forEach { (k, v) -> appendQueryParameter(k, v) } }.build().encodedQuery val parts = listOfNotNull(query?.takeIf { it.isNotEmpty() }, pendingCampaign) pendingCampaign = null lastScreen = clean enqueue("pageview", if (parts.isEmpty()) clean else clean + "?" + parts.joinToString("&"), JSONObject()) } /** A goal or custom event, with up to 10 properties. */ @JvmStatic @JvmOverloads fun track(name: String, properties: Map = emptyMap()) { val extra = JSONObject().put("n", name.take(64)) if (properties.isNotEmpty()) extra.put("p", JSONObject(properties)) enqueue("goal", lastScreen, extra) } /** Tie this install to your own user, so their visits and payments show on one profile. */ @JvmStatic @JvmOverloads fun identify(userId: String, email: String? = null, name: String? = null) { val p = JSONObject().put("user_id", userId) email?.let { p.put("email", it) } name?.let { p.put("name", it) } enqueue("identify", lastScreen, JSONObject().put("p", p)) } /** A deep link or app link the app was opened with: its utm_ and ref parameters credit the next screen view. */ @JvmStatic fun open(uri: Uri) { val q = Uri.Builder() var any = false try { for (k in uri.queryParameterNames) if (k in CAMPAIGN_KEYS) { q.appendQueryParameter(k, uri.getQueryParameter(k)); any = true } } catch (e: UnsupportedOperationException) { return } if (any) pendingCampaign = q.build().encodedQuery } /** * The Play Store install referrer ("utm_source=...&utm_medium=..."), from the Play Install Referrer library: * credits the first screen view to the campaign that brought the install. Sent once per install. */ @JvmStatic fun installReferrer(referrer: String) { if (!configured || prefs.getBoolean("es_referrer_done", false)) return prefs.edit().putBoolean("es_referrer_done", true).apply() val q = Uri.parse("app://x/?$referrer") open(q) } /** This install's visitor id, known after the first event is sent. Give it to RevenueCat or your checkout as es_visitor_id. */ @JvmStatic val visitorId: String? get() = if (configured) prefs.getString("es_visitor", null) else null /** Called on the main thread with the visitor id as soon as it is known (at once if it already is). */ @JvmStatic fun onVisitorId(callback: (String) -> Unit) { val v = visitorId if (v != null) callback(v) else synchronized(visitorCallbacks) { visitorCallbacks.add(callback) } } /** Stop or resume sending (an in-app analytics opt out). Kept across launches. */ @JvmStatic var enabled: Boolean get() = !configured || !prefs.getBoolean("es_disabled", false) set(value) { if (!configured) return prefs.edit().putBoolean("es_disabled", !value).apply() if (!value) executor.execute { queue.clear(); saveQueue() } } /** Send what is queued now (also done every 10 seconds and when the app goes to the background). */ @JvmStatic fun flush() = executor.execute { flushNow() } private val installId: String get() = prefs.getString("es_install", null) ?: UUID.randomUUID().toString().also { prefs.edit().putString("es_install", it).apply() } private fun enqueue(type: String, path: String, extra: JSONObject) { if (!configured || !enabled) return val e = extra.put("t", type).put("path", path).put("ts", System.currentTimeMillis()) executor.execute { queue.add(e) while (queue.size > MAX_QUEUE) queue.removeAt(0) saveQueue() if (type != "pageview" || queue.size >= 20) flushNow() else executor.schedule({ flushNow() }, 1, TimeUnit.SECONDS) } } private fun backgrounded() { if (foregroundSince > 0) { val ms = System.currentTimeMillis() - foregroundSince if (ms >= 1000) enqueue("ping", lastScreen, JSONObject().put("d", minOf(ms, 600_000L))) } foregroundSince = 0 flush() } /** Runs on the executor only. Sends oldest first; network failures stay queued, refused events (4xx) are dropped. */ private fun flushNow() { while (queue.isNotEmpty()) { val e = queue[0] val age = System.currentTimeMillis() - e.optLong("ts") if (age > MAX_AGE_MS) { queue.removeAt(0); continue } val body = JSONObject() .put("w", siteId) .put("t", e.optString("t")) .put("u", "app://$appId${e.optString("path", "/")}") .put("sw", screenWidth) .put("m", meta()) if (age > 2000) body.put("ago", age) for (k in listOf("n", "p", "d", "r")) if (e.has(k)) body.put(k, e.get(k)) if (debug) { Log.i("EarnedStats", "debug, not sent: $body") queue.removeAt(0) continue } val status = post(body) ?: break // offline: try again later if (status >= 500) break queue.removeAt(0) } saveQueue() } private fun post(body: JSONObject): Int? { var conn: HttpURLConnection? = null return try { conn = (URL(endpoint).openConnection() as HttpURLConnection).apply { requestMethod = "POST" connectTimeout = 15_000 readTimeout = 15_000 doOutput = true setRequestProperty("Content-Type", "application/json") setRequestProperty("User-Agent", "EarnedStats-Android/$SDK_VERSION") } conn.outputStream.use { it.write(body.toString().toByteArray()) } val status = conn.responseCode if (status in 200..299) { val text = conn.inputStream.bufferedReader().use { it.readText() } val v = try { JSONObject(text).optString("v") } catch (e: Exception) { "" } if (v.isNotEmpty() && v != prefs.getString("es_visitor", null)) { prefs.edit().putString("es_visitor", v).apply() val callbacks = synchronized(visitorCallbacks) { visitorCallbacks.toList().also { visitorCallbacks.clear() } } main.post { callbacks.forEach { it(v) } } } } status } catch (e: Exception) { null } finally { conn?.disconnect() } } private fun meta(): JSONObject = JSONObject() .put("i", installId) .put("os", "android") .put("osv", Build.VERSION.RELEASE) .put("dev", if (tablet) "tablet" else "mobile") .put("sdk", "android/$SDK_VERSION") .apply { appVersion?.let { put("av", it) } } private fun loadQueue() { val raw = prefs.getString("es_queue", null) ?: return try { val arr = JSONArray(raw) for (i in 0 until arr.length()) queue.add(arr.getJSONObject(i)) } catch (e: Exception) {} } private fun saveQueue() { prefs.edit().putString("es_queue", JSONArray(queue).toString()).apply() } }