# Android Deferred Deep Links

Deferred deep links let you route users to specific content even when they don't have your app installed. The user clicks a link, installs from the Play Store, and on first launch the SDK matches them back to the original link.

## How It Works

1. User taps a WarpLink URL in Chrome
2. WarpLink captures browser signals and sets the Play Install Referrer with `utm_source=warplink&utm_content={link_id}`
3. User is redirected to the Play Store
4. User installs and opens the app
5. SDK detects first launch. A completion marker in the app's no-backup storage (`noBackupFilesDir`) is written only after the check completes, and Auto Backup never restores it, so a reinstall attributes fresh. If that directory cannot be written, the marker falls back to a SharedPreferences entry bound to the install, so a restore cannot carry it onto a reinstall.
6. SDK reads the Play Install Referrer. If it contains `utm_source=warplink`, a deterministic match is made (confidence 1.0). A referral invitation token (`wl_rt`) in the referrer is matched first and is also exact
7. If the referrer is unavailable, the SDK falls back to probabilistic matching (device language + timezone, with the IP derived server-side). Clicks that share a match key are kept as a list, newest first, up to 10, so a second click never overwrites the first
8. Server returns a `WarpLinkDeepLink` with `isDeferred = true`

Tether is for iPhone only. On Android, the Play Install Referrer already carries the link through the install, so no clipboard read is needed. See the [Tether overview](https://warplink.app/docs/tether).

## Automatic Check

The deferred check fires automatically from `configure()`. The result arrives in your `onLink` callback, where `isDeferred` is `true`. `navigateTo(...)`, `showWelcome(...)` and `showOnboarding()` in the samples on this page stand for your own code:

```kotlin
WarpLink.configure(
    context = this,
    apiKey = "wl_live_yoursdkkeyhere000000000000000000",
    options = WarpLinkOptions(onLink = { result ->
        result.onSuccess { deepLink ->
            if (deepLink.isDeferred) {
                val confidence = deepLink.matchConfidence ?: 0.0
                if (confidence > 0.5) {
                    navigateTo(deepLink.deepLinkUrl ?: deepLink.destination)
                } else {
                    showWelcome(suggestedContent = deepLink.destination)
                }
            } else {
                navigateTo(deepLink.destination) // a tap, not a deferred install
            }
        }
    })
)
```

If that check cannot reach the server, for example on a launch with no network, the failure also arrives in `onLink`. The first-launch gate stays open, so a later launch checks again by itself. From SDK 1.4.0, it waits before it tries again, and the first launch never waits. The waits are listed under [Caching Behavior](#caching-behavior). Treat a `WarpLinkError.NetworkError` there as a report, not as something to act on.

## Manual Check (Advanced)

To run the check yourself, set `automaticDeferredDeepLinks = false` in `WarpLinkOptions` and call `checkDeferredDeepLink`:

```kotlin
WarpLink.checkDeferredDeepLink { result ->
    result.onSuccess { deepLink ->
        if (deepLink == null) {
            showOnboarding()
            return@onSuccess
        }

        val confidence = deepLink.matchConfidence ?: 0.0

        if (confidence > 0.5) {
            val target = deepLink.deepLinkUrl ?: deepLink.destination
            navigateTo(target)
        } else {
            showWelcome(suggestedContent = deepLink.destination)
        }
    }.onFailure { error ->
        Log.e("MyApp", "Deferred deep link error: ${error.message}")
        showOnboarding()
    }
}
```

## Confidence-Based Routing

```kotlin
WarpLink.checkDeferredDeepLink { result ->
    result.onSuccess { deepLink ->
        if (deepLink == null || !deepLink.isDeferred) return@onSuccess
        val confidence = deepLink.matchConfidence ?: 0.0

        if (confidence > 0.5) {
            // High confidence: navigate straight to the link's destination
            navigateTo(deepLink.deepLinkUrl ?: deepLink.destination)
        } else if (confidence > 0.3) {
            // Medium confidence: show suggestion
            showWelcome(suggestedContent = deepLink.destination)
        }
        // Below 0.3: ignore, show default onboarding
    }
}
```

## Confidence Scores

Probabilistic scores depend on the match key variant. `enriched_tz` hashes the IANA timezone name and is what an SDK that collects a zone name sends. `enriched` hashes the minute offset instead and stays as the fallback for older SDKs. `basic` drops the timezone entirely.

| Scenario | Confidence | Match Type |
|----------|------------|------------|
| Play Install Referrer match | 1.0 | `DETERMINISTIC` |
| `enriched_tz` match key, < 1 hour | 0.85 | `PROBABILISTIC` |
| `enriched_tz` match key, < 3 hours | 0.65 | `PROBABILISTIC` |
| `enriched_tz` match key, < 6 hours | 0.50 | `PROBABILISTIC` |
| `enriched_tz` match key, < 24 hours | 0.30 | `PROBABILISTIC` |

The offset variant scores 0.80 / 0.60 / 0.45 / 0.25 across the same bands, and `basic` scores 0.70 / 0.50 / 0.35 / 0.20. Two further signals adjust the score: more than one distinct link in the match key bucket applies x0.6, and a shared click IP applies x0.6 for carrier-grade NAT or a private address, x0.9 for a household IPv4 address, and x1.0 for IPv6. Past 24 hours there is no match at all.

**Recommendation:** Route to specific content when `matchConfidence > 0.5`. Show generic onboarding below 0.5. `matchGuaranteed` is `true` for a deterministic match (the Play Install Referrer; `evidenceClass` is `LEGACY_LINK` for a plain link and `EXACT` for a referral invitation token) and sharpens the routing choice further. Route a probabilistic match to content or a sign-in screen, and keep sign-in on your own authentication.

## Match Window

The match window is set **per link on the server**, not in the SDK. Configure it in the dashboard when you create or edit a link. The default is 6 hours and the maximum is 24 hours.

The window is deliberately short so the match key bucket stays tight and matches stay precise. Links created before the current limits may still carry a longer stored value, but the server caps every window at 24 hours when it reads them.

This governs probabilistic matching only. The Play Install Referrer branch is deterministic and is not affected by the window.

## Caching Behavior

- The attribution check runs on **first launch**
- Once it completes, a completion marker in the app's no-backup storage (`noBackupFilesDir`) is recorded so it does not run again for this install
- Subsequent launches return without another network request
- An attempt that produced no usable answer (offline, an error, or a match the SDK cannot route to a destination) is **not** recorded as complete, so a later launch tries again. SDK 1.3.0 and earlier try again on the next launch
- From SDK 1.4.0, a failed check waits before it tries again, and old installs are limited:
  - The wait is 15 minutes after the first failure, 1 hour after the second, 6 hours after the third, and 24 hours after every failure after that. The SDK stops 3 days after the first failure
  - While a wait runs, `checkDeferredDeepLink` sends no request and returns `success(null)`, the same answer as no match. `WarpLink.isAttributionComplete()` stays `false`, so a skipped check does not look finished. [`WarpLink.deferredCheckStatus`](#if-your-test-did-not-match) tells you which case you have. The check starts only while your app is in the foreground. A call made while the app is in the background waits until the app comes to the foreground, and then runs
  - An install older than 30 days is not checked. An install older than 48 hours is checked without language and timezone signals, so a match can come only from an exact method such as the Play Install Referrer
  - A `wl_test_` key has no waits and no age limits, so you can test a first launch as often as you like
- A reinstall is a new install, so it gets a new check. See [App Reinstall](#app-reinstall)

## Edge Cases

### Play Install Referrer Unavailable

The referrer is the primary matching method but is unavailable when:

- The app is sideloaded (`adb install` or direct APK)
- No Google Play Services (e.g., Huawei HMS devices)
- Referrer data has expired

The SDK automatically falls back to probabilistic matching. No code changes needed.

### Offline First Launch

If the device has no connectivity on first launch, `checkDeferredDeepLink` fails with `WarpLinkError.NetworkError`. The attempt is **not** consumed. The SDK tries the check again on a later launch. From SDK 1.4.0, it waits before it tries again, as listed under [Caching Behavior](#caching-behavior).

### App Reinstall

A reinstall is a new install and is attributed again. The SDK keeps two markers with two different jobs:

- **Completion marker**: a file in the app's no-backup storage (`noBackupFilesDir`). It says the check already ran for *this* install. Auto Backup never captures that directory, so a reinstall starts from a clean marker
- **Device-seen marker**: a `SharedPreferences` entry. It says the device was attributed at some point, and Auto Backup does restore it. It gates nothing. Its only job is to set `is_reinstall: true` on the attribution request, so the install is recorded as a reinstall rather than a first install

Both installs count. The dashboard shows installs and reinstalls together as one installs number. No manifest or `backup_rules.xml` changes are required on your side: keep Auto Backup on and the two markers behave as described.

### Routing-only mode

If the app is in [routing-only mode](https://warplink.app/docs/trust/attribution-accuracy#routing-only-mode), the server skips the probabilistic match. An install that carries a Play Install Referrer still matches. No SDK change is needed.

### Multiple Links Before Install

Clicks that share a match key are kept as a list, newest first, up to 10. The **most recent** click your app can claim is the one matched, and the others stay available for the other devices that share the address. When more than one click is claimable, the confidence score is multiplied by 0.6 to report that ambiguity.

### Referrer Age

The Play Install Referrer stays valid for months, so a check that runs long after the install, a `1.0.x` upgrade, or the first release you ship with the SDK, still names the original link. The server still records that attribution. The SDK routes a match whose Play install began within **7 days** of the check, which covers fresh installs and any check that runs soon after the Play install.

### Referral Invitation

A referral link needs no extra step on Android. Google Play hands the install referrer to the SDK at first launch, the invitation rides inside it, and the automatic check matches it. If the person pastes an invitation instead, `redeemInvitation(text, callback)` matches it the same way. A match delayed by a network failure is kept on the device and delivered to `onLink` on a later launch. See [Referral Invitations](https://warplink.app/docs/sdks/android/attribution#referral-invitations). The [referrals guide](https://warplink.app/docs/guides/referrals) covers the whole path.

## Testing

1. Uninstall the app from the test device
2. Open the test link in Chrome. It redirects to the Play Store (or fallback URL)
3. Install via Android Studio or `adb install`
4. Launch the app. `checkDeferredDeepLink` should return the matched deep link

### If your test did not match

Use a `wl_test_` key and a link from your Test app while you build: a Test key has no waits and no age limits. Tap the link again before every install: one tap matches one install.

If a test still shows no link, read the status of the check:

```kotlin
import android.util.Log

Log.d("WarpLinkTest", WarpLink.deferredCheckStatus.toString())
```

Read it after the check ends, for example from a debug button, or watch for the `Deferred check: <state>` log line. Right after `configure`, it reads the check as still running.

From Java, call `WarpLink.INSTANCE.getDeferredCheckStatus()`. The value is a `DeferredCheckStatus`. It sends no request, and it comes from state stored on the device, so a relaunch keeps it.

| State | What it means |
|-------|---------------|
| `NotChecked` | No check has finished for this install. A failed check whose wait has passed also reads `NotChecked`. |
| `Checking` | A check is running, or waiting for an activity to come on screen. |
| `Matched` | The check found a link. |
| `NoMatch` | The check finished and the server found no link. |
| `Waiting(retryAtMillis)` | An earlier check failed. The SDK sends nothing before `retryAtMillis`, in epoch milliseconds. |
| `SkippedOldInstall` | The install is older than 30 days. No request is sent. |
| `Stopped` | The SDK gave up 3 days after the first failure. No request is sent. |

A `wl_test_` key never reports `Waiting`, `SkippedOldInstall` or `Stopped`. These causes give no link:

- **The link and the key are from different environments.** A `wl_test_` key matches only taps on links of your Test app, at `<handle>-test.aplnk.to`. A `wl_live_` key matches only Production links. Create the test link in Test, and tap that link.
- **A wait is running.** The first launch never waits. A check counts as failed from the moment its request starts, so stopping the app in Android Studio while the request is out starts a 15-minute wait. Use a `wl_test_` key, or wait until `retryAtMillis`.
- **The install is too old.** With a `wl_live_` key, an install older than 48 hours is checked without language and timezone, so it usually reads `NoMatch`. An install older than 30 days is not checked and reads `SkippedOldInstall`. Android counts the age from the first install. A Run from Android Studio and `adb install -r` keep that time. Uninstall the app to start the age and the waits over.
- **The click was used.** A click matches one install. Tap the link again before the next install.
- **The click is too old.** The match window is 6 hours by default. See [Match Window](#match-window).

With `debugLogging = true`, each check prints `Deferred check request: attempt <n>, raw signals <yes|no>` to Logcat under the `WarpLink` tag, and each check ends with `Deferred check: <state>`. A waiting check prints `Deferred check: waiting, retry at <ISO 8601 time>`.
