# Android quickstart

> Count events from an Android app through your own server and the server API, with a consent question, as Insights Orbit has no Android SDK yet.

Source: https://docs.bifrostorbit.com/insights/developers/quickstart-android/

Insights Orbit has no SDK for Android yet. You can still count what people do in your app: the app tells your own server, and your server sends the event to the [server API](https://docs.bifrostorbit.com/insights/developers/server-api/) with an API key. In about 20 minutes you build a Jetpack Compose app for Northwilds that asks before counting, then sends **App opened** and **Brochure requested**.

The API key never goes into the app. Anyone can unpack an app and read what is inside it, and a key that sends events would let them send anything.

**Tested with:** Android Gradle plugin 9.5.1, Gradle 9.8.2, Kotlin 2.4.21, Compose BOM 2026.09.00, JDK 17, an Android 16 (API 36) emulator, and Node.js 24 for the server.

## Before you start

You need:

- **A site in Insights Orbit** for the app. Events from your server carry no page address, so the site's addresses don't matter here. See [Add your first site](https://docs.bifrostorbit.com/insights/everyone/add-a-site/).
- **The site key**, from the site's **Install** screen.
- **An API key that sends events.** An Admin makes it under **API keys** with **Send events** ticked. It starts with `ins_live_` and is a secret. See [API keys](https://docs.bifrostorbit.com/insights/developers/api-keys/).
- **A server you control**, with Node.js 20 or later for this guide's example. Any language works: it is one `POST` request.
- **Android Studio**, or the Android SDK and JDK 17 or later.

## What you get, and what you don't

Server events count in **Events**, goals, revenue and the monthly events, like events from a website. They have no visitor and no visit, so the app doesn't change the numbers of visitors, visits or bounce rate, and there are no countries or devices: their device is `server`. Each event counts as a goal completion of its own.

## 1. Add an endpoint to your server

The app sends `{ id, name, properties }` to your server. The server checks the name against a list, adds the site key and passes it on with the API key. This is the same endpoint as in the [iOS quickstart](https://docs.bifrostorbit.com/insights/developers/quickstart-ios/), so one serves both apps:

```js
// analytics-relay.mjs
import { createServer } from 'node:http'

const INSIGHTS = process.env.INSIGHTS_URL ?? 'https://api.bifrostorbit.com/insights/v1'
const ALLOWED = new Set(['App opened', 'Brochure requested', 'Trip booked'])

createServer(async (request, response) => {
  if (request.method !== 'POST' || request.url !== '/analytics') return response.writeHead(404).end()
  let body = ''
  for await (const chunk of request) {
    body += chunk
    if (body.length > 10_000) return response.writeHead(413).end()
  }
  let event
  try {
    event = JSON.parse(body)
  } catch {
    return response.writeHead(400).end()
  }
  if (!ALLOWED.has(event?.name)) return response.writeHead(400).end()
  const answer = await fetch(`${INSIGHTS}/server/events`, {
    method: 'POST',
    headers: { authorization: `Bearer ${process.env.INSIGHTS_API_KEY}`, 'content-type': 'application/json' },
    body: JSON.stringify({ site: process.env.INSIGHTS_SITE, events: [{ id: event.id, name: event.name, properties: event.properties }] }),
  }).catch(() => null)
  if (!answer?.ok) console.warn('Insights Orbit did not take the event', answer?.status, await answer?.text())
  response.writeHead(answer?.ok ? 202 : 502).end()
}).listen(process.env.PORT ?? 3000)
```

Start it with the site key and the API key:

```bash
INSIGHTS_SITE=SITE_KEY INSIGHTS_API_KEY=ins_live_… node analytics-relay.mjs
```

- **The list of names** stops anyone who finds the endpoint from filling your reports with made-up events. Add each event the app sends.
- **`id`** comes from the app. The server API counts an id it has already seen in the last eight days once, so the app or your server can safely send again.
- **If your server already has an API**, add the same route there instead, as the [Laravel quickstart](https://docs.bifrostorbit.com/insights/developers/quickstart-laravel/) does in PHP.

**Check it:** `curl -X POST localhost:3000/analytics -d '{"id":"check-1","name":"App opened"}'` answers `202`, and a name that isn't on the list answers `400`.

## 2. Create the project

In Android Studio, select **New Project › Empty Activity** and use:

- **Name:** `Northwilds`
- **Package name:** `com.northwilds.app`
- **Minimum SDK:** API 24
- **Build configuration language:** Kotlin DSL

Replace the generated Gradle files and manifest with the ones below. You can delete the generated `ui/theme` folder, as the app uses the default Material 3 theme.

```kotlin
// settings.gradle.kts
pluginManagement {
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
}

dependencyResolutionManagement {
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.name = "Northwilds"
include(":app")
```

```kotlin
// build.gradle.kts
plugins {
    id("com.android.application") version "9.5.1" apply false
    id("org.jetbrains.kotlin.plugin.compose") version "2.4.21" apply false
}
```

```properties
# gradle.properties
org.gradle.jvmargs=-Xmx2g
android.useAndroidX=true
```

```kotlin
// app/build.gradle.kts
import java.util.Properties

plugins {
    id("com.android.application")
    id("org.jetbrains.kotlin.plugin.compose")
}

val local = Properties().apply {
    rootProject.file("local.properties").takeIf { it.exists() }?.inputStream()?.use(::load)
}

android {
    namespace = "com.northwilds.app"
    compileSdk = 37

    defaultConfig {
        applicationId = "com.northwilds.app"
        minSdk = 24
        targetSdk = 36
        versionCode = 1
        versionName = "1.0"

        buildConfigField("String", "ANALYTICS_URL", "\"${local.getProperty("analytics.url") ?: "https://northwilds.com/analytics"}\"")
    }

    buildFeatures {
        compose = true
        buildConfig = true
    }
}

dependencies {
    implementation(platform("androidx.compose:compose-bom:2026.09.00"))
    implementation("androidx.compose.material3:material3")
    implementation("androidx.activity:activity-compose:1.13.0")
}
```

```xml
<!-- app/src/main/AndroidManifest.xml -->
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:label="Northwilds"
        android:theme="@android:style/Theme.Material.Light.NoActionBar">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
```

## 3. Point the app at your server

`ANALYTICS_URL` is your server's `https` address, `https://northwilds.com/analytics` in this guide. While you build, point it at the server on your computer in `local.properties`, which stays out of source control. The emulator reaches your computer at `10.0.2.2`:

```properties
# local.properties
analytics.url=http://10.0.2.2:3000/analytics
```

Android refuses plain `http` by default. Allow it in debug builds only, with a second manifest that release builds leave out:

```xml
<!-- app/src/debug/AndroidManifest.xml -->
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <application android:usesCleartextTraffic="true" />

</manifest>
```

## 4. Add the analytics client

```kotlin
// app/src/main/java/com/northwilds/app/Analytics.kt
package com.northwilds.app

import android.content.Context
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL
import java.util.UUID
import java.util.concurrent.Executors

object Analytics {
    private val worker = Executors.newSingleThreadExecutor()

    fun allowed(context: Context): Boolean? =
        prefs(context).takeIf { it.contains("allowed") }?.getBoolean("allowed", false)

    fun setAllowed(context: Context, allowed: Boolean) {
        prefs(context).edit().putBoolean("allowed", allowed).apply()
    }

    fun track(context: Context, name: String, properties: Map<String, String> = emptyMap()) {
        if (allowed(context) != true) return
        val body = JSONObject()
            .put("id", UUID.randomUUID().toString())
            .put("name", name)
            .put("properties", JSONObject(properties))
            .toString()
        worker.execute {
            runCatching {
                val connection = URL(BuildConfig.ANALYTICS_URL).openConnection() as HttpURLConnection
                connection.requestMethod = "POST"
                connection.connectTimeout = 5_000
                connection.readTimeout = 5_000
                connection.doOutput = true
                connection.setRequestProperty("Content-Type", "application/json")
                connection.outputStream.use { it.write(body.toByteArray()) }
                connection.responseCode
                connection.disconnect()
            }
        }
    }

    private fun prefs(context: Context) = context.getSharedPreferences("analytics", Context.MODE_PRIVATE)
}
```

- **No extra libraries:** `HttpURLConnection` and `org.json` come with Android.
- **Nothing is sent until the person agrees** (step 5): `allowed` is `null` before they answer, and `track` only sends when it is `true`.
- **Requests run on a background thread** and errors are ignored, so analytics never slows the app down or stops it.
- **Properties** are text here. Never send names, email addresses or other personal data. [Send your own events](https://docs.bifrostorbit.com/insights/developers/send-events/) has the limits.

## 5. Ask before counting

Insights Orbit reads nothing from the phone: the only data is what your app sends. Whether you ask first is your decision with your adviser; this app asks once and remembers the answer.

```kotlin
// app/src/main/java/com/northwilds/app/MainActivity.kt
package com.northwilds.app

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent { MaterialTheme { TripScreen() } }
    }
}

@androidx.compose.runtime.Composable
fun TripScreen() {
    val context = LocalContext.current
    var asking by remember { mutableStateOf(Analytics.allowed(context) == null) }
    var sent by remember { mutableStateOf(false) }

    LaunchedEffect(Unit) { Analytics.track(context, "App opened") }

    Column(Modifier.fillMaxSize().padding(24.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
        Text("Lofoten ski touring week", style = MaterialTheme.typography.headlineSmall)
        Text("Seven days of ski touring above the fjords, from €2,450.")
        Button(
            enabled = !sent,
            onClick = {
                Analytics.track(context, "Brochure requested", mapOf("trip" to "lofoten-ski-touring"))
                sent = true
            },
        ) { Text(if (sent) "On its way" else "Send me the brochure") }
    }

    if (asking) {
        AlertDialog(
            onDismissRequest = {},
            title = { Text("May we count how you use the app?") },
            text = { Text("We keep no personal data.") },
            confirmButton = {
                TextButton(onClick = {
                    Analytics.setAllowed(context, true)
                    asking = false
                    Analytics.track(context, "App opened")
                }) { Text("Yes") }
            },
            dismissButton = {
                TextButton(onClick = {
                    Analytics.setAllowed(context, false)
                    asking = false
                }) { Text("No thanks") }
            },
        )
    }
}
```

- **Yes** stores the answer and sends **App opened** at once. Every later launch sends it too.
- **No thanks** stores the answer, and `track` sends nothing from then on. Give people a switch in your settings screen that calls `Analytics.setAllowed`, so they can change their mind.

## 6. Check that events arrive

Run the app on the emulator, select **Yes**, then **Send me the brochure**.

- **In Insights Orbit:** **Events** lists **App opened** and **Brochure requested** within a few seconds. Open one to see its details, such as `trip`.
- **On your server:** a refused event prints `Insights Orbit did not take the event` with the status, such as `401` for a wrong key.
- **From the API**, on the Growth plan, with a key that reads events:

```bash
curl "https://api.bifrostorbit.com/insights/v1/events?site=SITE_KEY&name=Brochure%20requested" \
  -H "Authorization: Bearer ins_live_…"
```

The event comes back with `"device": "server"` and its `properties`.

To try **No thanks**, clear the app's storage under **Settings › Apps › Northwilds › Storage** and open it again: the question comes back, and after **No thanks** nothing reaches your server.

## Next steps

- [Send events from a server](https://docs.bifrostorbit.com/insights/developers/server-api/): every field, including `revenue`, `timestamp` and `userId`.
- [Set up goals](https://docs.bifrostorbit.com/insights/everyone/goals/): count **Brochure requested** as success.
- [iOS quickstart](https://docs.bifrostorbit.com/insights/developers/quickstart-ios/): the same for iPhone.
- [Read raw events](https://docs.bifrostorbit.com/insights/developers/raw-event-api/): every event for your own data tools.
