Receive links on Android

After this page, every link that opens your Android app lands on its screen, from a cold start, from the background, and on the first open after a Play install.

On this page 5
  1. 1. Feed the SDK the launch intent and new intents
  2. 2. Check links that arrive while the app is open
  3. 3. Handle links that don't match
  4. Common errors
  5. Next steps
Time
About 10 minutes
You need
The client created in your Application (Install & set up)
Works on
Android

1. Feed the SDK the launch intent and new intents

This uses ComponentActivity, which new Android Studio projects already have. If yours doesn't, add implementation("androidx.activity:activity:1.9.3") to app/build.gradle.kts. Already on AppCompatActivity? Keep it: it works the same.

MainActivity.kt
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity

class MainActivity : ComponentActivity() {
    private val links get() = (application as App).links
    private val stopListening = mutableListOf<() -> Unit>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        stopListening += links.onLinkStart { runOnUiThread { showOpeningLink() } }
        // onLink replays earlier links to every new listener, and a rotation re-creates this activity: open each link once.
        stopListening += links.onLink { e ->
            runOnUiThread { if (e.matched && handled.add(e.id)) navigate(e.path, e.params) else hideOpeningLink() }
        }
        // Launched from closed: the intent's URL (or null). Runs the deferred check once per install.
        if (savedInstanceState == null) links.start(intent?.dataString)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        intent.dataString?.let(links::handleUrl)   // app was already running
    }

    override fun onDestroy() {
        stopListening.forEach { it() }   // this activity stops listening; the next one starts again
        stopListening.clear()
        super.onDestroy()
    }

    // Replace these three with your own loading UI and navigation.
    private fun showOpeningLink() { /* show a spinner */ }
    private fun hideOpeningLink() { /* hide it */ }
    private fun navigate(path: String?, params: Map<String, String>?) {
        hideOpeningLink()
        val id = path?.removePrefix("/product/")?.takeIf { it != path } ?: return
        startActivity(Intent(this, ProductActivity::class.java).putExtra("id", id))
    }

    // Survives a rotation (it outlives the activity), so a replayed link isn't opened twice.
    companion object { private val handled = mutableSetOf<String>() }
}

onLink replays past events to late subscribers, and both onLink and onLinkStart return an unsubscribe function. That's why the activity unsubscribes in onDestroy and opens each event id once: after a rotation the new activity gets the last link again and must not navigate a second time.

You should see: with the app closed, adb shell am start -W -a android.intent.action.VIEW -d "yourapp://shop.example.com/product/42" opens ProductActivity with id 42.

Keep the app in the foreground and run the same adb command again. singleTask delivers it to onNewIntent.

You should see: ProductActivity opens again, and the event's appState is foreground (or background if you'd left the app).

When matched is false, reason says why: not_found, expired, password_protected, no_match, network or invalid_url. The activity is already showing, so just hide the spinner, as above.

You should see: a link to a slug that doesn't exist leaves you on the main screen with no spinner.

Common errors

  • Links open a second copy of the activity. android:launchMode="singleTask" is missing, so onNewIntent never runs.
  • Rotating the phone runs the deferred check again, or opens the product screen again. Call start only when savedInstanceState == null, unsubscribe in onDestroy, and skip an event id you've already handled, as above.
  • CalledFromWrongThreadException. Navigation ran on the SDK's executor. Wrap it in runOnUiThread.

Next steps