Skip to main content

Android with Kotlin

Initialize with a workspace-issued device key validated by the backend, then submit stride-safe CameraX frames under the resolved tenant seat.

SDK 0.1.0-RC5 · Evaluation

Test the sample in three steps · Open SDK workspace

Version : 0.1.0-RC5

Support state : Android evaluation

Minimum Android : Android 8.0 (API 26)

Coordinate : com.visionscan.sdk:vision-scan-android-sdk:0.1.0-RC5

This is the canonical Android integration path. The runnable implementation is in samples/android-sample ; the complete camera UI is in reference-android-app . Both compile in the SDK release gate.

Start here: four steps

  1. In your SDK workspace , activate a trial or buy a seat directly, create its device key and download 0.1.0-RC5 . Copy the complete key once.
  2. Extract the ZIP, add its local Maven repository and use the versioned SDK dependency. See AAR installation .
  3. Call VisionScanSdk.initialize(applicationContext, VisionScanSdkConfiguration(origin, apiKey)) on a worker. Use its returned tenant/device context for your scan session. No manual phone enrollment or phone login UI is required.
  4. Bind CameraX to MatrixScan, consume result.accepted for captured barcodes, and enable Matrix telemetry before creating the session if you want workspace usage visibility.

For the quickest end-to-end test, run the ZIP's standalone sample-app using the three-step sample walkthrough . The app resolves the packaged Maven AAR, not SDK source projects. Its Scan with AR + telemetry button shows native boundaries and captured values; the workspace shows privacy-safe scan statistics.

RC4 packages lack the high-level initialize API. Use RC5 for the examples below. Detailed concepts and alternative bearer-token integration follow; they are not extra setup steps for the key-based path.

Core concepts

For new multi-barcode camera integrations use the native MatrixScan path below . VisionSession remains the compatibility path for existing receiving/image workflows. Do not combine both trackers for the same live scan. That compatibility path reads native results through VisionSession.getLatestObservations ; new MatrixScan integrations consume result.accepted .

Concept Responsibility
Tenant and device The SaaS control plane owns trial/subscription state, device seats, activation, features, limits, and revocation.
Signed license A backend-issued compact JWS binds tenant, device, plan, features, limits, revision, expiry, and offline grace. The SDK verifies it before scanning.
VisionScanSdk Initializes secure lease storage, refreshes or applies a signed license, evaluates entitlements, and creates sessions.
VisionSession Owns one leak-safe scanning lifecycle through AutoCloseable and LeakSafeCloseable , and accepts live, rescue, or batch frames.
Frame source The host owns CameraX, image selection, permissions, preview, focus, torch, and lifecycle.
Observation getLatestObservations() returns only native-decoded, deterministically parsed evidence. A submit status is never a barcode count.

Unlike an embedded static license key, the VisionScan flow can revoke a tenant/device lease, enforce feature entitlements, and apply bounded offline grace without teaching the client to construct claims.

Public contract map

The complete signatures are in the Android public API reference . The customer integration depends on three contract groups:

Contract Input Result Lifecycle and failure behavior
initializeLeaseStore Host no-backup directory and activated device ID Device-bound verified-lease persistence Call after enrollment and before license refresh. Storage or binding failures prevent offline admission.
initialize HTTPS origin and workspace-issued device SDK key Backend-resolved tenant/device IDs after license verification Call on an I/O worker from app initialization. The key is supplied in host code/build configuration, never an end-user input screen. Preflight validates the key in the backend database and records Android device metadata.
refreshPaidLicense / applySignedLicenseJws HTTPS control-plane origin or compact JWS, authenticated tenant ID, activated device ID EntitlementEvaluationResult or LicenseRefreshResult Run refresh on an I/O worker. Signature, claim, tenant, device, revision, expiry, revocation, and grace failures deny scanning.
createSessionVisionSessionConfig with session, tenant, site, and mode Auto-closeable VisionSession Requires a verified matching license and all mode features. Close on stop, logout, or workflow completion.
submitFrame Positive dimensions, supported format, stride-correct luminance bytes, optional profile Native status code Status is not a barcode count. Closed sessions and invalid buffers fail deterministically.
getLatestObservations None after an accepted frame Immutable List<BarcodeObservation> An empty list is a valid no-decode result. OCR-only identity remains review-required.

The machine-readable definitions used by the portal are in contracts/sdk-public-contracts.json . They record required inputs, results, lifecycle rules, security boundaries, and fail-closed behavior for every method shown below.

Choose an integration path

Native MatrixScan choices: createMatrixScanBatch (unique identities), createMatrixScanAR (persistent boxes), createMatrixScanCount (physical carriers), createMatrixScanFind (exact byte targets), and createMatrixScanPick (targets plus per-track pick state). All require barcode-intelligence and multi-barcode-dense entitlements. These names describe workflow contracts, not measured Scandit equivalence.

The following table describes the older VisionSession path:

Workflow Session mode Frame profile Required feature
Continuous live sweep LIVE_STREAMStillImageBatchScanProfile.liveSweep()barcode-intelligence
Tap or focused rescue HIGH_DENSITY_RESCUEStillImageBatchScanProfile.stillImageDense(1)barcode-intelligence , multi-barcode-dense
Batch receiving from an image STILL_IMAGE_BATCHStillImageBatchScanProfile.stillImageDense(expectedCount)barcode-intelligence , multi-barcode-dense

Live mode may discard stale camera frames. Once a still or batch input is accepted, it must not be silently dropped.

Native MatrixScan Tenant Telemetry

Reporting is off unless explicitly started . Complete authenticated enrollment with VisionScanSdk.initialize first. The verified VisionScan license must contain the registered backend UUID device ID , not a phone serial number. A Scandit license cannot activate VisionScan or authorize this API.

import com.visionscan.sdk.telemetry.MatrixTelemetryOptions

// Start before creating any MatrixScan session; runtime origin and version are host-owned.
val reporting = VisionScanSdk.startMatrixTelemetry(
    MatrixTelemetryOptions(
        controlPlaneOrigin = BuildConfig.VISION_SCAN_CONTROL_PLANE_ORIGIN,
        sdkVersion = VisionScanSdk.VERSION
    ),
    tokenProvider = { BuildConfig.VISION_SCAN_SDK_API_KEY }
)
val session = VisionScanSdk.createMatrixScanAR(config)
// Native processFrame results now report automatically; no per-frame host telemetry code.
// At a session boundary, request an asynchronous flush:
reporting.flushAsync()
// On logout/device/tenant change, stop camera/session first, then reporting.close().

The provider runs on the telemetry worker and returns the same complete workspace device SDK key used for initialization. The backend checks its telemetry scope and tenant/device ownership. A signed license JWS is not an authentication key. No credentials are stored by reporting. Android host manifests must request android.permission.INTERNET . Newly created sessions attach to the reporter; earlier sessions do not retroactively attach. Close/recreate them after enabling reporting. Batch/AR/Count/Find/Pick all use the same integration. Legacy VisionSession and hardware DataWedge are not automatically instrumented by this MatrixScan integration.

