# Android reference

> Every public type in the FacePing Android SDK: setup, enrolment, verification, the camera view and results.

Source: https://docs.faceping.ai/sdk/android/

Package: [`ai.faceping:faceping-android`](https://central.sonatype.com/artifact/ai.faceping/faceping-android) (Maven Central, preview). Starter app: [faceping/android-starter](https://github.com/faceping/android-starter). Android 7 (API 24) or later, on 64-bit phones (`arm64-v8a`) and `x86_64` emulators. Your app builds with `compileSdk` 36 and Android Gradle Plugin 8.9.1 or later (FacePing's AndroidX dependencies need them).

```kotlin title="app/build.gradle.kts"
android {
    defaultConfig {
        ndk { abiFilters += listOf("arm64-v8a", "x86_64") }   // the ABIs FacePing's native core is built for
    }
}

dependencies {
    implementation("ai.faceping:faceping-android:1.0.0-preview.4")   // from mavenCentral(), or libs.faceping from your version catalog
}
```

Everything is in the package `ai.faceping`. The calls are `suspend` functions: call them from a coroutine, for example `lifecycleScope.launch { … }`. They do their work off the main thread.

## Setup

```kotlin
// Once, for example in Application.onCreate. Returns at once and loads the models in the background.
val faceping = FacePing.init(context, sandboxKey = "fp_test_…")     // sandbox: faces enrolled on the device
// val faceping = FacePing.init(context, deviceToken = "fpd_…")     // production or your practice list: faces synced from that list
```

`FacePing.current` returns the same instance anywhere in the app, and throws `IllegalStateException` until `init` has been called. Calling `init` again with the same options returns the same instance; with different options it throws (call `close()` on the old one first).

### FacePingOptions

For every option, pass `FacePing.init(context, FacePingOptions(...))`.

| Property | Type | Default | Notes |
|---|---|---|---|
| `sandboxKey` | `String?` | `null` | A `fp_test_` key from [**Developers → Sandbox keys**](https://app.faceping.ai/developers). |
| `deviceToken` | `String?` | `null` | Production, or your sandbox's practice list. A `fpd_` device token for one check-in list (from `POST /v1/lists/{listId}/devices`, or the list's Devices tab). Set this or `sandboxKey`, not both. |
| `region` | `FacePingRegion` | `EU` | Your account's region, which sets the API address. Today the only value is EU (`https://api-eu.faceping.ai/`). |
| `apiBaseUrl` | `String?` | `null` | Overrides the region's address. UK and US regions are available on request: we give you the address to put here. |
| `passiveLiveness` | `Boolean` | `true` | Passive liveness on every check. Turn it off only if your app runs its own liveness check first. |
| `autoSyncInterval` | `Duration?` | 5 minutes | With a device token (production, or a practice-list device). `null` turns automatic sync off; call `sync()` yourself. |
| `verifyPolicy` | `VerifyPolicy` | `VerifyPolicy.DEFAULT` | How strict verification is. Change only if you know why. |

Setting neither `sandboxKey` nor `deviceToken`, or both, or a sandbox key that doesn't start with `fp_test_`, throws `FacePingSetupException` from `init`.

## FacePing

```kotlin
class FacePing : Closeable {
    companion object {
        fun init(context: Context, sandboxKey: String? = null, deviceToken: String? = null,
                 region: FacePingRegion = FacePingRegion.EU): FacePing
        fun init(context: Context, options: FacePingOptions): FacePing
        val current: FacePing
        val SDK_VERSION: String
    }

    val options: FacePingOptions
    val isSandbox: Boolean               // true with a sandbox key; false with a device token, even for a practice list
    val enrolledIds: Set<String>
    val synced: SharedFlow<SyncResult>                      // every sync, automatic or not

    suspend fun enroll(id: String, photo: FaceImage): EnrollResult   // also Bitmap or ByteArray
    suspend fun verifyLive(id: String, camera: FaceCameraView, nonce: String? = null): VerifyResult
    suspend fun verify(id: String, photo: FaceImage, nonce: String? = null): VerifyResult  // also Bitmap or ByteArray

    suspend fun forget(id: String): Boolean
    suspend fun forgetAll()
    suspend fun unpair()

    suspend fun sync(): SyncResult
    override fun close()
}
```

| Method | Notes |
|---|---|
| `enroll` | Sandbox only. Production enrolment happens with consent on your server or through the FacePing widget. Replaces any face already stored under `id`. |
| `verifyLive` | Runs a live attempt on the camera's frames: match, head turn, match again. Shows prompts in the `FaceCameraView` and sets its guide. Times out after 10 seconds with `NO_FACE` or the last failure; cancel the coroutine to stop early. |
| `verify` | One photo, passive liveness only. |
| `nonce` | Check-in devices: a nonce from your server, signed into the result's `signedResult` so your server can tell the result answers that check. 1 to 128 characters, no control characters (anything else throws `IllegalArgumentException`). See [Signed check results](https://docs.faceping.ai/signed-results/). |
| `forget` | With a sandbox key: deletes the face stored under `id` from the device straight away, and returns `false` if there was none. With a device token (production, or a practice-list device): throws `IllegalStateException`; remove a person through your server instead, and every device drops them at its next sync. |
| `forgetAll` | Deletes every face on the device straight away. In production the next sync brings back the people still enrolled. |
| `unpair` | Unpairs the device: deletes every face on it and forgets the check-in list it synced, so it can start again with any device token. Moving to another list doesn't need this: start with that list's token and the first successful sync swaps the lists, wiping the old faces first ([Move a device to another list](https://docs.faceping.ai/devices/#move-a-device-to-another-list-or-retire-it)). Use it when a device is retired or handed back, and clear your saved token too. In the sandbox it deletes the faces enrolled on the device. Then `close()` and `init` with the new token. |
| `enrolledIds` | Who can be verified on this device, as of the last enrol, forget or sync. |
| `sync` | Production: downloads the latest faces for the device's list; a revoked device wipes its faces. Sandbox: activates the key, or renews its licence when due. Either way it refreshes `enrolledIds`, so it's a good first call when the app starts. |
| `close` | Stops automatic sync and frees the engine. `FacePing.current` is cleared; call `init` again to start over. |

## FaceImage

What you can pass as a photo.

| From | Example |
|---|---|
| `Bitmap` | `faceping.enroll("me", bitmap)` |
| `ByteArray` (JPEG or PNG) | `faceping.enroll("me", bytes)` |
| A `content://` or `file://` `Uri` (for example from the photo picker) | `faceping.enroll("me", FaceImage.fromUri(context, uri))` |
| `FaceCameraView` capture | `faceping.enroll("me", camera.capture())` |

`FaceImage.fromBytes`, `fromBitmap` and `fromUri` build one yourself. Photos are turned upright from their EXIF orientation and scaled down to 1280 pixels on the device before anything else happens.

## FaceCameraView

A front-camera view with a face guide and the liveness prompts ("Turn your head left", "Look back at the camera"). The SDK runs the camera (CameraX), so you don't need another camera library.

```xml
<ai.faceping.FaceCameraView
    android:id="@+id/camera"
    android:layout_width="match_parent"
    android:layout_height="420dp" />
```

| Member | Notes |
|---|---|
| `suspend fun capture(): FaceImage` | Takes a still from the live view: upright, as the camera sees it (the preview is mirrored, the picture isn't). Throws `IllegalStateException` if the camera doesn't deliver a picture within 5 seconds. |
| `showGuide: Boolean` | The face outline. Default `true`. |
| `prompt: String?` | Set by `verifyLive` while a live check runs. |
| `guideState: FaceGuideState` | How the guide looks: `READY` (dashed), `WORKING` (a scan line), `MATCH` (green) or `NO_MATCH` (red). `verifyLive` sets it; set it yourself for other steps, for example `WORKING` while enrolling. Main thread only. |
| `cameraFailedListener` | Called on the main thread when the camera can't start: permission refused or no front camera. The message says which. |
| `fun startCamera()` | Starts (or restarts) the camera. Called for you when the view is attached; call it if your app gets camera permission another way. |

The camera starts when the view is attached to a window inside an AndroidX activity or fragment, and stops with its lifecycle. In Jetpack Compose, wrap it with `AndroidView(factory = { FaceCameraView(it) })`.

The prompts are the string resources `faceping_prompt_look_at_camera`, `faceping_prompt_turn_left`, `faceping_prompt_turn_right` and `faceping_prompt_look_back`: define them in your app to translate or reword them.

## Permissions

The library's manifest declares `android.permission.CAMERA` (for the camera view) and `android.permission.INTERNET` (to activate a sandbox key and to sync in production; face checks never use the network). Android merges both into your app, so you don't add them yourself.

`FaceCameraView` asks for the camera the first time it appears, if your app hasn't asked already. To ask earlier, use `CameraPermission.isGranted(context)` and `CameraPermission.request(activity)`, then call `startCamera()` on the view once it's granted.

## Backups

The face store's encryption keys are kept in this device's Android Keystore, which can't be restored on another device. FacePing keeps its data in `faceping/` in the app's files and in the shared preferences `faceping.keys.xml` (its face models are in the cache, which is never backed up). Set `android:allowBackup="false"`, and from Android 12 also exclude both from `cloud-backup` and `device-transfer` in your data extraction rules: [Allow the camera](https://docs.faceping.ai/start/android/#allow-the-camera) in the guide has the file.

## Results

```kotlin
data class EnrollResult(val outcome: EnrollOutcome, val id: String) {
    val isEnrolled: Boolean   // outcome == ENROLLED
}

enum class EnrollOutcome { ENROLLED, NO_FACE, MULTIPLE_FACES, FACE_TOO_SMALL, NOT_LIVE, LIMIT_REACHED }

data class VerifyResult(
    val outcome: VerifyOutcome,
    val similarity: Double,
    val livenessScore: Double?,
    val elapsed: Duration,
    val isSandbox: Boolean,
    val signedResult: String?,  // check-in devices: the signed result for your server; null in the sandbox
) {
    val isMatch: Boolean      // outcome == MATCH
}

enum class VerifyOutcome {
    MATCH, NO_MATCH, NOT_ENROLLED, NO_FACE, LIVENESS_FAILED, CHALLENGE_FAILED, EXPIRED, LEASE_EXPIRED
}

data class SyncResult(
    val status: SyncStatus,   // OK, GONE, REVOKED or UNAVAILABLE
    val enrolled: Int,
    val leaseUntilMillis: Long?,      // production: verifies offline until then
    val deleteAfterMillis: Long?,
    val signing: SigningState,        // REGISTERED, MISMATCH or UNKNOWN
)
```

What a sync status means, with a device token:

| Status | What happened | What the app should do |
|---|---|---|
| `OK` | The device has the list's latest faces. | Nothing: it verifies offline until the lease runs out. |
| `GONE` | The list is past its deletion date, so the device wiped its copy. | Stop offering face check-in for this list. |
| `REVOKED` | The device token was revoked, isn't valid, or its list was deleted, so the device wiped its copy. | Stop offering face check-in, and pair the device again with a new token if it should carry on. |
| `UNAVAILABLE` | No connection, or the server couldn't be reached. The device keeps its copy. | Carry on: it verifies offline until the lease runs out, then needs a sync. |

`signedResult` is set on a check-in device (a device token): every outcome is signed by the device, so your server can prove the check happened. It's `null` in the sandbox, and until the device's first sync. `signing` says whether FacePing holds the device's signing key: `REGISTERED`; `MISMATCH` (the app was reinstalled or its data cleared, so checks still work but signed results won't verify: add the device again); or `UNKNOWN` (before the first sync, and in the sandbox). See [Signed check results](https://docs.faceping.ai/signed-results/).

`LIMIT_REACHED` means the sandbox already holds 25 faces on this device: forget one first. `LEASE_EXPIRED` (production) means the device hasn't synced for longer than its lease, 24 hours by default; it needs a connection before it verifies again.

## Exceptions

| Exception | When |
|---|---|
| `FacePingSetupException` | The key or token is missing or malformed (neither set, both set, or a sandbox key that doesn't start with `fp_test_`), or the sandbox key couldn't be activated (the first run needs a connection, or the server refused the key). The message says which. A revoked or mistyped device token throws this at a device's first sync; once a device has synced, a revoked token or a deleted list doesn't throw: sync returns `REVOKED` and the device wipes its copy. |
| `FacePingModelException` | The face models couldn't load on this device. Send people to your normal entry. |
| `IllegalArgumentException` | A bad argument, for example an empty id or bytes that aren't a JPEG or PNG. |
| `IllegalStateException` | Not allowed in this mode or state: enrolling or forgetting one person in production, a closed FacePing, or a camera that didn't deliver a picture. |
| `IOException` | The device's storage failed. |

Everything else is a result, not an exception: a face check never throws because someone looked away.
