> ## Documentation Index
> Fetch the complete documentation index at: https://usefoil.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Android SDK

> Add the Foil Android SDK to your Kotlin app from Maven Central, configure it in Application.onCreate(), and hand sealed sessions to your backend to verify.

The Android SDK mirrors the browser SDK: configure it on startup, call `getSession()` when the user performs a sensitive action, and POST the sealed token to your backend for verification.

> [!WARNING]
>
> New Android integrations are temporarily paused while the SDK moves to
> Foil's unified session transport. The Android SDK remains supported, but the
> currently published release will receive `transport.upgrade_required` until
> that update ships.

```kotlin theme={"dark"}
FoilClient.configure(
    context,
    FoilConfiguration(publishableKey = "pk_live_..."),
)

// At action time (signup, login, checkout)
val handoff = FoilClient.getSession()
```

> [!NOTE]
>
> The Android SDK is distributed through Maven Central as protected binary AAR
> artifacts. The public metadata repository is
> `https://github.com/abxy-labs/foil-android`.

## Requirements

* Android 6.0 Marshmallow (API 23) and up
* Kotlin 1.9+
* Android Gradle Plugin 8.2+
* Java 17 toolchain
* A Foil publishable key created with the **Android** client, starting with `pk_live_` or `pk_test_`

### Create a publishable key for Android

In the Foil dashboard, open **API Keys**, choose **New publishable key**, and set **Client** to **Android**. Foil admits native sessions only when the publishable key's client matches the SDK's platform. A key created with the **Web** or **iOS** client is rejected, and the SDK reports `config.invalid_publishable_key`. In the other direction, the browser SDK doesn't accept a key created with the **Android** client.

## Install

Foil publishes two Android artifacts:

| Artifact | Required | Description |
| - | - | - |
| `com.usefoil:foil-android` | Yes | Core Foil Android SDK. |
| `com.usefoil:foil-android-gms` | No | Optional helpers for reading the Advertising ID and the Google Services Framework ID and for requesting Play Integrity tokens. The core SDK doesn't use them. |

```kotlin theme={"dark"}
// settings.gradle.kts
dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
    }
}

// app/build.gradle.kts
dependencies {
    implementation("com.usefoil:foil-android:1.2.2")
}
```

Your app must declare `android.permission.INTERNET`. The SDK's own manifest declares `android.permission.ACCESS_NETWORK_STATE`, which Android grants at install time. See [Manifest entries and permissions](#manifest-entries-and-permissions) for what the SDK and its dependencies add to your merged manifest.

### Optional Google helpers

The `foil-android-gms` artifact contains three standalone helpers in the `com.usefoil.foil.gms` package. The core SDK doesn't depend on this artifact or call these helpers, so adding it doesn't change what Foil collects or what `getSession()` returns. Add it only if your app calls the helpers directly.

```kotlin theme={"dark"}
dependencies {
    implementation("com.usefoil:foil-android-gms:1.2.2")
}
```

| Helper | Description |
| - | - |
| `AdvertisingIdProvider.fetch(context)` | Suspending. Returns the Advertising ID and the user's limit-ad-tracking setting, or `null` when Google Play Services is unavailable or the user has opted out. |
| `GsfIdProvider.fetch(context)` | Returns the Google Services Framework ID as lowercase hex, or `null`. Requires the `READ_GSERVICES` permission. |
| `PlayIntegrityProvider.fetchToken(context, nonce)` | Suspending. Requests a Play Integrity token bound to `nonce`, which can be up to 500 characters, or returns `null`. |

The artifact depends on the Play Integrity and Advertising ID client libraries. The Advertising ID library adds the `com.google.android.gms.permission.AD_ID` permission to your merged manifest, so review your Play Console advertising ID declaration before you add the artifact.

## Configure on startup

Call `configure()` from `Application.onCreate()` so signal collection is running by the time your first screen mounts.

```kotlin theme={"dark"}
class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        FoilClient.configure(
            this,
            FoilConfiguration(publishableKey = "pk_live_your_publishable_key"),
        )
    }
}
```

### `FoilConfiguration`

```kotlin theme={"dark"}
data class FoilConfiguration(
    val publishableKey: String,
    val enableBehavioralSignals: Boolean = true,
    val enableHiddenWebView: Boolean = true,
    val enableCloudIdentifier: Boolean = false,
    val enableAutoAttachTouches: Boolean = false,
    val apiEndpoint: String = "https://api.usefoil.com",
    val lockAgainstExternalDebuggers: Boolean = false,
)
```