Licensing, Privacy And Delivery

  • Tenant/device/public license identity is read from the SDK's verified license,

never a telemetry tenant parameter. Tenant attribution is server-enforced from authenticated claims and registered device licensing. A key ID is not authentication.

  • POST /api/v1/sdk-telemetry/ingest receives bounded events using the published

backend record contract. No body tenant override, license key/token, barcode value, GTIN, lot, serial, image, quad or track ID is transmitted.

  • Native accepted events define acceptedBarcodes ; visible AR redraws and

cumulative native count do not increment it again. Count-mode physical copies remain separate. These are scan acceptance statistics, not receipt quantities.

  • The strict contracts/json/matrix-scan-usage.schema.json delta is sent in the

operational UsageCounter's diagnosticPayload . It contains mode, frames, acceptance/symbology counts, duplicate observations, decode calls, exhausted budgets, failed frames and native processing-duration sums/maxima. It does not measure time-to-first-scan, successful receipt commits or false decode rate.

  • Five fixed mode buckets update on the scan worker; JSON, encryption, disk and

HTTPS use a separate SDK worker. No retry/network/filesystem work enters the portable engine or camera loop. HTTPS redirects are refused.

  • Reporting defaults to 30-second intervals, 128 queued events and batches of 50.

The bounds are 10-600 seconds and 5-512 events. The worker uses bounded timeout, response/body size and retry backoff. Transient failures retain original event IDs; Accepted and Duplicate acknowledgments retire delivered events.

  • Per-event Rejected is terminal: it retires that event, increments

rejectedEvents , and exposes BACKEND_REJECTED , never delivery success. Missing, duplicate or unknown acknowledgment IDs retain the entire batch. When the queue fills, new counters remain in five bounded per-mode memory buckets and QUEUE_FULL signals delayed reporting. Reconnect drains immutable queued events, then schedules the retained counters without changing retry IDs. Scanning and receipt evidence remain unaffected. This is not a billing ledger.

  • Device, tenant or license-ID change stops the old reporter permanently. Close

it and start a new reporter after verified activation. Never reuse a reporter or persistent file for a different licensing identity.

Offline Storage And Cleanup

Without storage, queued summaries survive connectivity loss only within the current process. For process-restart recovery pass storage = MatrixTelemetryStorage(appPrivateFile, hostKeystoreAesKey) in options. The host supplies a stable AES/GCM-compatible key (prefer Android Keystore) and an app-private, per-license file excluded from backup. Never hardcode/export a key. The SDK uses authenticated encryption, identity-bound additional authenticated data and atomic replacement. Only one reporter may own that file. Corruption, wrong identity/key, or failed persistence reports STORAGE_FAILED , preserves the old file and prevents sending unpersisted events. Host remediation must be explicit. Already accumulated counters before the next interval remain memory-only and can be lost on abrupt process death even when encrypted storage is enabled. When closing with a full queue, counters that cannot be scheduled are explicitly counted in droppedEvents (summary buckets, not barcode count); QUEUE_FULL remains visible rather than being overwritten by CLOSED . Flush and verify delivery before shutdown when practical; offline capacity is not unlimited.

close() immediately stops new collection and queues final persistence without blocking the caller or attempting a final network upload. A request already in flight may finish. On a host cleanup worker call reporting.awaitStopped() after close and check its boolean result before reusing/deleting its file. isStopped reports termination; the SDK refuses a replacement reporter until that is true. Memory-only final queued events are not durable; call flushAsync() while still authenticated before stopping the reporter. Monitor status , queuedEvents , droppedEvents and rejectedEvents ; do not log credentials or response text.

Existing SaaS Dashboard

The tenant frontend at C:/Projects/Coefficiant/apps/vision-scan reads GET /api/v1/sdk-telemetry/usage for SDK usage/device diagnostics. The additive scanAnalytics projection introduced by backend PRXSAAS-BE-0244 and frontend PRXSAAS-FE-0181 supplies accepted-barcode, frame and duplicate-observation totals, UTC daily/cumulative series, symbology/mode histograms and registered-device counts. Large counters are exact decimal strings. The dashboard offers day/week grouping, cumulative/discrete charts, bounded 7/30/90-day filters and refresh.

totalEventCount remains telemetry messages, not scans. Accepted scans are native session admissions, not globally unique products: repeated AR redraws do not add acceptances, while distinct physical copies in count mode can. Charts use summary reporting time, not precise individual acquisition timestamps. isTruncated marks lower bounds when the query exceeds 20,000 events or 500 devices; unsupported usage summaries are excluded and reported, never guessed as scans. No raw payloads, images, credentials or support correlation IDs are returned by scan analytics. Device-model and historical license/project filtering are not supplied by this slice.

Software tests are not proof of enrolled phone-to-dashboard delivery. That check requires a trusted non-production HTTPS origin, an actually enrolled registered device UUID, verified VisionScan license, authorized token provider and device Keystore/storage validation. The POCO reference tester's direct JNI path is not automatically instrumented: use the Kotlin MatrixScan session facade after starting telemetry, or complete an explicitly reviewed host adapter before claiming coverage.

Native MatrixScan Camera Integration

Complete the signed-license setup in sections 1-3 before creating a session. The compiled integration is samples/android-sample/src/main/kotlin/com/visionscan/sample/MatrixScanCameraBinding.kt . It shows CameraX binding, a single worker, bounded UI result delivery and cleanup. It is sample source, not a class bundled in the SDK AAR.

Minimal SDK Handoff

import androidx.camera.core.ImageAnalysis
import com.visionscan.sdk.VisionScanSdk
import com.visionscan.sdk.VisionSessionConfig
import com.visionscan.sdk.camerax.MatrixScanAnalyzer
import com.visionscan.sdk.camerax.MatrixScanCameraListener
import com.visionscan.sdk.camerax.MatrixScanCameraResult
import com.visionscan.sdk.camerax.MatrixScanCameraError

// config has authenticated tenant/site/session context; license is already verified.
val session = VisionScanSdk.createMatrixScanAR(config)
val analyzer = MatrixScanAnalyzer(session, object : MatrixScanCameraListener {
    override fun onResult(frame: MatrixScanCameraResult) {
        // Consume frame.result.accepted for host evidence BEFORE conflating UI frames.
        // Worker callback: offer to a bounded latest-result UI handoff.
        // On UI: previewView.outputTransform?.let { frame.mapVisibleTracks(it) }
        // Draw each overlay.quad; identity/state remain in overlay.track.
    }
    override fun onError(error: MatrixScanCameraError) {
        // Worker callback: display typed failure; do not log frames or payloads.
    }
})
val analysis = ImageAnalysis.Builder()
    .setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888)
    .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
    .build()
analysis.setAnalyzer(singleWorkerExecutor, analyzer)

