Skip to content
manihqPublic

About

Lightweight Android analytics SDK with event batching, Room-backed offline storage and WorkManager uploads, built on Kotlin coroutines and Flow.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Beacon

Build JitPack minSdk

A small analytics SDK for Android. You track events; Beacon stores them on disk, batches them and uploads them in the background, even if the app is offline or gets killed.

Beacon.track("checkout_started", mapOf("items" to 3, "total" to 1499.0))
  • Custom events with typed properties (strings, numbers, booleans, enums, lists, maps)
  • Batching: events go out in groups, not one request each
  • Offline storage: events are written to SQLite first, so nothing is lost when there's no network or the process dies
  • Background upload: WorkManager sends batches when the device is online, with exponential backoff
  • Bring your own backend: POST to any URL, or plug in your own uploader
  • Super properties: attach properties like a plan or experiment group to every event
  • Opt-out: one call stops tracking and deletes anything not yet sent
  • Small footprint: no Retrofit, OkHttp, Room or Gson. It only needs WorkManager, Lifecycle and coroutines.

Setup

// settings.gradle.kts
dependencyResolutionManagement {
    repositories {
        google()
        mavenCentral()
        maven("https://jitpack.io")
    }
}

// app/build.gradle.kts
dependencies {
    implementation("com.github.manihq.Beacon:beacon:1.0.0")
}

Initialise once in your Application:

class App : Application() {
    override fun onCreate() {
        super.onCreate()
        Beacon.initialize(
            this,
            BeaconConfig.Builder("https://collect.example.com/v1/batch")
                .header("Authorization", "Bearer ${BuildConfig.ANALYTICS_KEY}")
                .batchSize(20)
                .build(),
        )
    }
}

Usage

Beacon.track("song_played", mapOf("id" to song.id, "duration" to 214, "shuffle" to true))

Beacon.identify(user.id)  // attached to every event from now on
Beacon.register(mapOf("plan" to "pro"))  // super properties, sent with every event
Beacon.unregister("plan")
Beacon.reset()            // on logout: clears the user and super properties, new anonymous id
Beacon.flush()            // send now, without waiting for a full batch

A property passed to track() wins over a super property with the same name. Super properties are kept in memory, so register them again on each launch (in Application.onCreate, after initialize).

Privacy

Beacon.optOut()      // stop tracking and delete queued events; remembered across launches
Beacon.optIn()       // resume
Beacon.isOptedOut()

reset() doesn't change the opt-out choice.

Every method is non-blocking and safe to call from any thread. It works from Java too (Beacon.track("x")).

How it works

track() ──► validate ──► serialise ──► SQLite queue
                                          │
          batch full / timer / app backgrounded
                                          ▼
                              WorkManager (needs network)
                                          │
                              upload oldest N events
                       ┌──────────────────┼──────────────────┐
                    2xx: delete     401/403/408/429/5xx:   other 4xx: split
                                    keep and back off    batch, drop only
                                                         the bad events
  • Ordering. Writes go through a single-threaded dispatcher and are read back in insertion order.
  • No double sends. Uploads are serialised with a mutex and run as unique work, so a manual flush and a scheduled one can't send the same batch twice. Each event has a UUID the server can use to drop duplicates if a response is lost.
  • Poison events. When the server refuses a batch with a 4xx, Beacon splits it in half and resends each half until it finds the event(s) being refused. Only those are dropped, so one bad event can't block the queue or take the good events in its batch down with it.
  • Auth errors keep events. 401 and 403 are retried rather than dropped: a wrong or expired API key is a config problem, and the events go out once it's fixed.
  • Snapshots. Properties are serialised when you call track(), so changing a list or map you passed in afterwards doesn't change the event.
  • Limits. Events are ignored (with a warning in Logcat) if the name is blank or over 128 characters, there are more than 100 properties, or the serialised event is over 32 KB. NaN and infinite numbers are sent as null.
  • Bounded storage. Once maxQueueSize is reached, the oldest events are dropped.
  • When it flushes: when a full batch is queued, every flushInterval while the app is in the foreground, when the app goes to the background, and on the next launch for anything left over.

Request format

{
  "sentAt": 1732800000000,
  "context": {
    "library": { "name": "beacon-android", "version": "1.0.0" },
    "os": { "name": "Android", "version": "15", "sdk": 35 },
    "device": { "manufacturer": "Google", "model": "Pixel 8" },
    "app": { "package": "com.example", "version": "2.3.0", "build": 230 },
    "locale": "en-IN"
  },
  "batch": [
    {
      "id": "6f1c…",
      "event": "checkout_started",
      "timestamp": 1732799990000,
      "anonymousId": "b2a4…",
      "userId": "user-42",
      "properties": { "items": 3, "total": 1499.0 }
    }
  ]
}

Bodies are gzipped by default (Content-Encoding: gzip). Turn that off with .gzip(false).

Custom uploader

To send events through an existing API client or a third-party service, skip the endpoint and pass an EventUploader:

BeaconConfig.Builder()
    .uploader { events ->
        val response = api.sendEvents(events.map { it.json })
        when {
            response.isSuccessful -> UploadResult.Success
            response.code() in 400..499 -> UploadResult.Rejected("HTTP ${response.code()}")
            else -> UploadResult.Retry
        }
    }
    .build()

Configuration

build() throws IllegalArgumentException for an invalid setting, including an endpoint that isn't an http(s) URL.

Option Default
batchSize 20 Events per request; reaching it triggers an upload
flushInterval 30 s Periodic flush while in the foreground
maxQueueSize 1000 Oldest events are dropped beyond this
flushOnBackground true Flush when the app is backgrounded
gzip true Compress request bodies
logLevel Warn None, Error, Warn or Debug (Logcat tag Beacon)

Project layout

beacon/
  Beacon.kt, BeaconConfig.kt, EventUploader.kt   public API
  internal/
    pipeline/   EventPipeline: queueing, batching, upload loop
    store/      SQLite-backed event queue
    upload/     HTTP uploader, WorkManager worker and scheduler
sample/         demo app that logs batches to Logcat

The pipeline depends only on interfaces (EventStore, EventUploader, UploadScheduler), so its batching and retry logic is unit-tested on the JVM with in-memory fakes.

./gradlew build    # compile, lint, unit tests

License

MIT, see LICENSE.

About

Lightweight Android analytics SDK with event batching, Room-backed offline storage and WorkManager uploads, built on Kotlin coroutines and Flow.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages