Deferred deep linking on Android and iOS
Deferred deep linking with Brevily: open the right screen after an install through the Play install referrer or Get the app, and report app opens.
On this page
Deferred deep linking opens the right screen of your app the first time it launches after an install, even though the app wasn't there when the link was tapped. With Brevily, Android gets the screen through the Google Play install referrer, and iPhone gets it when the visitor taps Get the app, which copies the link for the app to read. This guide shows the first-launch code for both, then how an app that opens straight from your domain reports each open with POST /events/open.
Before you start: the link needs a deep link with The app store as its fallback (see deep links to app screens), and your app needs its record in Brevily (add a mobile app). Your app's calls use its app key, with nothing to sign; keep API errors to hand. Opens and installs can be reported only for links on your own domains picked for the app.
How deferred deep linking works in Brevily
When a phone without the app taps a deep-linked short link, Brevily counts the click, then sends the phone to the store with what the app needs to find the screen later:
- Android: the Play Store address carries a
referrerwith the path (brv_path). Google Play hands it to the app after the install, and the app reads it once on first launch. - iPhone: the App Store passes nothing to a fresh install, so the short link's page offers Get the app. The tap copies the app's own link, such as
exampleapp://offers/autumn, then opens the App Store. On first launch the app reads it from the clipboard. - A web fallback carries nothing to a later install, on either phone.
On a link with Track events switched on (on its Settings tab), both also carry the click as brv_click, so the app can report the install against it. Brevily never matches a visit to an install by device or network address: on iPhone, only visitors who tap Get the app and let the app paste are covered.
[screenshot: the iPhone page with Open in the app, Get the app and the line under them]
What you need
- A plan with deep links. Reporting opens also needs Universal Links and App Links; reporting installs needs events. See pricing.
- Android: Google's Play Install Referrer library, and the app's Play Store address on its Brevily record.
- iOS: iOS 16 or later for the system Paste button (
UIPasteControl), and the App Store address on the record. - For opens and installs: the app's publishable key (
brv_pk_…), from Mobile apps › your app › Count taps that open the app. It's safe to ship in the app. - Your organisation's code, from Settings › General, under Code.
Android: read the Play install referrer
Google Play gives the app the referrer once decoded, so it reads as a query string:
brv_click=<the click>&brv_path=%2Foffers%2Fautumnbrv_click is there only on a link with Track events. Nothing reaches the app unless it asks, so read the referrer on first launch:
// build.gradle.kts// implementation("com.android.installreferrer:installreferrer:[version]")import android.content.Contextimport android.net.Uriimport android.os.RemoteExceptionimport com.android.installreferrer.api.InstallReferrerClientimport com.android.installreferrer.api.InstallReferrerClient.InstallReferrerResponseimport com.android.installreferrer.api.InstallReferrerStateListenerfun readInstallReferrer(context: Context, open: (path: String) -> Unit, keepClick: (String) -> Unit) { val prefs = context.getSharedPreferences("brevily", Context.MODE_PRIVATE) if (prefs.getBoolean("referrer_read", false)) return // first launch only val done = { prefs.edit().putBoolean("referrer_read", true).apply() } val client = InstallReferrerClient.newBuilder(context).build() client.startConnection(object : InstallReferrerStateListener { override fun onInstallReferrerSetupFinished(code: Int) { when (code) { InstallReferrerResponse.OK -> try { val referrer = client.installReferrer.installReferrer val q = Uri.parse("?$referrer") q.getQueryParameter("brv_click")?.let(keepClick) // kept whole, for the install q.getQueryParameter("brv_path")?.let(open) // e.g. "/offers/autumn" done() } catch (e: RemoteException) { // the Play Store went away: try again on the next launch } InstallReferrerResponse.FEATURE_NOT_SUPPORTED -> done() // no Play Store here else -> Unit // SERVICE_UNAVAILABLE and the rest: try again next launch } client.endConnection() } override fun onInstallReferrerServiceDisconnected() {} })}Send brv_path through the same router as the app's own exampleapp:// links, so one handler serves both.
Only an install from the Play Store page the link opened carries the values. An install from Android Studio, or one found by searching the store, has no brv_path, and the app should open its start screen.
iOS: pick up the link "Get the app" copied
The tap copies exactly the address an installed app would have been opened with:
exampleapp://offers/autumnexampleapp://offers/autumn?brv_click=<the click> (with Track events)Safari lets a page write to the clipboard only during a tap, so the copy happens in the tap itself. If it's refused, the button still opens the App Store; the visitor just arrives without the link.
On first launch, read the clipboard once. Reading it directly shows the system's paste prompt; the system Paste button reads it without one, because the person's own tap is the permission:
import UIKitimport UniformTypeIdentifiers/// First launch only: offer to pick up the link "Get the app" copied.@available(iOS 16.0, *) // UIPasteControlfinal class WelcomeViewController: UIViewController { private let scheme = "exampleapp" // the iOS app's "Opens with" in Link setup › Mobile apps private let checkedKey = "brevily.clipboard.checked" override func viewDidLoad() { super.viewDidLoad() let defaults = UserDefaults.standard guard !defaults.bool(forKey: checkedKey) else { return } defaults.set(true, forKey: checkedKey) // look once guard UIPasteboard.general.hasStrings else { return } // asks nothing // The system Paste button reads the clipboard without a prompt. pasteConfiguration = UIPasteConfiguration( acceptableTypeIdentifiers: [UTType.plainText.identifier]) let paste = UIPasteControl(configuration: UIPasteControl.Configuration()) paste.target = self view.addSubview(paste) // beside a line such as "Continue where you left off" } override func paste(itemProviders: [NSItemProvider]) { guard let provider = itemProviders.first, provider.canLoadObject(ofClass: String.self) else { return } _ = provider.loadObject(ofClass: String.self) { text, _ in guard let text, let url = URL(string: text.trimmingCharacters(in: .whitespacesAndNewlines)), url.scheme == self.scheme else { return } // only your own links DispatchQueue.main.async { DeepLinks.open(url) } // the handler a tapped link uses } }}Hand the address to the code that already handles exampleapp:// links; it reads brv_click from the query there too.
Report app opens with POST /events/open
With Universal Links or App Links on your domain, a tap opens the installed app before the short link loads, so Brevily never sees the visit. The app reports it instead: it sends the link it was opened with, and Brevily decides the visit as for any tap (targeting, A/B tests, schedules, expiry, a disabled link, a password), counts the click and answers what to show.
curl -X POST "https://console.brevily.com/api/EXAMPLE/events/open" \ -H "x-brevily-key: brv_pk_…" \ -H "content-type: application/json" \ -d '{"url": "https://go.example.com/autumn"}'When the link opens this app, the answer is the screen and the click:
{ "open": "app", "path": "/offers/autumn", "brvClick": "01JC8Z6Q3W5X7Y9A1B2C3D4E5F.01JC8Z5M2N4P6R8T0V1W3X5Y7Z"}path is the link's path in the app, with the visit's own query added. brvClick is null when no click was counted. When the visit belongs in a browser, the answer is where to go: the web page when a fallback applies, or the short link itself when the link has a password, is disabled, or has expired with no fallback, so the browser shows the right page:
{ "open": "browser", "url": "https://example.com/autumn" }Show that address in a browser inside the app (SFSafariViewController, a Custom Tab). Handed back to the phone, it would open the app again.
Send the call from the device itself, never through your server: the click takes its country and address from the request.
The open on iOS (Swift)
import SafariServicesimport UIKit/// What POST /events/open answers.struct OpenAnswer: Decodable { let open: String // "app" or "browser" let path: String? // with "app": the screen, such as "/offers/autumn" let brvClick: String? // with "app": the click, to report an install with let url: String? // with "browser": the page to show instead}final class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? private let endpoint = URL(string: "https://console.brevily.com/api/EXAMPLE/events/open")! private let appKey = "brv_pk_…" // Mobile apps › your app › Count taps that open the app // A link that launched the app. func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // … your window set-up … connectionOptions.userActivities.forEach(reportOpen) } // A link tapped while the app was running. func scene(_ scene: UIScene, continue userActivity: NSUserActivity) { reportOpen(userActivity) } private func reportOpen(_ activity: NSUserActivity) { guard activity.activityType == NSUserActivityTypeBrowsingWeb, let link = activity.webpageURL else { return } var request = URLRequest(url: endpoint) request.httpMethod = "POST" request.setValue(appKey, forHTTPHeaderField: "x-brevily-key") request.setValue("application/json", forHTTPHeaderField: "content-type") request.httpBody = try? JSONEncoder().encode(["url": link.absoluteString]) URLSession.shared.dataTask(with: request) { data, response, _ in let answer = (response as? HTTPURLResponse)?.statusCode == 200 ? data.flatMap { try? JSONDecoder().decode(OpenAnswer.self, from: $0) } : nil DispatchQueue.main.async { if answer?.open == "app", let path = answer?.path { if let click = answer?.brvClick { Clicks.keep(click) } // your own storage Router.show(path: path) // your own screen routing } else { // "browser", a refusal or no answer: show the page inside the app. let page = answer?.url.flatMap { URL(string: $0) } ?? link self.window?.rootViewController?.present( SFSafariViewController(url: page), animated: true) } } }.resume() }}The open on Android (Kotlin)
import android.content.Intentimport android.net.Uriimport android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport androidx.browser.customtabs.CustomTabsIntentimport org.json.JSONObjectimport java.net.HttpURLConnectionimport java.net.URLimport kotlin.concurrent.threadclass LinkActivity : AppCompatActivity() { private val endpoint = "https://console.brevily.com/api/EXAMPLE/events/open" private val appKey = "brv_pk_…" // Mobile apps › your app › Count taps that open the app override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) intent?.data?.let { reportOpen(it.toString()) } // a link that launched the app } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) intent.data?.let { reportOpen(it.toString()) } // a link tapped while it ran } private fun reportOpen(link: String) { thread { val answer: JSONObject? = try { val conn = URL(endpoint).openConnection() as HttpURLConnection conn.requestMethod = "POST" conn.setRequestProperty("x-brevily-key", appKey) conn.setRequestProperty("content-type", "application/json") conn.doOutput = true conn.outputStream.use { it.write(JSONObject().put("url", link).toString().toByteArray()) } if (conn.responseCode == 200) JSONObject(conn.inputStream.bufferedReader().readText()) else null } catch (e: Exception) { null } runOnUiThread { if (answer != null && answer.optString("open") == "app") { if (!answer.isNull("brvClick")) Clicks.keep(answer.getString("brvClick")) Router.show(answer.getString("path")) // your own screen routing } else { // "browser", a refusal or no answer: show the page in a Custom Tab. val page = answer?.optString("url")?.takeIf { it.isNotEmpty() } ?: link CustomTabsIntent.Builder().build().launchUrl(this, Uri.parse(page)) } } } }}An open counts as a click, never as an event, so it doesn't use your plan's events.
Report the install
With the click in hand, from the open's brvClick or a brv_click carried through the store, report the install with the same key. The value is two IDs joined by a dot: the click's, then the link's. They go in the address, and id is your own value, so a repeat counts once:
curl -X POST \ "https://console.brevily.com/api/EXAMPLE/links/$LINK/clicks/$CLICK/events/install" \ -H "x-brevily-key: brv_pk_…" \ -H "content-type: application/json" \ -d '{"id": "install_8f2c"}'A 201 means it's recorded against the link. Event reporting in full is in event tracking by link, and the calls are in the reference: open and an event against a click.
Troubleshooting deferred deep links and app opens
- No
brv_pathon Android: the app wasn't installed from the Play Store page the link opened, or the link's fallback is The link's destination. Check the app record has its Play Store address. - No
brv_click: the link doesn't have Track events on, or your plan doesn't include events. The screen still travels. - Nothing on the iPhone clipboard: the visitor went to the App Store another way, didn't paste, or copied something else before the first launch. The app should open its start screen.
- 400
VALIDATION_FAILED:urlisn't an address, or the key in the header and akeyin the body differ. Send the link exactly as the app received it. - 401
UNAUTHENTICATED: the key isn't a live key of this organisation: a typo, a retired key, or another organisation's code in the address. - 403
ACCESS_DENIED: your plan doesn't include Universal Links and App Links (for opens) or events (for installs), or the key is a website key, not the app's. A publishable key never reports a sale or an amount. - 404
NOT_FOUND: the link isn't one of your organisation's, or it doesn't open this app on a domain picked for it under Open from your domains. That covers installs too: from the app, report them only for links on those domains, and report others from your server. For an open, show the link in the in-app browser. - 429
RATE_LIMITED: too many calls with this key. Wait a minute; don't retry in a loop.
Common questions
Is there a Brevily SDK for deferred deep links?
Not yet, and none is needed: the code in this guide uses Google's Play Install Referrer library and the systems' own APIs, nothing else.
Does Brevily match iPhone installs by IP address?
No. Brevily never matches a visit to an install by device or network address, since a match would be a guess. On iPhone, only visitors who tap Get the app and let the app paste carry the screen into the install.
What happens with a deferred deep link if the visitor already has the app?
Nothing is deferred: Android opens the app at the screen straight away, and iPhone after one tap on Open in the app, or directly with Universal Links on your own domain.
Do deferred deep links work on iPad?
Most iPads browse as a Mac, so they get the link's web destination and never see the Get the app page.
Next steps
- Add a mobile app: set up Universal Links and App Links, and make the app's key.
- Event tracking by link: report sign-ups and sales against the click.
- Deep links to app screens: the link side, for your marketing team.
- API errors: every code, and when to retry.
On this page