Bind Preview and ImageAnalysis in the same UseCaseGroup/ViewPort from a laid-out PreviewView. The sample selects 1920x1080 with device fallback; tune resolution/focus for your device and barcode size rather than assuming CameraX defaults are sufficient. No automatic zoom is imposed by this adapter.

The SDK adapter copies stride-correct luma, calls the native session, captures the source transform and closes every delivered ImageProxy in finally . Callbacks contain no borrowed camera buffer. Callbacks execute on the worker; keep them short. Use the sample's one-pending UI update pattern rather than posting every camera result into an unbounded UI queue.

The compiled binding delivers every processed result to onFrame on the worker before conflating visual updates for onOverlays on UI. Route native accepted evidence and required audit metadata through that worker callback; do not derive a durable acceptance stream from the latest-only UI callback. Host persistence/domain qualification must acknowledge evidence or surface an explicit failure, not silently discard it. Camera frames may be skipped before native processing; already returned acceptance evidence must not be hidden by the rendering policy.

Geometry And Ownership

Native MatrixTrack.quad is four ordered points in full unrotated input-luma pixels . MatrixScanCameraResult.mapVisibleTracks(previewView.outputTransform) uses CameraX transforms for rotation, crop, preview scale and mirroring. It returns MatrixScanOverlay : original track plus mapped quad in PreviewView pixels. Render in a view aligned with PreviewView; never replace the quad with a locator tile or separately rotate/crop it again. If outputTransform is null, skip painting until layout/preview is ready. Clear overlays on failure, stop and camera rebind. Discard pending callbacks from the previous binding, as the compiled sample does.

The adapter is live-only. CameraX may replace stale frames, and overlapping analyzer calls are released without decoding. Accepted still/burst inputs must instead be processed synchronously through session.processFrame ; do not route them through this dropping live adapter.

Shutdown order: on the main thread close the binding (or close analyzer, clearAnalyzer and unbind only your camera use cases); then schedule session.close() on the same worker and shut down that executor after queued cleanup. Analyzer.close() is idempotent and does not close the borrowed session or executor. Already admitted work finishes and delivers its worker callback, including acceptance evidence; suppress only stale UI painting. Create a new session when resolution changes, a scan operation ends, or tenant/site changes.

Result And Mode Semantics

  • visibleTracks : native stable tracks seen in this frame. Use for AR, not

historical tracks. Failed/cancelled/invalid results expose no visible boxes.

  • accepted : newly accepted native evidence under the mode policy. It is

not every visible barcode on every frame.

  • Batch/AR count unique payload-plus-symbology identities for the session.

Count mode uses physical tracks; two identical labels in different locations remain separate. Neither count is a receipt quantity or unique-GTIN count.

  • Find/Pick use setTargets(List<ByteArray>) ; inspect targetMatched .

Pick updates native state using setPickState(trackId, MatrixPickState.PICKED) . All visible quads can be drawn, including non-targets; style by native state.

  • payload is raw bytes, not necessarily UTF-8. Decode text only under a

declared symbology/domain policy. GS1/pharmacy qualification belongs outside the generic camera adapter. Arrays are caller-owned mutable snapshots: do not mutate results shared with other consumers or log their contents.

Status / error Host action
OK with empty tracks Normal no-decode frame; keep scanning.
CAPACITY_REACHED Show capacity state; finish/export and start a new operation.
INVALID_FRAME Check buffer layout and increasing timestamps; recreate after resolution change.
CANCELLED / DECODER_ERROR Clear overlays; stop or explicitly recover, never auto-commit evidence.
ENTITLEMENT_DENIED Stop scanning and refresh/reconcile verified licensing.
INVALID_IMAGE Check YUV format, dimensions, strides and CameraX timestamp.
PROCESSING_FAILED Stop/recreate or report adapter failure without logging sensitive result JSON.

The decoder rejects incompatible wire versions, coordinate spaces, encodings and malformed typed results with a redacted IllegalStateException. No partial result is returned. Native budgets are cooperative, not hard frame deadlines. The SDK has no Scandit dependency. Android MatrixScan is evaluation-only; iOS MatrixScan and a stable C MatrixScan session ABI are not published contracts. See API details and limits .

Prerequisites

  • Android Studio with JDK 17 and an Android API 35 SDK installed.
  • An application with minSdk 26 or newer.
  • A rear camera capable of YUV_420_888 ; continuous autofocus and torch are recommended.
  • A Vision Scan workspace with an active trial or purchased device seat and its device SDK key.
  • A tenant download grant for the signed Android evaluation kit.
  • Camera and internet permission; use a physical Android phone for the first scan.

The granted ZIP contains a Maven repository, standalone sample source, documentation, notices and SBOM. It contains no tenant key, prebuilt tenant-configured APK or required synthetic test label.

1. Verify and install the SDK

Compare the ZIP SHA-256 against the authenticated catalog before extracting it. Reject a revoked release or checksum mismatch. Server HMAC signing keys are never customer inputs.

Verify the downloaded archive against the authenticated catalog SHA-256. Extract its Maven repository into vision-scan-kit/maven so the wrapper and transitive dependencies are available; do not install the SDK AAR alone:

repositories {
    maven { url = uri(rootProject.file("vision-scan-kit/maven")) }
    google()
    mavenCentral()
}

dependencies {
    implementation("com.visionscan.sdk:vision-scan-android-sdk:0.1.0-RC5")
    implementation("androidx.camera:camera-core:1.4.1")
    implementation("androidx.camera:camera-camera2:1.4.1")
    implementation("androidx.camera:camera-lifecycle:1.4.1")
    implementation("androidx.camera:camera-view:1.4.1")
}

The release AAR includes consumer-rules.pro . Keep the kit notices and open-source attributions with the application distribution.

Declare camera and network access:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />

Request camera permission at runtime before binding CameraX.

2. Issue a device SDK key and initialize

From the tenant workspace, activate a free trial or purchase a device seat, then create a device SDK key for that entitled seat. Trial activation is optional when the tenant already has a paid seat. Add the one-time key to the host app's protected build configuration and pass it to VisionScanSdk.initialize ; never ask the device user to type it or accept a tenant ID from the app UI.

// Worker thread only. The backend validates the key in its database and resolves
// the associated tenant/device. It also stores the Android Build metadata.
val initialized = VisionScanSdk.initialize(
    applicationContext,
    VisionScanSdkConfiguration(
        controlPlaneOrigin = BuildConfig.VISION_SCAN_CONTROL_PLANE_ORIGIN,
        apiKey = BuildConfig.VISION_SCAN_SDK_API_KEY
    )
)
val tenantId = initialized.tenantId
val deviceId = initialized.deviceId

Use a unique, revocable key for each device installation. The SDK sends the key only in the HTTPS X-Api-Key header, does not log or persist it, and clears the previous local lease before attempting a new initialization. The backend remains the authority for key validity, tenant ownership, seat status, and license claims.

3. Alternative: authenticated bearer-token enrollment