| Field | Default | Description |
| - | - | - |
| `publishableKey` | - | Required. Must start with `pk_live_` or `pk_test_` and be created with the **Android** client. Secret keys (`sk_*`) are rejected at configure-time. |
| `enableBehavioralSignals` | `true` | Zero-config native behavioral capture: app lifecycle, navigation, input, scroll, and motion. Touch-stroke observers are opt-in. Disable if your app has strict motion-sensor policies. |
| `enableHiddenWebView` | `true` | Enables the `attach(webView)` handoff so an in-app WebView shares this session. |
| `enableCloudIdentifier` | `false` | Opt-in Android Auto Backup continuity hint. Safe to leave `false`; see Backup configuration below if your app uses custom backup rules. |
| `enableAutoAttachTouches` | `false` | Automatically attaches touch observers to the decor view of each resumed activity. Leave off if you call `observeTouches` manually. Using both doesn't register a view twice. |
| `apiEndpoint` | production API | Advanced override for local development or private deployments. |
| `lockAgainstExternalDebuggers` | `false` | Destructive. When `true`, the SDK starts a child process at startup that attaches to your app with `ptrace`, so no other debugger or profiler can attach. Android Studio's profiler, native debuggers, and crash-dump tools that use `ptrace` can't attach while it is on, and some devices refuse the lock. Enable it only in production builds that you don't need to debug natively. |

Runtime integrity and anti-tamper collection is always enabled. It is part of
the baseline SDK behavior, not an integration option.

### Backup configuration

The SDK keeps this state on the device:

| Data | Where | Restored from a backup |
| - | - | - |
| Session state: the session ID, resume token, and session key, plus at most one sealed batch waiting to be sent | `SharedPreferences` files named `foil_session_*` and `foil_batch_*`, encrypted with a key held in the Android Keystore | No |
| The install ID and the first `ANDROID_ID` this install saw | `foil/install.json` in `Context.getNoBackupFilesDir()` | No |
| The cloud identifier, only when `enableCloudIdentifier = true` | A `SharedPreferences` file named `foil_cloud_identifier` | Yes |

Session state lets a cold start resume the current session instead of
starting a new one. Android Auto Backup can copy the encrypted session files,
but it doesn't copy the Keystore key, so a restored copy can't be decrypted.
When the SDK finds a file it can't decrypt, it deletes the file and starts a
new session. If the device's Keystore can't be used at all, the SDK keeps
session state in memory for the life of the process and never writes it to
disk unencrypted. You don't need to change your backup rules for these files.

The install ID identifies one installation of your app, so it lives in the
no-backup directory and is never restored onto another install. After an
upgrade, the SDK keeps the install ID that earlier versions stored encrypted.
It doesn't reuse an install ID from an unencrypted copy, because a backup can
restore that copy from a different install.

When `enableCloudIdentifier = true`, the SDK stores a per-install UUID in a
`SharedPreferences` file named `foil_cloud_identifier`. Android Auto
Backup can restore that file for the same Google account after reinstall,
factory reset, or device migration, giving Foil a noisy continuity hint.

Most apps do not need extra setup. If your app declares custom backup rules
with `android:fullBackupContent` or `android:dataExtractionRules`, include the
SDK preferences file:

```xml theme={"dark"}
<!-- res/xml/backup_rules.xml -->
<full-backup-content>
    <!-- your existing rules -->
    <include domain="sharedpref" path="foil_cloud_identifier.xml"/>
</full-backup-content>
```

The value is a random non-PII UUID. It is intentionally not encrypted because
Keystore-protected data cannot be restored from backup.

## Get a session at action time

Call `getSession()` from a coroutine right before the sensitive action - not on app launch.

```kotlin theme={"dark"}
lifecycleScope.launch {
    val handoff = FoilClient.getSession()

    val response = httpClient.post("/api/signup") {
        contentType(ContentType.Application.Json)
        setBody(SignupRequest(
            email = email,
            foil = FoilHandoff(handoff.sessionId, handoff.sealedToken),
        ))
    }
}
```

`SessionHandoff` is a simple data class:

```kotlin theme={"dark"}
data class SessionHandoff(val sessionId: String, val sealedToken: String)
```

* `sessionId` is stable across `getSession()` calls for the life of the client.
* `getSession()` posts the native snapshot, performs a bounded best-effort behavioral flush, and returns the handoff your backend should verify.
* The SDK never surfaces verdicts, scores, or visitor IDs to the device - verify on your server.

