# Get started with Android

> Build a small Kotlin app that enrols your face and verifies it offline, on your own Android phone.

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

What you'll build

### A face check that works in airplane mode

An app that enrols your face, verifies it live with a head-turn liveness check, and still matches with no network.

About 10 minutes
Android phone
Free sandbox key

## Get a sandbox key

Sign up at [app.faceping.ai/signup](https://app.faceping.ai/signup?platform=android) with your email, then open [**Developers → Sandbox keys → Create sandbox key**](https://app.faceping.ai/developers). It starts with `fp_test_`. It also works on the API for your practice list, so keep test apps within your team, and revoke the key under Developers if it leaks.

The sandbox is free and instant: up to 25 faces per device, each deleted 24 hours after it was enrolled. No card, no approval.

## Create the project

You need [Android Studio](https://developer.android.com/studio) and an Android phone (Android 7 or later, 64-bit) with USB debugging on and a cable.

In Android Studio: **File → New → New Project → Empty Views Activity**. Call it `FaceCheck`, pick **Kotlin** as the language and **API 24 ("Nougat"; Android 7.0)** or later as the minimum SDK.

FacePing builds with `compileSdk` 36 and Android Gradle Plugin 8.9.1 or later. New projects already have both; in an older app, raise them first, or the first sync stops at `checkDebugAarMetadata`.

First Android app on this machine?

The 10 minutes assume Android Studio already builds and runs apps on your phone. If it doesn't, set that up first (Android Studio downloads the SDK on first launch, which takes a while):

- [Install Android Studio](https://developer.android.com/studio/install).
- On the phone, [turn on developer options and USB debugging](https://developer.android.com/studio/debug/dev-options), then accept the prompt when you plug it in.

## Add FacePing

One dependency from Maven Central. It brings the face models, liveness checks and a camera view with it, and the screen below also uses `lifecycleScope`. New projects already list `mavenCentral()` in `settings.gradle.kts` and keep their libraries in a version catalog, so add two entries to the `[versions]` and `[libraries]` sections that are there (skip any your catalog already has):

```toml title="gradle/libs.versions.toml"
[versions]
faceping = "1.0.0-preview.4"
lifecycleRuntimeKtx = "2.11.0"

[libraries]
faceping = { module = "ai.faceping:faceping-android", version.ref = "faceping" }
androidx-lifecycle-runtime-ktx = { module = "androidx.lifecycle:lifecycle-runtime-ktx", version.ref = "lifecycleRuntimeKtx" }
```

Then add these to the `android` and `dependencies` blocks that are already in the app's build file, and **Sync Now**:

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

dependencies {
    implementation(libs.faceping)
    implementation(libs.androidx.lifecycle.runtime.ktx)
}
```

No version catalog? Use `implementation("ai.faceping:faceping-android:1.0.0-preview.4")` and `implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.11.0")` instead. FacePing for Android is in preview: see [Maven Central](https://central.sonatype.com/artifact/ai.faceping/faceping-android) for the latest version.

The first build downloads the FacePing library (about 27 MB, with Microsoft's ONNX Runtime and the face models inside). On a phone it adds about 34 MB to your app: the face engine and ONNX Runtime for one ABI (about 20 MB) plus the face models (about 14 MB). An APK holds both ABIs (about 65 MB for this app); publish an App Bundle, and Google Play sends each phone only its own ABI.

## Allow the camera

Nothing to add. The FacePing library declares `android.permission.CAMERA` (and `INTERNET`, to activate your key) in its own manifest, and Android merges them into your app. (The merged manifest also shows `ACCESS_NETWORK_STATE`, from the CameraX library FacePing uses, and an internal permission AndroidX adds to every app.) The camera view asks the person for the camera the first time it appears.

One change: keep FacePing's data out of backups. FacePing encrypts its face data with a key kept in the Android Keystore, which backups don't include, so a backed-up copy could never be read on another phone (and face data shouldn't leave the device anyway). In `app/src/main/AndroidManifest.xml`, change the template's line on `<application>`:

```xml title="app/src/main/AndroidManifest.xml"
android:allowBackup="false"
```

From Android 12, `allowBackup` no longer covers moving to a new phone (device-to-device transfer), so also replace the template's empty rules file, which the manifest already points to (`android:dataExtractionRules="@xml/data_extraction_rules"`):

```xml title="app/src/main/res/xml/data_extraction_rules.xml"
<?xml version="1.0" encoding="utf-8"?>
<data-extraction-rules>
    <cloud-backup>
        <exclude domain="file" path="faceping/" />
        <exclude domain="sharedpref" path="faceping.keys.xml" />
    </cloud-backup>
    <device-transfer>
        <exclude domain="file" path="faceping/" />
        <exclude domain="sharedpref" path="faceping.keys.xml" />
    </device-transfer>
</data-extraction-rules>
```

For Android 11 and earlier, put the same two lines in the template's `res/xml/backup_rules.xml` (the manifest's `android:fullBackupContent`), so the rules hold even if backup is turned back on later:

```xml title="app/src/main/res/xml/backup_rules.xml"
<?xml version="1.0" encoding="utf-8"?>
<full-backup-content>
    <exclude domain="file" path="faceping/" />
    <exclude domain="sharedpref" path="faceping.keys.xml" />
</full-backup-content>
```

## Turn FacePing on

Set FacePing up once, when the app starts, with your sandbox key. Add an `Application` class next to `MainActivity.kt`:

```kotlin title="FaceCheckApp.kt"
package com.example.facecheck

import ai.faceping.FacePing
import android.app.Application
import android.util.Log

class FaceCheckApp : Application() {
    override fun onCreate() {
        super.onCreate()
        // Starts loading the face models in the background, so the first check is quick.
        try {
            FacePing.init(this, sandboxKey = "fp_test_…")
        } catch (e: Exception) {
            // A missing or malformed key: the screen says so instead of the app stopping.
            Log.w("FaceCheck", "FacePing setup: ${e.message}")
        }
    }
}
```

Then tell Android to use it:

```xml title="AndroidManifest.xml"
<!-- app/src/main/AndroidManifest.xml: add android:name to the <application> tag that's there -->
<application
    android:name=".FaceCheckApp"
    ... >
```

If you picked a different package name in [Create the project](#create-the-project), use yours in place of `com.example.facecheck`.

## Add the screen

A camera view and two buttons (Verify filled, Enrol outlined): one enrols your face on the phone, the other verifies it. Add the button text to `res/values/strings.xml`, then replace the layout and the activity.

```xml title="res/values/strings.xml"
<!-- add inside <resources> -->
<string name="enroll">Enrol my face</string>
<string name="verify">Verify</string>
```

```xml title="activity_main.xml"
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="24dp">

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

        <Button
            android:id="@+id/enroll"
            style="?attr/materialButtonOutlinedStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:text="@string/enroll" />

        <Button
            android:id="@+id/verify"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:text="@string/verify" />

        <TextView
            android:id="@+id/status"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:gravity="center"
            android:textSize="18sp" />
    </LinearLayout>
</FrameLayout>
```

```kotlin title="MainActivity.kt"
package com.example.facecheck

import ai.faceping.FaceCameraView
import ai.faceping.FacePing
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import java.util.Locale

class MainActivity : AppCompatActivity() {
    // null when the setup in FaceCheckApp failed (for example a mistyped key).
    private val faceping: FacePing? = try { FacePing.current } catch (e: IllegalStateException) { null }
    private lateinit var camera: FaceCameraView
    private lateinit var status: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        camera = findViewById(R.id.camera)
        status = findViewById(R.id.status)
        findViewById<Button>(R.id.enroll).setOnClickListener { onEnroll() }
        findViewById<Button>(R.id.verify).setOnClickListener { onVerify() }
        if (faceping == null) status.text = "FacePing isn't set up: check the sandbox key in FaceCheckApp.kt."
    }

    private fun onEnroll() = act { faceping ->
        val photo = camera.capture()
        val result = faceping.enroll("me", photo)
        status.text = if (result.isEnrolled) "Enrolled. Now tap Verify." else "Try again: ${result.outcome}"
    }

    private fun onVerify() = act { faceping ->
        // A live check: matches your face, then asks you to turn your head (liveness).
        val result = faceping.verifyLive("me", camera)
        val time = String.format(Locale.UK, "%.2f s", result.elapsed.inWholeMilliseconds / 1000.0)
        status.text = if (result.isMatch) "Match · $time" else "Try again: ${result.outcome}"
    }

    private fun act(action: suspend (FacePing) -> Unit) = lifecycleScope.launch {
        val faceping = faceping ?: return@launch
        try {
            action(faceping)
        } catch (e: Exception) {
            // For example no connection on the very first run (the sandbox key is activated once), or no camera.
            status.text = e.message
        }
    }
}
```

## Run it on your phone

Plug your phone in and press **Run** in Android Studio, or from a terminal:

```bash
./gradlew installDebug
```

A debug build is fine, timings included: the FacePing core inside the SDK is already compiled for speed, whichever build you run.

Want a release build on the phone?

A new project's release build is unsigned, so it won't install. For testing, sign it with the debug key: add the `signingConfig` line to the `release` block that's already there, then run `./gradlew installRelease`. Set up your own upload key before you publish.

```kotlin title="app/build.gradle.kts"
android {
    buildTypes {
        release {
            signingConfig = signingConfigs.getByName("debug")   // for testing only
        }
    }
}
```

The first run needs a connection, to activate your sandbox key. Tap **Enrol my face**, then **Verify**: you should see `Match`. Use a phone: an Android emulator only has one if you map your computer's webcam to it in the emulator's camera settings, which is slower and less reliable for the liveness check.

**Now switch on airplane mode and tap Verify again.** Still a match: the check ran entirely on your phone.

## You've built a face check that works offline

Next, make it real: verify the people in your app (members, visitors or people with tickets), and apply to go live when you're ready.

- [Clone the finished app](https://github.com/faceping/android-starter): github.com/faceping/android-starter
- [How the SDK works](https://docs.faceping.ai/sdk/): Liveness, storage, sandbox limits
- [Android reference](https://docs.faceping.ai/sdk/android/): Every type and method
- [Go to production](https://docs.faceping.ai/going-live/): Apply and sync faces to devices

## Try a check-in device on your practice list

This is the ticketing flow, end to end, in the sandbox: a person enrols through your server or an enrolment link, and a check-in device verifies them offline.

1. Create your practice list, if your account doesn't have one: **New list** in the [dashboard](https://app.faceping.ai/lists) asks for everything it needs, or use [quickstart steps 1 and 2](https://docs.faceping.ai/quickstart/#1-create-a-check-in-list) (create the list, then set its widget details: enrolment links need them). Then enrol someone on it with your sandbox key: open an enrolment link ([quickstart step 3](https://docs.faceping.ai/quickstart/#3-create-an-enrolment-link-for-a-person); links last 30 minutes unless you pass `validForHours`), or enrol a selfie from your server with the copy-paste request in [Enrol someone from your server](https://docs.faceping.ai/quickstart/#enrol-someone-from-your-server). Note their `personId`, for example `ACME-000123` (if your team shares the practice list, pick your own).
2. Add a check-in device: the list's **Devices** tab in the [dashboard](https://app.faceping.ai/lists), or `POST /v1/lists/{listId}/devices`. Copy the `fpd_` device token: it's shown once.
3. Check the token works before you build: `curl https://api-eu.faceping.ai/v1/device -H "X-Device-Token: fpd_…"` returns the list's name and `peopleEnrolled`. It doesn't download any faces or count as a sync.
4. Make a device build that sits next to your sandbox app. In `app/build.gradle.kts`, add a `device` product flavour with its own application id and name. Then pick the `deviceDebug` build variant in Android Studio, or from a terminal run `./gradlew installDeviceDebug` (and `./gradlew installSandboxDebug` for the sandbox app: with flavours, plain `installDebug` no longer works):

```kotlin title="app/build.gradle.kts"
android {
    buildFeatures {
        buildConfig = true   // BuildConfig.FLAVOR, below
        resValues = true     // a name per build
    }
    flavorDimensions += "mode"
    productFlavors {
        create("sandbox") {
            dimension = "mode"
            resValue("string", "app_name", "FaceCheck")
        }
        create("device") {
            dimension = "mode"
            applicationIdSuffix = ".device"
            resValue("string", "app_name", "FaceCheck Device")
        }
    }
}
```

Each flavour now sets the app's name, so delete the `app_name` line from `res/values/strings.xml`.

5. Set FacePing up with the device token in the device build, and keep your sandbox key for the other. In `FaceCheckApp.kt`:

```kotlin title="FaceCheckApp.kt"
try {
    if (BuildConfig.FLAVOR == "device") {
        FacePing.init(this, deviceToken = "fpd_…")
    } else {
        FacePing.init(this, sandboxKey = "fp_test_…")
    }
} catch (e: Exception) {
    Log.w("FaceCheck", "FacePing setup: ${e.message}")
}
```

6. In `MainActivity.kt`, verify the person you enrolled, and show each sync as it happens. Add the field and the lines at the end of `onCreate`, and replace `onVerify`:

```kotlin title="MainActivity.kt"
// A field: the person to verify on the device build.
private val personId = if (BuildConfig.FLAVOR == "device") "ACME-000123" else "me"

// At the end of onCreate: sync now, then show every later sync (FacePing syncs again every few minutes).
if (BuildConfig.FLAVOR == "device") faceping?.let { fp ->
    lifecycleScope.launch { fp.synced.collect { status.text = "${it.enrolled} people synced (${it.status})" } }
    act { it.sync() }
}

// onVerify, checking personId in place of "me":
private fun onVerify() = act { faceping ->
    val result = faceping.verifyLive(personId, camera)
    val time = String.format(Locale.UK, "%.2f s", result.elapsed.inWholeMilliseconds / 1000.0)
    status.text = when {
        result.isMatch -> "Match · $time"
        result.outcome == VerifyOutcome.NOT_ENROLLED -> "$personId isn't on this device yet: enrol them, then wait for the next sync."
        else -> "Try again: ${result.outcome}"
    }
}
```

Add `import ai.faceping.VerifyOutcome` at the top.

7. Run the device build. It downloads the list's faces at start-up and every few minutes after; the status line shows how many people synced and the sync status, and updates with each sync. `REVOKED` means the token was revoked, mistyped or its list deleted, and the device wipes its faces. People enrol on the server, not in the app: `enroll` throws `IllegalStateException` on a device, so the enrol button shows the refusal message. Tap **Verify**, with no network if you like.

Each face stays on the device no longer than its 24 hours on the practice list. See [Devices and offline sync](https://docs.faceping.ai/devices/).

If you switch one install from the sandbox key to a device token instead, the two sets of faces stay apart: the app sees only the people synced from the device's list, and your sandbox faces come back (if they're under 24 hours old) when you switch back. Uninstalling removes both.

The [finished app](https://github.com/faceping/android-starter) runs as a check-in device too, with two Gradle properties: `./gradlew installRelease -Pfaceping.deviceToken=fpd_… -Pfaceping.personId=ACME-000123` (or edit the defaults in `app/build.gradle.kts`). Its release build is signed with the debug key, as above, so it installs straight away.