The host application performs login and tenant selection. Use the authenticated control-plane sequence; do not accept a tenant id from an untrusted route or editable local setting:

  1. POST /api/v1/auth/login
  2. GET /api/v1/tenants/current
  3. POST /api/v1/evaluations/activate
  4. Request and redeem the tenant-scoped SDK download grant.
  5. POST /api/v1/Devices/reserve-seat
  6. POST /api/v1/Devices/activate-device
  7. Refresh the device license only after activation succeeds.

Cross-tenant reservation, duplicate non-idempotent activation, an expired trial, or a revoked subscription must fail closed at the backend and SDK boundary.

4. Advanced bearer-token path: refresh and verify the signed license

Run the blocking network refresh on an I/O worker. The origin must be HTTPS and contains no path, query, or fragment.

VisionScanSdk.initializeLeaseStore(
    storageDir = File(context.noBackupFilesDir, "visionscan-license"),
    hostDeviceId = deviceId
)

val refresh = VisionScanSdk.refreshPaidLicense(
    controlPlaneOrigin = "https://api.example.com",
    tenantId = tenantId,
    deviceId = deviceId,
    bearerToken = shortLivedAccessToken
)
check(refresh.activated) { "VisionScan activation failed: ${refresh.errorCode}" }

refreshPaidLicense fetches the fixed license/JWKS routes, verifies the asymmetric signature and claims, persists the device-bound lease, and applies it. If the host already obtained a compact JWS, use:

val evaluation = VisionScanSdk.applySignedLicenseJws(jws, tenantId, deviceId)
check(evaluation.isAllowed) { evaluation.denialReason ?: "License denied" }

The legacy object-taking applySignedLicense overload is permanently denied. Never place a backend signing key or a caller-created license object in an Android application.

5. Create a session

val session = VisionScanSdk.createSession(
    VisionSessionConfig(
        sessionId = UUID.randomUUID().toString(),
        tenantId = tenantId,
        siteId = siteId,
        scanMode = ScanMode.LIVE_STREAM
    )
)

Session creation throws VisionScanEntitlementDeniedException when the verified lease is missing, expired, revoked, outside offline grace, bound to another tenant/device, or missing the required feature.

6. Submit CameraX frames safely

Configure ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST for live sweep. Camera buffers can contain row padding, so do not copy buffer.remaining() and assume it equals width * height . Use the public extractor and close every proxy exactly once:

class VisionScanAnalyzer(
    private val session: VisionSession,
    private val onObservations: (List<BarcodeObservation>) -> Unit,
    private val onError: (Throwable) -> Unit
) : ImageAnalysis.Analyzer {
    override fun analyze(image: ImageProxy) {
        try {
            val plane = image.planes.first()
            val luma = YPlaneExtractor.extractYPlane(
                plane.buffer,
                image.width,
                image.height,
                plane.rowStride,
                plane.pixelStride
            )
            val result = session.processFrame(
                image.width,
                image.height,
                ImageFormat.YUV_420_888,
                luma,
                StillImageBatchScanProfile.liveSweep()
            )
            check(result.status >= 0) { "VisionScan rejected frame with status ${result.status}" }
            onObservations(result.observations)
            val overlayTracks = result.tracking.tracks
        } catch (error: Throwable) {
            onError(error)
        } finally {
            image.close()
        }
    }
}

The same code is compiled as samples/android-sample/.../VisionScanAnalyzer.kt . The reference app additionally demonstrates CameraXAdapter , PreviewView , permission handling, lifecycle binding, and STRATEGY_KEEP_ONLY_LATEST .

7. Render only verified observations

val gtins = session.getLatestObservations()
    .filterNot { it.isOcrRescue }
    .mapNotNull { it.gtin }
    .distinct()

An empty list is a valid no-decode result. GTIN remains the primary pharmacy identity; lot, expiration, and serial remain dependent evidence. OCR-only GTIN or serial evidence requires review and must not auto-commit. PremierRx backend validation remains authoritative for purchase order, quantity, short-date policy, serial uniqueness, and receipt commit.

For find/pick workflows, install exact decoded barcode targets before scanning:

session.setFindTargets(
    listOf(VisionScanTarget(rawPayload = "036000291452", label = "matchbox", requiredStableObservations = 2))
)

result.tracking is native SDK session state. Use activeTrackCount , stableTrackCount , and targetMatchCount for count/find status; render VisionTrackedBarcode.points as overlay geometry. Targets match only deterministic decoder payloads after stable evidence, never OCR-only or geometry-inferred values.

For MatrixScan Count-style duplicate handling, use duplicatePayloadTrackCount and the full tracks list rather than counting distinct payload strings. Two physical products with the same UPC/EAN remain separate native tracks when the SDK sees separate geometry. For MatrixScan Pick-style flows, mark work completed with:

session.setTrackPickState(trackId, VisionPickState.PICKED)

The SDK reports pick state and overlay geometry; the host decides presentation, confirmation UX, and backend commit.

8. Focused rescue and batch images

Use a separate appropriately licensed session for dense rescue or batch receiving:

VisionScanSdk.createSession(tenantId, siteId, ScanMode.STILL_IMAGE_BATCH).use { batch ->
    val profile = StillImageBatchScanProfile.stillImageDense(expectedBarcodeCount = 12)
    val result = batch.processFrame(width, height, ImageFormat.YUV_420_888, gray8, profile)
    check(result.status >= 0)
    val observations = result.observations
}

Decode selected images outside the portable core, normalize them to bounded Gray8/YUV luminance, preserve aspect ratio, and reject malformed or oversized input before submission.

9. Lifecycle, offline grace, and errors

  • Refresh at login, foreground, device reassignment, entitlement revision change, and before lease expiry.
  • Close VisionSession , CameraXAdapter , executors, and auto-refresh handles on lifecycle stop or logout.
  • Keep the bearer token only in host-owned memory/secure credential storage; the lease store is for verified leases, not access tokens.
  • Offline scanning is allowed only through signed grace claims and fails closed when grace expires or anti-rollback checks fail.
  • Stop scanning after entitlement denial; keep redacted diagnostics available for support.
  • Never log JWS values, bearer tokens, raw images, full serial numbers, or tenant-identifying payloads.

10. Test the integration

The downloaded ZIP's sample walkthrough builds against the actual delivered AAR. Check native captures first, then confirm tenant telemetry. These repository-maintainer commands are optional for teams working from SDK source:

.\gradlew.bat :customer-android-sample:assembleDebug
.\gradlew.bat :reference-android-app:assembleDebug
python samples\control_plane_smoke.py

Test at least: active trial, paid active, expired trial, revoked license, missing feature, cross-tenant device reservation, offline grace expiry, duplicate idempotency, camera permission denial, padded Y-plane rows, background/foreground, and device rotation.

For a same-device comparison with another licensed SDK, use the vendor-neutral prx-android-sdk-benchmark/v1 contract and scripts/compare_android_scanner_runs.py . The protocol is in docs/testing/testing_and_benchmarking_guide.md . Do not compare different devices, corpora, resolutions, modes, or ground-truth revisions.