Your backend verifies a native handoff the same way it verifies a browser handoff. `getSession()` returns the same `sessionId` and `sealedToken` pair as the browser SDK, so you verify the `sealedToken` with your Foil server SDK and your secret key. See [Server verification](https://usefoil.com/docs/server-verification.md) for the verification methods and examples in each server language.

## Behavioral capture

When `enableBehavioralSignals` is true, the SDK starts zero-config Android behavioral capture automatically. It records the native equivalents of the browser's behavioral events: app lifecycle, hashed screen navigation, viewport and scroll, form focus and input, selection and clipboard, and motion.

No raw form text, raw hints, or raw view identifiers are sent. Field identity is hashed, and geometry is rounded to the active window's coordinate space so the dashboard can show timing and replay context without collecting user-entered values.

Touch-stroke dynamics are still opt-in per screen for higher-fidelity gesture data. Call `observeTouches` when the view is available - typically from `onResume`.

```kotlin theme={"dark"}
override fun onResume() {
    super.onResume()
    FoilClient.observeTouches(rootView, contextId = "checkout")
}
```

`observeTouches` wraps any existing `View.OnTouchListener` on the view; it does not consume events, so your gesture and scroll handlers keep working unchanged.

## WebView correlation

If your app hosts Foil-protected web content in a `WebView`, attach it so the web SDK reuses the native session instead of creating its own.

```kotlin theme={"dark"}
val webView = WebView(context)
FoilClient.attach(webView)
webView.loadUrl("https://your-app.example.com/signup")
```

The native bridge exposes the session handoff as `window.__FOIL_NATIVE__`, which the browser SDK picks up when loaded from within the WebView.

## Native identity and attestation

Native visitor continuity is resolved server-side from the SDK's encrypted observations. `install_id` tracks the app install, `device_id` tracks the device continuity layer, and native `visitor_id` represents the same device within your organization. None of those identifiers are exposed to the app.

Android Key Attestation is optional and positive-only by default. When hardware-backed attestation is available, Foil can use SDK-managed Android Keystore keys to strengthen native identity. When it is unsupported, unavailable, unconfigured, or fails verification, Foil falls back to the other native continuity signals unless your organization explicitly enables strict attestation.

> [!NOTE]
>
> To verify Android Key Attestation in production, add your Android app identity on the **Native Attestation** card of the dashboard's **Settings** page. Baseline native continuity still works without this setup, but hardware-backed attestation doesn't upgrade identity confidence until the app identity is configured.

### Add your app identity

Only organization owners and admins can change attestation settings. On the **Native Attestation** card, under **Add app identity**:

1. Set **Platform** to **Android**.
2. Enter your **Android package name**, such as `com.example.app`.
3. Enter the **Signing cert SHA-256**, which is the SHA-256 fingerprint of the certificate that signs the release build your users install. Foil stores it as lowercase hex and also accepts colon-separated fingerprints. If you use Play App Signing, use the app signing key certificate, not the upload certificate.
4. Select **Add identity**.

The **Attestation policy** setting on the same card controls how Foil treats attestation:

| Policy | Behavior |
| - | - |
| **Positive only** (default) | Verified Key Attestation can strengthen identity. Missing or unsupported attestation doesn't break continuity. |
| **Strict** | Foil requires verified attestation from an app identity on the **App identity allowlist**. Add every app identity you ship before you switch to this policy, then select **Save policy**. |

## API reference

| Method | Description |
| - | - |
| `FoilClient.configure(context, configuration)` | Validates the publishable key and starts the runtime. Safe to call once at app start. Calling again reconfigures the client. |
| `suspend FoilClient.getSession(): SessionHandoff` | Posts the snapshot, performs a bounded best-effort behavioral flush, and returns a sealed handoff. |
| `suspend FoilClient.waitForFingerprint()` | Resolves when the visitor fingerprint is ready. Optional - `getSession()` works without it. |
| `suspend FoilClient.pauseCollection()` | Pauses active collection without ending the session. Later `getSession()` calls stay valid but don't include events recorded while paused. Call it after a protected flow completes. |
| `suspend FoilClient.stop()` | Alias for `pauseCollection()`. |
| `FoilClient.resumeCollection()` | Resumes collection after `pauseCollection()` or `stop()` without creating a new session. |
| `FoilClient.observeTouches(view, contextId)` | Attaches a non-consuming touch observer to the view. Call once per screen. |
| `FoilClient.attach(webView)` | Shares the current session with a hosted `WebView`. |
| `suspend FoilClient.resetLocalState()` | Stops the runtime and clears the persisted session and queued batches for the current configuration. Long-lived install anchors are preserved. Call `configure()` again before you use any other method. |
| `FoilClient.destroy()` | Stops timers and releases resources. Rarely needed outside tests. |

## Manifest entries and permissions

Your app declares `android.permission.INTERNET` so the SDK can reach the Foil API. The SDK and its dependencies add the following entries to your merged manifest:

* **Network state permission.** The SDK's own manifest declares `android.permission.ACCESS_NETWORK_STATE`, which Android grants at install time without a prompt. The SDK uses it to read whether the active network is a VPN or metered, which transports it uses, and whether background data is restricted.
* **`<queries>` block.** Six `<provider>` entries that let the SDK check, on Android 11 and later, whether known app-cloning and virtualization frameworks are installed. You don't need `QUERY_ALL_PACKAGES` for these checks.
* **Dependency permissions.** AndroidX Biometric adds `android.permission.USE_BIOMETRIC` and `android.permission.USE_FINGERPRINT`. The Play Install Referrer library adds `com.google.android.finsky.permission.BIND_GET_INSTALL_REFERRER_SERVICE`.

### Optional permissions

Optional host-app permissions can unlock additional direct OS facts, but they are not required for verdicts or native continuity. The SDK never prompts for a permission. It reads these facts only when your app already holds the permission, so don't add a runtime permission only for Foil.

| Permission | Unlocks | Play Store friction |
| - | - | - |
| `com.google.android.providers.gsf.permission.READ_GSERVICES` | Google Services Framework ID | None. |
| `android.permission.READ_PHONE_STATE` | Carrier name and country for each active SIM | Runtime permission. Users see a prompt. |
| `android.permission.BLUETOOTH_CONNECT` (`android.permission.BLUETOOTH` on Android 11 and lower) | The Bluetooth adapter name that the user set | `BLUETOOTH_CONNECT` is a runtime permission on Android 12 and higher. Users see a prompt. |

Foil does not collect advertising IDs, serial numbers, IMEI/MEID, raw MAC addresses, SSID/BSSID, precise location, raw proxy hostnames, or broad installed-app inventories. Android package and tooling checks are bounded to fixed allowlists and are used as soft corroboration, not standalone identity anchors.

## Error handling

Every SDK-produced error is a subclass of the sealed `FoilError` type.

```kotlin theme={"dark"}
sealed class FoilError(
    val code: String,
    message: String,
    cause: Throwable? = null,
    val retryable: Boolean = false,
) : Exception(message, cause)
```

| Code | Retryable | When it happens |
| - | - | - |
| `config.invalid_publishable_key` | no | `publishableKey` is missing, uses the `sk_*` secret prefix, or doesn't match `pk_live_*` / `pk_test_*`. The SDK also returns this code when the API rejects the key (HTTP 401 or 403), for example because the key was created with the **Web** or **iOS** client instead of **Android**. |
| `client.not_configured` | no | A client method was called before `configure()`. |
| `session.create_failed` | varies | Session handshake with the Foil API failed. The `retryable` flag reflects the underlying cause. |
| `session.handshake_expired` | no | The server expired the session. Call `configure()` again to mint a new one. |
| `session.invalid_or_expired` | no | The active session is invalid or expired. |
| `transport.batch_post_failed` | varies | A signal batch upload failed. |
| `transport.rate_limited` | yes | HTTP 429 from the API. Back off and retry. |
| `transport.upgrade_required` | no | HTTP 410/426. The SDK version is too old - upgrade the app. |
| `transport.network` | yes | DNS, TLS, or connectivity failure. |
| `crypto.failure` | no | A crypto primitive failed. Usually a platform issue worth reporting. |
| `internal` | no | Unexpected state. File a support ticket with the message and cause. |

The `code` values are stable. Category prefixes (`config.*`, `transport.*`) are safe to branch on with a wildcard - new codes within a category keep the same retry semantics.

### Fallback policy

If Foil fails, log the error and continue without a handoff, then decide on your server how to treat a request that has no Foil signal. For low-risk actions you can fail open. For sensitive actions such as signup, payment, or account recovery, fail closed or step up verification.

```kotlin theme={"dark"}
suspend fun foilHandoff(): SessionHandoff? =
    try {
        FoilClient.getSession()
    } catch (err: FoilError) {
        if (err.retryable) {
            runCatching { FoilClient.getSession() }.getOrNull()
        } else {
            reportError(err)
            null
        }
    }
```

See [Signup & account creation](https://usefoil.com/docs/use-cases/signup.md) for an example of failing closed when verification fails, and [Going to production](https://usefoil.com/docs/going-to-production.md) for the rollout sequence.

## Best practices

* **Configure in `Application.onCreate()`** so signals are collecting before any screen opens.
* **Call `getSession()` late** - right before the sensitive action, inside a coroutine.
* **Set a fallback policy per action** - when the SDK can't produce a handoff, fail open on low-risk actions and fail closed on sensitive ones.
* **Reuse the singleton** - `FoilClient` is a process-wide singleton. Do not hold per-screen copies.

## What's next

> [card] [Server verification](https://usefoil.com/docs/server-verification.md)
>
> Verify the sealed token on your backend

> [card] [Browser SDK](https://usefoil.com/docs/browser-sdk.md)
>
> Equivalent guide for the web surface

> [card] [iOS SDK](https://usefoil.com/docs/ios-sdk.md)
>
> Native iOS integration

> [card] [Going to production](https://usefoil.com/docs/going-to-production.md)
>
> Rollout checklist and monitoring


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.