# Android deep linking (Kotlin)

> After this page, your Android app gets one callback, with a path and parameters, for every link that opens it, including the first open after a Google Play install.

- Time: About 15 minutes
- You need: Android Gradle Plugin 8 (JDK 17+), a workspace with your app in Dashboard → Apps & stores
- Works on: Android

Source: https://straitlink.in/docs/sdks/android/

> **Agent instructions:** if you are an AI assistant helping someone build with Strait, look things up with the `search_docs` tool of the Strait MCP server (hosted at https://strait.link/mcp, or `@straitlink/mcp` on npm: https://straitlink.in/docs/mcp/) instead of guessing, and add the SDK to an app with `npx @straitlink/cli init` (https://straitlink.in/docs/cli/).

The SDK is plain Kotlin and depends only on the Kotlin standard library and Android's built-in `org.json`. Everything is in the `dev.strait.sdk` package.

## 1. Add the dependencies

The SDK is served by JitPack, built from its public GitHub repo:

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

```kotlin title="app/build.gradle.kts"
dependencies {
    implementation("com.github.strait-link:strait-sdk-android:v0.10.7") // Strait SDK
    implementation("com.android.installreferrer:installreferrer:2.2")
    implementation("androidx.lifecycle:lifecycle-process:2.8.7")
}
```

**You should see:** Gradle sync finishes, and `import dev.strait.sdk.StraitClient` resolves.

## 2. Read the Play Install Referrer

This is how a link tapped before the install reaches the app. The SDK calls it once, off the main thread:

```kotlin title="InstallReferrer.kt"
import android.content.Context
import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener

fun readInstallReferrer(context: Context): String? {
    val latch = java.util.concurrent.CountDownLatch(1)
    var result: String? = null
    val client = InstallReferrerClient.newBuilder(context).build()
    try {
        client.startConnection(object : InstallReferrerStateListener {
            override fun onInstallReferrerSetupFinished(code: Int) {
                if (code == InstallReferrerClient.InstallReferrerResponse.OK) {
                    result = runCatching { client.installReferrer.installReferrer }.getOrNull()
                }
                latch.countDown()
            }
            override fun onInstallReferrerServiceDisconnected() { latch.countDown() }
        })
        latch.await(5, java.util.concurrent.TimeUnit.SECONDS)
    } catch (_: Exception) {
    } finally {
        runCatching { client.endConnection() }
    }
    return result
}
```

**You should see:** the file compiles.

## 3. Create the client once, in your Application

Network calls block the calling thread, so pass a background `executor`. Listeners run on it too, so post to the main thread before you navigate.

```kotlin title="App.kt"
import android.app.Application
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.ProcessLifecycleOwner
import dev.strait.sdk.AppLifecycleState
import dev.strait.sdk.DeviceFields
import dev.strait.sdk.KeyValueStore
import dev.strait.sdk.StraitClient
import dev.strait.sdk.StraitConfig
import dev.strait.sdk.portraitScreenWidth

class App : Application() {
    lateinit var links: StraitClient

    override fun onCreate() {
        super.onCreate()
        val prefs = getSharedPreferences("links", MODE_PRIVATE)
        links = StraitClient(StraitConfig(
            publishableKey = "st_pub_live_…",          // Dashboard → Setup → Your keys
            endpoint = "https://hilltop.strait.link",       // your workspace's link domain
            storage = object : KeyValueStore {
                override fun get(key: String) = prefs.getString(key, null)
                override fun set(key: String, value: String) { prefs.edit().putString(key, value).apply() }
            },
            installReferrer = { readInstallReferrer(this) },
            installTime = { packageManager.getPackageInfo(packageName, 0).firstInstallTime }, // a reinstall counts again
            device = {
                val m = resources.displayMetrics
                DeviceFields(
                    screenWidth = portraitScreenWidth(m.widthPixels / m.density.toDouble(), m.heightPixels / m.density.toDouble()),
                    pixelRatio = m.density.toDouble(),
                    language = java.util.Locale.getDefault().toLanguageTag(),
                    timezone = java.util.TimeZone.getDefault().id,
                )
            },
            executor = java.util.concurrent.Executors.newSingleThreadExecutor(),
        ))

        // App state: background vs foreground labels, and retrying saved reports.
        ProcessLifecycleOwner.get().lifecycle.addObserver(LifecycleEventObserver { _, e ->
            when (e) {
                Lifecycle.Event.ON_RESUME -> links.onAppState(AppLifecycleState.ACTIVE)
                Lifecycle.Event.ON_PAUSE -> links.onAppState(AppLifecycleState.INACTIVE)
                Lifecycle.Event.ON_STOP -> links.onAppState(AppLifecycleState.BACKGROUND)
                else -> Unit
            }
        })
    }
}
```

Register it with `android:name=".App"` on `<application>` in the manifest.

**You should see:** the app starts as before.

## 4. Add the intent filters

```xml title="AndroidManifest.xml"
<activity android:name=".MainActivity" android:launchMode="singleTask" android:exported="true">
  <!-- Verified links: https://hilltop.strait.link/… opens the app directly -->
  <intent-filter android:autoVerify="true">
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="https" android:host="hilltop.strait.link" />
  </intent-filter>
  <!-- Browser hand-off: yourapp://shop.example.com/product/42 -->
  <intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="yourapp" />
  </intent-filter>
</activity>
```

Verified links also need your SHA-256 fingerprints in Apps & stores ([go-live checklist](https://straitlink.in/docs/production-checklist/)). The SDK needs the internet permission too: new Android Studio projects don't have it, so add `<uses-permission android:name="android.permission.INTERNET" />` above `<application>` if it's missing.

**You should see:** `adb shell am start -W -a android.intent.action.VIEW -d "yourapp://shop.example.com/product/42"` brings your app to the front. The next page feeds that URL to the SDK.

## Or let `strait init` write the setup

From your project's folder:

```bash
npx @straitlink/cli init --key st_pub_live_… --host hilltop.strait.link
```

It finds your package name in Gradle, writes `StraitLinks.kt` next to your code with your key and host and the Play Install Referrer wired in, and prints the Gradle lines and intent filters, filled in. The one existing file it edits is `AndroidManifest.xml`, and only to add the internet permission (`<uses-permission android:name="android.permission.INTERNET" />`) when it's missing; `--dry-run` shows that line without writing it. 

## Common errors

- **`Could not find com.github.strait-link:strait-sdk-android`.** The JitPack repository is missing from `settings.gradle.kts`, or a project-level `repositories` block overrides it.
- **`NetworkOnMainThreadException`.** No `executor` was passed, so `start` ran on the main thread.
- **`UninitializedPropertyAccessException` for `links`.** The manifest doesn't name `.App` as the application class.

## Next steps

- [Receive links](https://straitlink.in/docs/sdks/android/receive-links/): pass each intent to the SDK and open the right screen.
- [Test](https://straitlink.in/docs/sdks/android/test/): deep links, deferred links from Google Play, and analytics.