Troubleshooting

Symptom Check
License refresh denied HTTPS origin, authenticated tenant, activated device, trial/subscription state, device binding, and server time.
Session creation denied JWS verification, expiry/revocation, offline grace, tenant binding, and feature entitlement.
Frames accepted but no GTIN Read getLatestObservations() ; verify focus, motion blur, glare, working distance, Y-plane extraction, and supported symbology.
Distorted or intermittent decode Confirm row/pixel stride handling and do not reuse an ImageProxy after close() .
Live preview stalls Use KEEP_ONLY_LATEST , close every proxy in finally , and avoid work on the main thread.
Batch mode denied Confirm multi-barcode-dense entitlement and use a batch/rescue session.

Generate a redacted support bundle and include SDK version, correlation id, device profile, entitlement state, and non-sensitive session summary. Raw images require explicit policy and consent.

Support matrix

Full API contract reference

Public contract reference

These are the callable methods and HTTP operations used by this guide. Inputs, results, lifecycle rules, and denial behavior are part of the versioned customer contract.

Hardware enrollment proof and bound lease admission

PRXV-0132-S10: Android hardware-only installation keys, current app signers and signed lease binding. Wire contract: contracts/json/sdk-hardware-binding.schema.json. Backend attestation and atomic activation remain release gates.

VisionScanSdk.createEnrollmentProof(context: Context, challenge: VisionScanEnrollmentChallenge): VisionScanHardwareBindingProof

method

Create an app-scoped non-exportable hardware P-256 key and signed enrollment evidence.

Inputs for VisionScanSdk.createEnrollmentProof(context: Context, challenge: VisionScanEnrollmentChallenge): VisionScanHardwareBindingProof
InputTypeRequiredMeaning
contextContextYesReal application context supplies package and current signing identity.
challengeVisionScanEnrollmentChallengeYesTrusted server-issued bounded nonce and origin; no caller-generated enrollment authority.
Result
Restricted proof JSON containing public SPKI, DER signature and bounded attestation chain; never a private key.
Lifecycle
Worker only; once per approved installation. Existing keys are never overwritten; recovery requires admin approval.
Trust boundary
No networking. Server validates chain trust, revocation, app identity and challenge and consumes it atomically. Client labels are not authority; no proof in logs or telemetry.
Failure behavior
  • VisionScanBindingException.code: malformed/expired challenge, worker required, existing key, unavailable attestation or hardware key.

VisionScanSdk.createLicenseBindingProof(context: Context, challenge: VisionScanEnrollmentChallenge): VisionScanHardwareBindingProof

method

Prove possession of the existing installation key for lease renewal.

Inputs for VisionScanSdk.createLicenseBindingProof(context: Context, challenge: VisionScanEnrollmentChallenge): VisionScanHardwareBindingProof
InputTypeRequiredMeaning
contextContextYesReal application context.
challengeVisionScanEnrollmentChallengeYesFresh server challenge bound to approved origin and public license ID.
Result
Signed proof with empty attestation chain; server uses previously verified enrollment.
Lifecycle
Worker only. Missing keys never regenerate silently.
Trust boundary
Public-key hash is SHA-256 of DER SPKI, not JWK thumbprint. Renewal signature does not establish new attestation trust.
Failure behavior
  • Malformed/expired challenge, missing key or hardware provider failure fail closed.

VisionScanSdk.initializeHardwareBinding(context: Context)

method

Require signed app/signer/key matching before commercial lease admission.

Inputs for VisionScanSdk.initializeHardwareBinding(context: Context)
InputTypeRequiredMeaning
contextContextYesPlatform app context reads the existing installation key and current signers.
Result
Strict binding mode, with old process admission cleared even if setup fails.
Lifecycle
Call on a worker after lease-store initialization and before applying a bound lease. Store reinitialization retains strict mode.
Trust boundary
Legacy unconfigured hosts remain compatible. This is not an encrypted-key activation API. Unsupported Swift/C++ hosts reject bound leases rather than ignore them.
Failure behavior
  • Missing/non-hardware key rejects setup; signed binding absence/mismatch rejects admission; key loss or signer change stops feature checks.

Android license lifecycle

The host stores only a verified device-bound lease and never constructs entitlement claims.

VisionScanSdk.initialize(context: Context, configuration: VisionScanSdkConfiguration): VisionScanSdkInitializationResult

method

Validate a workspace-issued device SDK key and initialize the matching tenant/device license without collecting credentials in the app UI.

Inputs for VisionScanSdk.initialize(context: Context, configuration: VisionScanSdkConfiguration): VisionScanSdkInitializationResult
InputTypeRequiredMeaning
contextContextYesApplication context used to create device-bound, no-backup lease storage.
controlPlaneOriginHTTPS originYesTrusted VisionScan control-plane origin; HTTPS only, with no path, query, or fragment.
apiKeydevice SDK API keyYesOne-time workspace-issued device key supplied by the host application's build/configuration code, never typed into an end-user screen.
Result
Tenant and registered device IDs resolved by the backend after database-backed key validation and a verified signed-license refresh.
Lifecycle
Blocking; call on a worker. Run at app initialization and again after key rotation or device reassignment. The backend records Android manufacturer, model, device build, OS version, and API level.
Trust boundary
The tenant and device are derived from authenticated database records, never caller input. The key is sent only over HTTPS, is not logged or stored by the SDK, and should be unique and revocable per device; a client-embedded key can be extracted from the application package.
Failure behavior
  • Invalid, revoked, or unknown key; unentitled seat; rejected device metadata; unavailable control plane; invalid signed license; or tenant/device claim mismatch deny initialization.

VisionScanSdk.initializeLeaseStore(storageDir: File, hostDeviceId: String): Unit

method

Configure device-bound persistence used for offline grace and anti-rollback checks.

Inputs for VisionScanSdk.initializeLeaseStore(storageDir: File, hostDeviceId: String): Unit
InputTypeRequiredMeaning
storageDirFileYesA host-owned no-backup directory; do not use a shared or user-exportable location.
hostDeviceIdStringYesThe stable device identifier activated for the authenticated tenant.
Result
Replaces the process entitlement manager with one backed by the device-bound lease store.
Lifecycle
Call once after authenticated device enrollment and before applying or refreshing a license.
Trust boundary
Store verified leases only; bearer tokens remain in host-owned secure credential storage.
Failure behavior
  • Blank or unstable device identity prevents a durable binding.
  • Unreadable storage causes later lease persistence or offline checks to fail closed.

VisionScanSdk.refreshPaidLicense(controlPlaneOrigin, tenantId, deviceId, bearerToken): LicenseRefreshResult

method

Fetch the fixed license and JWKS routes, verify the compact JWS, persist it, and activate it for the process.

