Captur Android SDK: Implementation Guide
This guide covers a full integration: install the library, set up your API key, prepare a session, show the camera, handle events, and tear down.
Requirements
| Requirement | Minimum |
|---|---|
minSdk | API 24 (Android 7.0) |
compileSdk | API 36 |
| Kotlin | 2.1 |
| UI toolkit | Jetpack Compose 1.10, with Compose enabled in your app module |
| Distribution | Compiled AAR, added as a Gradle dependency |
The SDK is a compiled AAR. Nothing is built from source on your side. Camera access is provided through CameraX and on-device inference runs through LiteRT.
1. Install the library
The SDK is published to Captur's GitLab Maven repository. Captur gives you a
GitLab username and token together with your API key. Add the repository to your
settings.gradle.kts:
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
maven {
url = uri("https://gitlab.captur.ai/api/v4/projects/1/packages/maven")
content { includeGroup("ai.captur") }
credentials {
username = providers.gradleProperty("capturGitlabUsername").get()
password = providers.gradleProperty("capturGitlabToken").get()
}
authentication { create<BasicAuthentication>("basic") }
}
}
}
Keep the credentials out of source control: put them in ~/.gradle/gradle.properties
as capturGitlabUsername=<your username> and capturGitlabToken=<your token>, or set
the ORG_GRADLE_PROJECT_capturGitlabUsername and ORG_GRADLE_PROJECT_capturGitlabToken
environment variables on CI.
Then add the dependency to your app module's build.gradle.kts. Gradle
resolves the SDK's own dependencies automatically:
dependencies {
implementation("ai.captur:captursdk:<version>")
}
Pin an exact version. The camera preview is a composable, so your app module must have Compose enabled, the Kotlin Compose compiler plugin applied, and a Compose BOM on its classpath:
plugins {
id("org.jetbrains.kotlin.plugin.compose") // same version as your Kotlin plugin
}
android {
buildFeatures {
compose = true
}
}
dependencies {
implementation(platform("androidx.compose:compose-bom:<version>"))
implementation("androidx.compose.ui:ui")
}
2. Add camera permission
The SDK's manifest declares the CAMERA, INTERNET and ACCESS_NETWORK_STATE
permissions and marks the camera feature as not required. They merge into your
app's manifest automatically; you do not need to add them yourself.
The SDK does not request the runtime camera permission for you. Request it in
your app before preparing the camera, for example with the Activity Result API.
If permission hasn't been granted, prepareCamera fails with
CAMERA_PERMISSION_MISSING (see step 6).
val requestCamera = rememberLauncherForActivityResult(
ActivityResultContracts.RequestPermission()
) { granted ->
if (granted) prepareCamera() else showPermissionRequired()
}
val alreadyGranted = ContextCompat.checkSelfPermission(
context, Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED
if (alreadyGranted) prepareCamera() else requestCamera.launch(Manifest.permission.CAMERA)
3. Get an API key
Captur will issue an API key for your app. Pass it to Captur.initialise
(see step 4).
4. Initialise the SDK
Call Captur.initialise once, early in your app's lifetime. It fetches your
workspace configuration over the network and delivers a Captur instance
through the listener. Keep that instance for the lifetime of the app. Your
Application subclass is a natural place to own it:
import ai.captur.captursdk.api.Captur
import ai.captur.captursdk.api.models.CapturSDKInitResult
import android.app.Application
class ExampleApplication : Application() {
@Volatile
var captur: Captur? = null
private set
override fun onCreate() {
super.onCreate()
Captur.initialise(context = this, apiKey = "<YOUR_CAPTUR_API_KEY>") { result ->
when (result) {
is CapturSDKInitResult.Success -> captur = result.captur
is CapturSDKInitResult.Failure -> { /* result.type, result.message */ }
}
}
}
}
Register the class in your manifest with android:name=".ExampleApplication".
You can instead retain Captur in an app-owned dependency container or
service layer. Pass that same instance down to wherever captures happen.
Calling initialise again with the same API key delivers the same Captur
instance, so it is safe to call again after a failure.
CapturSDKInitResult.Failure.type is one of:
| Type | Meaning |
|---|---|
INVALID_API_KEY | Captur rejected the API key. Check the key you passed. |
NOT_CONNECTED | The device has no network connection. Call initialise again once it is online. |
FAILED | Fetching the configuration failed for another reason; message has the detail. |
DIFFERENT_KEY_PROVIDED | The SDK is already initialised with a different API key. One key is supported per app process. |
Threading. SDK callbacks in this guide (the initialise, session and camera listeners, and capture events) may be delivered on a background thread. Switch to the main thread before touching UI state, for example with
viewModelScope.launch { ... }orwithContext(Dispatchers.Main).
5. Prepare a capture session
prepareSession resolves the policy and model for your policyType at the
given location, downloads the model if needed (an already-downloaded model is
reused), and delivers a CapturSession through the listener. It makes a
network call, so call it as early as you know a capture is coming, so the
camera opens without a cold start.
captur.prepareSession(
policyType = "<YOUR_POLICY_TYPE>",
location = CapturLocation(latitude = 51.5074, longitude = -0.1278),
reference = "order-${UUID.randomUUID()}",
listener = object : CapturSessionPrepareListener {
override fun onSuccess(session: CapturSession) { /* keep the session */ }
override fun onFailed(error: CapturSessionError) { /* error.type, error.message */ }
},
)
| Parameter | Required | Description |
|---|---|---|
policyType | Yes | The Captur policy for this capture. |
location | Yes | Coordinate used to resolve the policy and model. A coarse, early location is fine here. |
reference | Yes | Your own identifier for this capture, used for billing and correlation. |
listener | Yes | Receives the prepared CapturSession or a CapturSessionError. |
CapturSessionError.type is one of:
| Type | Meaning |
|---|---|
AUTHENTICATION_FAILED | Captur rejected the API key. |
NO_CONNECTION | The device has no network connection. Prepare the session again once it is online. |
SERVER_ERROR | Captur returned an error while resolving or downloading the model and policy; message has the detail. |
DISABLED | Captur is disabled for your workspace. Contact Captur. |
PENDING_IMAGE_LIMIT_REACHED | Too many captured images from offline use are still waiting to be sent. Sessions can't be prepared until some of them have been sent, which happens automatically once the device is online. |
UNKNOWN | Any other failure; message has the detail. |
6. Prepare and show the camera
Ensure camera permission is granted, then call session.prepareCamera with
the device's current location.
session.prepareCamera(
location = CapturLocation(latitude = 51.5074, longitude = -0.1278),
eventsListener = object : CapturEventsListener {
override fun onCapturEvent(event: CapturEvents) { handleCapturEvent(event) }
},
listener = object : CapturCameraControllerCreateListener {
override fun onSuccess(controller: CapturCameraController) { /* show the camera */ }
override fun onFailed(error: CapturCameraControllerError) { /* error.type, error.message */ }
},
)
prepareCamera loads the session's inference and policy models into LiteRT
and returns a CapturCameraController through the listener. A returned
controller means both models are loaded and ready.
CapturCameraControllerError.type is one of:
| Type | Meaning |
|---|---|
CAMERA_PERMISSION_MISSING | The app has not been granted the camera permission (see step 2). |
CREATION_IN_PROGRESS | A previous prepareCamera on this session is still running. Wait for its result. |
CAMERA_ALREADY_ACTIVE | This session already returned a camera controller. Use that controller, or close it and prepare a new session. |
CAMERA_ALREADY_CLOSED | This session's camera has been closed. Prepare a new session. |
STALE_SESSION | The session's model or policy files are no longer available. Prepare a new session. |
INVALID_MODEL | A different model version is now deployed for this policyType. Prepare a new session. |
SESSION_EXPIRED | The device is offline and the model and policy prepared with the session are no longer valid. Prepare a new session once the device is online. |
POLICY_RESOLUTION_FAILED | Captur returned an error while confirming the model and policy for this location; message has the detail. |
UNKNOWN | The model failed to load, or another failure; message has the detail. |
prepareCamera confirms the session's model and policy with Captur for the
given location. If the device is offline, it continues with the model and
policy prepared with the session for a limited time; after that it fails with
SESSION_EXPIRED.
The camera hardware itself isn't touched yet: CameraX starts when you render
the controller in a CapturCameraScreen.
Camera configuration
Pass a CapturCameraConfiguration to choose the initial camera position and
lens, and to control consecutive-pass automatic capture:
val cameraConfiguration = CapturCameraConfiguration(
position = CapturCameraPosition.BACK,
lens = CapturCameraLens.WIDE,
disableAuto = false,
)
session.prepareCamera(
location = CapturLocation(latitude = 51.5074, longitude = -0.1278),
eventsListener = eventsListener,
cameraConfiguration = cameraConfiguration,
listener = listener,
)
| Setting | Options | Default | Description |
|---|---|---|---|
position | BACK, FRONT | BACK | Camera position to use when the preview starts. |
lens | WIDE, ULTRA_WIDE | WIDE | Lens to use when the preview starts. Availability depends on the selected position and device. |
disableAuto | true, false | false | When true, consecutive PASS predictions do not automatically finish the capture. Manual capture and the SDK-managed timeout still apply. |
Torch and zoom are not initial configuration settings. Change them after the preview starts using the controller methods described in step 7.
Compose
Embed the preview and put your own controls on top. The preview fills its parent.
import ai.captur.captursdk.api.camera.CapturCameraScreen
@Composable
fun CaptureScreen(controller: CapturCameraController) {
Box(modifier = Modifier.fillMaxSize()) {
CapturCameraScreen(capturCameraController = controller)
// Your capture controls overlay here.
}
}
CapturCameraScreen binds the camera to the composable's lifecycle owner. If
your app moves to the background during a capture, the attempt can end by
timeout; call retake() when the user returns to start a fresh attempt.
7. Capture, inference & camera controls
Once CapturCameraScreen is on screen and frames are flowing, real-time
predictions arrive through the CapturEventsListener you passed to
prepareCamera. Every analysed frame produces a Prediction event. The
attempt ends with exactly one FinalDecision or Failed event, triggered by
whichever of these happens first:
- Auto-capture. The SDK finishes the capture automatically once the frames
consistently pass. Disable it with
disableAuto = truein the camera configuration. - Manual capture.
controller.captureImage()marks the next analysed frame as the final one. - Timeout. A short SDK-managed timeout, measured from when analysis
begins. If at least one frame was
analysed, the last decision becomes the
FinalDecision; otherwise the attempt ends withFailed(TIMEOUT).
override fun onCapturEvent(event: CapturEvents) {
when (event) {
is CapturEvents.Prediction -> {
// Live, per-frame result. `decision` carries `value`, `title` and `reasonCode`.
println(event.decision.value)
}
is CapturEvents.FinalDecision -> {
// The captured outcome: `imageData`, plus `decision`, `modelVersionUID` and `trigger`.
println("${event.imageData.size} bytes, ${event.decision.value} via ${event.trigger}")
}
is CapturEvents.Failed -> {
// TIMEOUT, INFERENCE_FAILED or UNKNOWN.
println("${event.error.type}: ${event.error.message}")
}
}
}
// Trigger a manual final decision.
controller.captureImage()
// Adjust the camera
controller.togglePosition() // front / back
controller.toggleLens() // wide / ultra-wide
controller.toggleTorch() // flash on / off
controller.toggleZoom() // 1x / 2x
Call the camera controls on the main thread. Each returns a
CapturCameraControlError?: null on success, or an error when the device
cannot honour it. Its type is LENS_UNAVAILABLE, TORCH_UNAVAILABLE,
ZOOM_UNAVAILABLE, NO_CAMERAS_AVAILABLE or UNKNOWN. Calling a control
before the preview is running, or after a capture until retake(), returns
CAMERA_PREVIEW_NOT_RUNNING.
captureImage() has no return value. It takes effect once
CapturCameraScreen is displayed; a call made before that, or after a final
decision until retake(), is ignored.
After a final decision the SDK stops analysing frames until you call
retake() (see step 8).
Event payloads
Prediction and FinalDecision both carry a CapturPredictionDecision;
FinalDecision adds the captured image, the model version, when and how the
capture happened, and whether it was taken offline. Failed carries a
CapturCameraError:
data class CapturPredictionDecision(
val value: String, // the policy decision value
val title: String?, // display title, when the policy provides one
val reasonCode: String?, // why the policy decided this, when provided
)
class FinalDecision(
val decision: CapturPredictionDecision,
val imageData: ByteArray, // the captured image, JPEG-encoded
val modelVersionUID: String, // the on-device model version that produced this decision
val capturedAt: Long, // when the captured frame was analysed, epoch milliseconds
val trigger: CapturFinalDecisionTrigger, // AUTO, MANUAL or TIMEOUT
val offlineMode: Boolean, // true when the camera was prepared offline
)
data class CapturCameraError(
val type: Type, // TIMEOUT, INFERENCE_FAILED, UNKNOWN
val message: String?,
)
8. Retake or dismiss the camera
Three calls matter once a capture attempt ends:
controller.retake()starts a fresh attempt after a final decision, clearing it and restarting the auto-capture count and timeout. IfCapturCameraScreenis still on screen, analysis resumes immediately; otherwise it resumes when you show the screen again.- Removing
CapturCameraScreenfrom composition pauses the camera and inference but keeps the controller alive, so you can show a review UI and re-compose the same controller. Re-composing before a final decision restarts the capture count and timeout; re-composing after one does not start a new attempt, that takesretake(). Showing the screen again resets the camera controls to the initial camera configuration. controller.close()is the terminal, idempotent shutdown: it stops analysis, releases the loaded models, stops callbacks, and marks the session closed. It does not dismiss your UI; removeCapturCameraScreenafterwards to release the camera. A closed session cannot be reused;prepareCameraon it fails withCAMERA_ALREADY_CLOSED, so prepare a new session for the next capture.
Each session gives out one camera controller: a second prepareCamera on the
same session fails with CAMERA_ALREADY_ACTIVE. If a controller has been
returned but you'll never present the screen, close() it before discarding
it.
End-to-end example
ExampleApplication from step 4 owns the SDK instance. A ViewModel owns the
session and controller and marshals the SDK's background-thread callbacks onto
the main thread; the Activity renders the camera and handles permission.
import ai.captur.captursdk.api.camera.CapturCameraControllerCreateListener
import ai.captur.captursdk.api.camera.CapturEvents
import ai.captur.captursdk.api.camera.CapturEventsListener
import ai.captur.captursdk.api.Captur
import ai.captur.captursdk.api.CapturSession
import ai.captur.captursdk.api.CapturSessionPrepareListener
import ai.captur.captursdk.api.camera.CapturCameraControllerError
import ai.captur.captursdk.api.models.CapturLocation
import ai.captur.captursdk.api.models.CapturSessionError
import ai.captur.captursdk.api.camera.CapturCameraController
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import java.util.UUID
class CaptureViewModel(private val captur: Captur) : ViewModel() {
var session by mutableStateOf<CapturSession?>(null)
private set
var controller by mutableStateOf<CapturCameraController?>(null)
private set
var finalEvent by mutableStateOf<CapturEvents?>(null)
private set
var errorMessage by mutableStateOf<String?>(null)
private set
private fun currentLocation() = CapturLocation(latitude = 51.5074, longitude = -0.1278)
// Call this earlier in the flow so the model is prepared before capture.
fun prepareSession() {
captur.prepareSession(
policyType = "<YOUR_POLICY_TYPE>",
location = currentLocation(),
reference = "example-${UUID.randomUUID()}",
listener = object : CapturSessionPrepareListener {
override fun onSuccess(session: CapturSession) {
viewModelScope.launch { this@CaptureViewModel.session = session }
}
override fun onFailed(error: CapturSessionError) {
viewModelScope.launch { errorMessage = error.message ?: error.type.name }
}
},
)
}
// Call this once camera permission has been granted.
fun prepareCamera() {
val session = session ?: return
session.prepareCamera(
location = currentLocation(),
eventsListener = object : CapturEventsListener {
override fun onCapturEvent(event: CapturEvents) {
if (event is CapturEvents.FinalDecision || event is CapturEvents.Failed) {
// Captured: `FinalDecision.imageData` is the image, `decision` the outcome,
// `trigger` says whether auto-capture, `captureImage()` or the timeout ended it.
// Display them here. See §7 for all event cases.
viewModelScope.launch { finalEvent = event }
}
}
},
listener = object : CapturCameraControllerCreateListener {
override fun onSuccess(controller: CapturCameraController) {
viewModelScope.launch { this@CaptureViewModel.controller = controller }
}
override fun onFailed(error: CapturCameraControllerError) {
viewModelScope.launch { errorMessage = error.message ?: error.type.name }
}
},
)
}
fun retake() {
finalEvent = null
controller?.retake()
}
fun closeCapture() {
controller?.close()
controller = null
session = null
finalEvent = null
}
}
import ai.captur.captursdk.api.camera.CapturCameraScreen
import ai.captur.captursdk.api.camera.CapturEvents
import android.graphics.BitmapFactory
@Composable
fun CaptureFlow(viewModel: CaptureViewModel) {
val context = LocalContext.current
val requestCamera = rememberLauncherForActivityResult(
ActivityResultContracts.RequestPermission()
) { granted -> if (granted) viewModel.prepareCamera() }
val controller = viewModel.controller
if (controller == null) {
Column {
Button(onClick = viewModel::prepareSession) { Text("Prepare Session") }
Button(
enabled = viewModel.session != null,
onClick = {
val granted = ContextCompat.checkSelfPermission(
context, Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED
if (granted) viewModel.prepareCamera() else requestCamera.launch(Manifest.permission.CAMERA)
},
) { Text("Prepare Camera") }
viewModel.errorMessage?.let { Text(it) }
}
} else {
when (val event = viewModel.finalEvent) {
is CapturEvents.FinalDecision -> Column {
val bitmap = BitmapFactory.decodeByteArray(event.imageData, 0, event.imageData.size)
Image(bitmap = bitmap.asImageBitmap(), contentDescription = null)
Text(event.decision.title ?: event.decision.value)
Button(onClick = viewModel::retake) { Text("Retake") }
Button(onClick = viewModel::closeCapture) { Text("Done") }
}
is CapturEvents.Failed -> Column {
Text("${event.error.type}: ${event.error.message}")
Button(onClick = viewModel::retake) { Text("Retake") }
Button(onClick = viewModel::closeCapture) { Text("Close") }
}
else -> Box(modifier = Modifier.fillMaxSize()) {
CapturCameraScreen(capturCameraController = controller)
Button(
onClick = controller::captureImage,
modifier = Modifier.align(Alignment.BottomCenter).padding(48.dp),
) { Text("Capture") }
Button(
onClick = viewModel::closeCapture,
modifier = Modifier.align(Alignment.TopEnd).padding(16.dp),
) { Text("Close") }
}
}
}
}
SDK version
For support requests and bug reports, read the bundled SDK version at runtime:
ai.captur.captursdk.BuildConfig.SDK_VERSION // the bundled version string