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.

On this page 7
  1. 1. Add the dependencies
  2. 2. Read the Play Install Referrer
  3. 3. Create the client once, in your Application
  4. 4. Add the intent filters
  5. Or let strait init write the setup
  6. Common errors
  7. Next steps

One prompt · for your AI coding tool

Prompt
Add Strait deep links (and deferred deep links) to this Android app.

Read https://straitlink.in/docs/sdks/android/ and follow it exactly. If anything here disagrees with that page, the page wins.
My link domain is https://<your-handle>.strait.link and my publishable key is st_pub_live_… (from Dashboard → Setup → Your keys: https://app.straitlink.in/setup#keys).

Rules:
- Use only the publishable key here. Never put a secret key (st_live_…) in app or website code.
- Route every link from the SDK's onLink callback (the event's path and params). Do not add a second deep-link handler for the link domain.
- Create the client once in the Application class. Pass the launch intent to start() in onCreate and later intents to handleUrl() in onNewIntent.

Steps:
1. Install the SDK with the command on that page.
2. Let the phone open the app: an App Links intent filter (autoVerify) for my link domain and a second intent filter for my custom scheme, on a singleTask activity.
3. Create the client once with publishableKey and endpoint, call start() once at launch, and subscribe to onLink.
4. Map link paths to screens in this codebase.

Finish by telling me exactly how to check it:
- curl https://<your-handle>.strait.link/.well-known/assetlinks.json and /.well-known/apple-app-site-association list my app
- adb shell pm get-app-links <package> says verified after a fresh install
- a tap from WhatsApp on a real phone opens the right screen and onLink fires with matched: true

The full prompt, and the others

By hand · the install line

app/build.gradle.kts
implementation("com.github.strait-link:strait-sdk-android:v0.10.7")

Then follow the steps below

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

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:

settings.gradle.kts
dependencyResolutionManagement {
    repositories {
        google()
        mavenCentral()
        maven("https://jitpack.io")
    }
}
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:

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.

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

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). 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:

Terminal
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: pass each intent to the SDK and open the right screen.
  • Test: deep links, deferred links from Google Play, and analytics.