Inputs for VisionScanSdk.refreshPaidLicense(controlPlaneOrigin, tenantId, deviceId, bearerToken): LicenseRefreshResult
InputTypeRequiredMeaning
controlPlaneOriginHTTPS originYesScheme and authority only; paths, queries, fragments, cleartext HTTP, and untrusted redirects are rejected.
tenantIdStringYesThe tenant resolved from the authenticated session.
deviceIdStringYesThe already activated device bound to a reserved seat.
bearerTokenStringYesA short-lived access token kept out of source, resources, intents, and logs.
Result
LicenseRefreshResult with activated=true only after signature and claim verification succeeds.
Lifecycle
Run on an I/O worker at login, foreground, entitlement revision changes, reassignment, and before lease expiry.
Trust boundary
The client cannot select arbitrary license routes or weaken the allowlisted signing algorithms.
Failure behavior
  • Network, HTTP, JWKS, signature, claim, tenant, device, expiry, revision, and persistence failures return activated=false.
  • The method never falls back to caller-created claims.

VisionScanSdk.applySignedLicenseJws(jws, expectedTenantId, expectedDeviceId, nowEpochSeconds): EntitlementEvaluationResult

method

Verify and apply a backend-issued compact JWS already fetched by authenticated host networking.

Inputs for VisionScanSdk.applySignedLicenseJws(jws, expectedTenantId, expectedDeviceId, nowEpochSeconds): EntitlementEvaluationResult
InputTypeRequiredMeaning
jwscompact JWSYesA backend-signed license envelope; never a caller-created claims object.
expectedTenantIdStringYesThe authenticated tenant that must match the signed tenant claim.
expectedDeviceIdStringYesThe activated device that must match the signed device claim.
nowEpochSecondsLongNoCurrent Unix time; callers normally use the default and inject time only in tests.
Result
EntitlementEvaluationResult describing allow/deny state, plan, remediation, and correlation identifier.
Lifecycle
Apply before session creation and refresh when the signed lease approaches expiry or the entitlement revision changes.
Trust boundary
The legacy object-taking applySignedLicense overload is permanently fail-closed.
Failure behavior
  • Unknown key, disallowed algorithm, invalid signature, issuer/audience mismatch, invalid timestamps, wrong tenant/device, rollback revision, revocation, expiry, or offline-grace expiry deny access.

Android session and frame lifecycle

A session is a tenant-scoped, entitlement-gated, AutoCloseable native processing lifecycle.

VisionScanSdk.createSession(config: VisionSessionConfig): VisionSession

method

Create a native scanning session for one tenant, site, and execution mode.

Inputs for VisionScanSdk.createSession(config: VisionSessionConfig): VisionSession
InputTypeRequiredMeaning
config.sessionIdStringYesA non-empty identifier unique to the host workflow.
config.tenantIdStringYesMust match the cryptographically verified active license.
config.siteIdStringYesThe authenticated facility or location scope.
config.scanModeScanModeYesLIVE_STREAM, STILL_IMAGE_BATCH, or HIGH_DENSITY_RESCUE.
Result
A ready VisionSession that owns native resources and must be closed.
Lifecycle
Create after license admission; close on workflow completion, logout, or lifecycle stop.
Trust boundary
Batch and rescue modes require both barcode-intelligence and multi-barcode-dense features.
Failure behavior
  • Invalid identifiers throw IllegalArgumentException.
  • Missing, unverified, wrong-tenant, expired, revoked, or feature-incomplete entitlement throws VisionScanEntitlementDeniedException.
  • A missing native bridge throws VisionScanNativeUnavailableException.

VisionSession.submitFrame(width, height, format, buffer, profile?): Int

method

Compatibility entry point that submits one bounded luminance frame to the native pipeline, optionally with an explicit preprocessing profile.

Inputs for VisionSession.submitFrame(width, height, format, buffer, profile?): Int
InputTypeRequiredMeaning
width / heightIntYesPositive pixel dimensions matching the normalized buffer.
formatIntYesThe SDK-supported image format code; CameraX integrations submit extracted luminance.
bufferByteArrayYesA stride-correct frame. Use YPlaneExtractor for padded CameraX Y planes.
profileStillImageBatchScanProfileNoUse liveSweep for responsive camera work or stillImageDense for licensed rescue/batch input.
Result
A native status code. It is not a barcode count; prefer processFrame for same-frame observations.
Lifecycle
Submit only while the session is open. Live mode may drop stale frames; accepted batch input must not be silently dropped.
Trust boundary
The host must bound decoded image size and must not retain or upload image bytes without policy and consent.
Failure behavior
  • Closed sessions throw IllegalStateException.
  • Invalid dimensions, format, buffer, entitlement, or native state return or throw a deterministic failure.

VisionSession.processFrame(width, height, format, buffer, profile?): VisionFrameProcessResult

method

Process one bounded luminance frame through the SDK-owned native scan pipeline and return the status plus observations from that same accepted frame.

Inputs for VisionSession.processFrame(width, height, format, buffer, profile?): VisionFrameProcessResult
InputTypeRequiredMeaning
width / heightIntYesPositive pixel dimensions matching the normalized buffer.
formatIntYesThe SDK-supported image format code; CameraX integrations submit extracted luminance.
bufferByteArrayYesA stride-correct frame. Use YPlaneExtractor for padded CameraX Y planes.
profileStillImageBatchScanProfileNoUse liveSweep for responsive camera work or stillImageDense for licensed rescue/batch input.
Result
VisionFrameProcessResult(status, observations, tracking), where observations are native-decoded evidence from the same accepted frame and tracking contains native stable tracks, active/distinct/stable counts, duplicate-payload physical track count, dense-selection hints, exact target matches, pick state, and overlay-ready quadrilaterals.
Lifecycle
Use for new live and batch capture integrations. Live mode may drop stale frames by policy; accepted batch input must not be silently dropped.
Trust boundary
The host must bound decoded image size and must not retain or upload image bytes without policy and consent.
Failure behavior
  • Closed sessions throw IllegalStateException.
  • Invalid dimensions, format, buffer, entitlement, or native state return or throw a deterministic failure.

VisionSession.setFindTargets(targets: List<VisionScanTarget>): Unit

method

Install exact decoded-payload targets for SDK-owned find/pick matching.

Inputs for VisionSession.setFindTargets(targets: List<VisionScanTarget>): Unit
InputTypeRequiredMeaning
targetsList<VisionScanTarget>YesZero or more payload labels with required stable observation counts. Empty clears targets.
Result
Targets are applied to the native session tracker; subsequent processFrame results update tracking.targetMatchCount and per-track targetMatched/targetLabel.
Lifecycle
Call after session creation and before or during scanning. Targets are session-local and cleared on close.
Trust boundary
Matching is exact against deterministic decoder payloads; geometry and OCR-only rescue never synthesize a target value.
Failure behavior
  • Closed sessions throw IllegalStateException.
  • A missing native target matcher throws VisionScanNativeUnavailableException.

VisionSession.setTrackPickState(trackId: Long, state: VisionPickState): Boolean

method

Update one native tracked barcode's pick state for MatrixScan Pick-style workflows.

Inputs for VisionSession.setTrackPickState(trackId: Long, state: VisionPickState): Boolean
InputTypeRequiredMeaning
trackIdLongYesA positive native track ID returned in VisionTrackedBarcode.trackId.
stateVisionPickStateYesTO_PICK, PICKED, or IGNORED.
Result
True when the native session updated a known track; false when the track is stale or unknown.
Lifecycle
Call only while the session is open. The state is session-local and returned on subsequent tracking results.
Trust boundary
Pick state is workflow metadata only; receipt commit and quantity authority remain outside the scanner SDK.
Failure behavior
  • Closed sessions throw IllegalStateException.
  • Non-positive track IDs throw IllegalArgumentException.
  • A missing native pick-state bridge throws VisionScanNativeUnavailableException.

Android decoded observation contract

Decoded evidence is read separately from frame admission and remains GTIN-first.

VisionSession.getLatestObservations(): List<BarcodeObservation>

method

Return immutable observations produced by the most recently accepted frame.

Result
Zero or more BarcodeObservation values containing rawPayload, symbology, GTIN, dependent lot/expiry/serial evidence, OCR provenance, and confidence.
Lifecycle
Read after submitFrame succeeds and before the session is closed.
Trust boundary
OCR-only GTIN or serial evidence requires review and must never auto-commit; backend receipt validation remains authoritative.
Failure behavior
  • An empty list is a valid no-decode result.
  • Closed sessions throw IllegalStateException.
  • Malformed native observations fail deterministically instead of producing sample data.

Native MatrixScan sessions

PRXV-0122-S01: one native session owns bounded location/decode, tracks and state. Result schema: contracts/schemas/matrix-scan-result.schema.json; formats: contracts/matrix-scan-capabilities.json.

VisionScanSdk.createMatrixScanBatch(config: VisionSessionConfig, formats: Set<MatrixSymbology> = emptySet()): MatrixScanBatch

method

Accept each stable identity once and suppress repeats.

Inputs for VisionScanSdk.createMatrixScanBatch(config: VisionSessionConfig, formats: Set<MatrixSymbology> = emptySet()): MatrixScanBatch
InputTypeRequiredMeaning
configVisionSessionConfigYesVerified tenant context. Barcode intelligence and dense scan entitlement are rechecked on every operation.
formatsSet<MatrixSymbology>NoOnly declared native capabilities; Codabar/ITF require opt-in.
Result
MatrixScanResult: status, input-pixel geometry, tracks, accepted, count and bounded scheduler diagnostics.
Lifecycle
Off camera/UI threads. Monotonic input timestamps. close() releases session. Capacity is explicit; a new operation requires a new session.
Trust boundary
Signed tenant license required by the public Android facade. Physical scan counts are not pharmacy quantities or backend receipt commits.
Failure behavior
  • Invalid/truncated/oversized frame rejected.
  • Decoder failure, cancellation and capacity reached are explicit.
  • Decode time budget is cooperative between backend calls; it does not interrupt an in-flight decoder.

VisionScanSdk.createMatrixScanAR(config: VisionSessionConfig, formats: Set<MatrixSymbology>): MatrixScanAR

method

Publish persistent decoder-confirmed quadrilaterals.

Inputs for VisionScanSdk.createMatrixScanAR(config: VisionSessionConfig, formats: Set<MatrixSymbology>): MatrixScanAR
InputTypeRequiredMeaning
configVisionSessionConfigYesVerified tenant context. Barcode intelligence and dense scan entitlement are rechecked on every operation.
formatsSet<MatrixSymbology>NoOnly declared native capabilities; Codabar/ITF require opt-in.
Result
MatrixScanResult: status, input-pixel geometry, tracks, accepted, count and bounded scheduler diagnostics.
Lifecycle
Off camera/UI threads. Monotonic input timestamps. close() releases session. Capacity is explicit; a new operation requires a new session.
Trust boundary
Signed tenant license required by the public Android facade. Physical scan counts are not pharmacy quantities or backend receipt commits.
Failure behavior
  • Invalid/truncated/oversized frame rejected.
  • Decoder failure, cancellation and capacity reached are explicit.
  • Decode time budget is cooperative between backend calls; it does not interrupt an in-flight decoder.

VisionScanSdk.createMatrixScanCount(config: VisionSessionConfig, formats: Set<MatrixSymbology>): MatrixScanCount

method

Count stable physical tracks; identical payloads at distinct locations remain separate.

Inputs for VisionScanSdk.createMatrixScanCount(config: VisionSessionConfig, formats: Set<MatrixSymbology>): MatrixScanCount
InputTypeRequiredMeaning
configVisionSessionConfigYesVerified tenant context. Barcode intelligence and dense scan entitlement are rechecked on every operation.
formatsSet<MatrixSymbology>NoOnly declared native capabilities; Codabar/ITF require opt-in.
Result
MatrixScanResult: status, input-pixel geometry, tracks, accepted, count and bounded scheduler diagnostics.
Lifecycle
Off camera/UI threads. Monotonic input timestamps. close() releases session. Capacity is explicit; a new operation requires a new session.
Trust boundary
Signed tenant license required by the public Android facade. Physical scan counts are not pharmacy quantities or backend receipt commits.
Failure behavior
  • Invalid/truncated/oversized frame rejected.
  • Decoder failure, cancellation and capacity reached are explicit.
  • Decode time budget is cooperative between backend calls; it does not interrupt an in-flight decoder.

VisionScanSdk.createMatrixScanFind(config: VisionSessionConfig, formats: Set<MatrixSymbology>): MatrixScanFind

method

Find exact byte targets only after stable decode evidence.

Inputs for VisionScanSdk.createMatrixScanFind(config: VisionSessionConfig, formats: Set<MatrixSymbology>): MatrixScanFind
InputTypeRequiredMeaning
configVisionSessionConfigYesVerified tenant context. Barcode intelligence and dense scan entitlement are rechecked on every operation.
formatsSet<MatrixSymbology>NoOnly declared native capabilities; Codabar/ITF require opt-in.
Result
MatrixScanResult: status, input-pixel geometry, tracks, accepted, count and bounded scheduler diagnostics.
Lifecycle
Off camera/UI threads. Monotonic input timestamps. close() releases session. Capacity is explicit; a new operation requires a new session.
Trust boundary
Signed tenant license required by the public Android facade. Physical scan counts are not pharmacy quantities or backend receipt commits.
Failure behavior
  • Invalid/truncated/oversized frame rejected.
  • Decoder failure, cancellation and capacity reached are explicit.
  • Decode time budget is cooperative between backend calls; it does not interrupt an in-flight decoder.

VisionScanSdk.createMatrixScanPick(config: VisionSessionConfig, formats: Set<MatrixSymbology>): MatrixScanPick

method

Find targets and retain per-track pick transitions.

Inputs for VisionScanSdk.createMatrixScanPick(config: VisionSessionConfig, formats: Set<MatrixSymbology>): MatrixScanPick
InputTypeRequiredMeaning
configVisionSessionConfigYesVerified tenant context. Barcode intelligence and dense scan entitlement are rechecked on every operation.
formatsSet<MatrixSymbology>NoOnly declared native capabilities; Codabar/ITF require opt-in.
Result
MatrixScanResult: status, input-pixel geometry, tracks, accepted, count and bounded scheduler diagnostics.
Lifecycle
Off camera/UI threads. Monotonic input timestamps. close() releases session. Capacity is explicit; a new operation requires a new session.
Trust boundary
Signed tenant license required by the public Android facade. Physical scan counts are not pharmacy quantities or backend receipt commits.
Failure behavior
  • Invalid/truncated/oversized frame rejected.
  • Decoder failure, cancellation and capacity reached are explicit.
  • Decode time budget is cooperative between backend calls; it does not interrupt an in-flight decoder.

Android native MatrixScan camera integration

PRXV-0122-S04: SDK-owned stride extraction, deterministic frame release and native-quad preview mapping. Host retains permission, camera binding, UI, secure storage and backend commit.

MatrixScanSession.processFrame(luma: ByteArray, width: Int, height: Int, stride: Int = width, timestampNs: Long = System.nanoTime()): MatrixScanResult

method

Submit one full unrotated luminance frame to the native session.

Inputs for MatrixScanSession.processFrame(luma: ByteArray, width: Int, height: Int, stride: Int = width, timestampNs: Long = System.nanoTime()): MatrixScanResult
InputTypeRequiredMeaning
frameByteArray + dimensions + stride + monotonic nanosecondsYesCaller-owned readable luma; fixed dimensions per session; no concurrent mutation. Maximum axis 8192 and 32000000 pixels.
Result
Typed MatrixScanResult with industry-neutral byte payloads and input-pixel quads. visibleTracks excludes lost/unstable tracks and failed-frame boxes.
Lifecycle
Synchronous worker call. Native state is session-owned; close after the operation. Do not feed accepted still/burst inputs through dropping live adapters.
Trust boundary
Verified license checked on every call. Payload is not necessarily UTF-8; counts are not backend receipt quantity.
Failure behavior
  • Invalid frame and decoder/capacity/cancellation statuses are explicit.
  • Incompatible native JSON version, encoding, mode or malformed typed result raises a redacted IllegalStateException.

MatrixScanAnalyzer(session: MatrixScanSession, listener: MatrixScanCameraListener): ImageAnalysis.Analyzer, AutoCloseable

type

Adapt live CameraX ImageProxy input without host pixel copying, tracking or decoder orchestration.

Inputs for MatrixScanAnalyzer(session: MatrixScanSession, listener: MatrixScanCameraListener): ImageAnalysis.Analyzer, AutoCloseable
InputTypeRequiredMeaning
sessionMatrixScanSessionYesBorrowed authorized native session; analyzer never closes it.
listenerMatrixScanCameraListenerYesWorker callbacks onResult(MatrixScanCameraResult) and onError(MatrixScanCameraError). Keep callbacks short; callback exceptions propagate after release.
Result
One typed snapshot per processed frame, no retained camera buffer. Every delivered ImageProxy is closed.
Lifecycle
YUV_420_888, KEEP_ONLY_LATEST, single worker. Concurrent/closed live calls are released without decoding. close stops new work; admitted work still delivers its worker callback/evidence. Host stops/unbinds, closes session on worker, then shuts down executor. Discard stale UI painting only.
Trust boundary
No logging or media persistence. Borrowed session keeps license checks; analyzer adds no Scandit dependency.
Failure behavior
  • INVALID_IMAGE, ENTITLEMENT_DENIED and PROCESSING_FAILED carry no raw exception/payload.
  • Native result statuses remain available in frame.result; no decode is a normal empty result.

MatrixScanCameraResult.mapVisibleTracks(previewTransform: OutputTransform): List<MatrixScanOverlay>

method

Map only current stable native quads to PreviewView pixels through CameraX CoordinateTransform.

Inputs for MatrixScanCameraResult.mapVisibleTracks(previewTransform: OutputTransform): List<MatrixScanOverlay>
InputTypeRequiredMeaning
previewTransformandroidx.camera.view.transform.OutputTransformYesNon-null PreviewView transform from the same ViewPort and camera binding as this frame.
Result
MatrixScanOverlay(track: MatrixTrack, quad: List<MatrixPoint>): original native track and four mapped preview-pixel points; original track.quad unchanged.
Lifecycle
Map/render on UI after preview layout. Discard previous-binding callbacks; do not rotate or crop mapped geometry twice. Raw frame timestamp is frame.timestampNs.
Trust boundary
Transforms do not infer payload, identity, target matching or count.
Failure behavior
  • Invalid/non-invertible/non-finite transform fails; never substitute guessed rectangles.
  • Wrong camera binding/ViewPort is caller misuse; clear overlays and rebind rather than painting stale geometry.

Licensed native MatrixScan usage reporting

PRXV-0132-S04: opt-in, content-free native acceptance/processing deltas to the existing tenant-authenticated ingestion API. Metrics schema: contracts/json/matrix-scan-usage.schema.json. Live staging delivery and analytics projections remain validation/downstream gates.

VisionScanSdk.startMatrixTelemetry(options: MatrixTelemetryOptions, tokenProvider: () -> String): MatrixScanTelemetry

method

Attach SDK-owned usage collection to subsequently created MatrixScan sessions, with independent bounded reporting work.

Inputs for VisionScanSdk.startMatrixTelemetry(options: MatrixTelemetryOptions, tokenProvider: () -> String): MatrixScanTelemetry
InputTypeRequiredMeaning
optionsMatrixTelemetryOptionsYesTrusted HTTPS control-plane origin, actual SDK version, bounded interval/capacity and optional encrypted host storage.
tokenProvider() -> StringYesWorker-only provider of the complete workspace device SDK key used for initialization; the existing enrolled bearer-token path is also supported. Never supply the signed license JWS.
Result
Lifecycle handle with typed status, queued/dropped/rejected counters, flushAsync, close, isStopped and awaitStopped.
Lifecycle
Verified UUID-device license first; reporting before native session creation. Close on logout/switch, then awaitStopped on a cleanup worker before reusing storage or restarting. One reporter/file writer.
Trust boundary
No tenant authority in request body; server checks claims and device licensing. No barcode value, image, quad, track ID, key/token or arbitrary diagnostic text. Opt-in, no redirects; five fixed mode buckets. Telemetry is not a billing or receiving authority.
Failure behavior
  • Invalid origin/version/bounds or missing verified UUID-device license rejects start.
  • Transport failure retains stable IDs; only matching per-event outcomes retire events.
  • Queue saturation delays new counters in fixed buckets; shutdown overflow and terminal rejections expose statistics losses, never receipt loss.
  • Corrupt/foreign encrypted spool stops delivery without overwriting it.