MÓDULO NATIVO
OCR
This documentation provides a detailed guide for developers on how to integrate and implement the
OCR SDK into their Android applications using Jetpack Compose. The SDK allows for the efficient and secure capture and processing of identification document data.Regresar
ANDROIDJETPACK COMPOSEv2.2.0
Compatibilidad y Requisitos
Lenguaje
Kotlin / Java
OS Min
Android 7+
API / Target
API 24+
IDE
Jellyfish+
1. Project Setup
Configure your project dependencies by adding the library to your Gradle files and version catalog.
libs.versions.toml
[versions]
dicioOcr = "2.2.0"
[libraries]
dicio-ocrsdk = { group = "io.bitbucket.juarezsdco", name = "ocrsdk", version.ref = "dicioOcr" }
build.gradle
dependencies {
implementation(libs.dicio.ocrsdk)
}
2. Basic Usage
The SDK is provided as a Jetpack Compose Composable named DicioCamera. You must invoke this Composable at the point in your UI where you want to display the scanning interface.
OcrScreen.kt
package com.tuapp.yourapp
import ai.dicio.ocrsdk.core.OcrCallback
import ai.dicio.ocrsdk.ui.models.settings.OcrResult
import ai.dicio.ocrsdk.ui.screens.camera.DicioCamera
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import kotlin.time.Duration.Companion.seconds
import android.util.Log
import org.json.JSONException
import org.json.JSONObject
// ... (Your logic to obtain the token
// For example, using State to handle the token
sealed class TokenState {
object Loading : TokenState()
data class Success(val token: String) : TokenState()
data class Error(val message: String) : TokenState()
}
@Composable
fun OcrScreen(tokenState: TokenState, modifier: Modifier = Modifier) {
// ... (Show loading screen, error, or the SDK depending on tokenState) ...
when(tokenState) {
TokenState.Loading -> { /* Show loading indicator */ }
is TokenState.Error -> { /* Show error message */ }
is TokenState.Success -> {
// When the token is ready, show the DicioCamera
DicioCameraIntegration(token = tokenState.token, modifier = modifier)
}
}
}
@Composable
fun DicioCameraIntegration(token: String, modifier: Modifier = Modifier) {
// You must provide your applicationId and your API base URL
val myApplicationId = "your.application.id" // Replace with your real Application ID
val myUrlBase = "https://your_url" // Replace with your real base URL
val ocrCallback = remember {
object : OcrCallback {
override fun onSuccess(result: OcrResult) {
// Successful scan. Process the received data.
Log.d("OCR_SDK", "Successful scan!")
Log.d("OCR_SDK", "Result Data: \${result.resultData}") // Extracted data in JSON format
Log.d("OCR_SDK", "Face Image B64 (first 50 chars): \${result.faceImageBase64.take(50)}...")
Log.d("OCR_SDK", "Front Image B64 (first 50 chars): \${result.frontImageBase64.take(50)}...")
Log.d("OCR_SDK", "Back Image B64 (first 50 chars): \${result.backImageBase64.take(50)}...")
// Here you can navigate and close the SDK screen and process the data
}
override fun onGuidanceMessage(message: String) {
// Guidance messages during scanning
Log.d("OCR_SDK", "Guidance message: $message")
// You can parse the "message" to get the code
val code = getCodeFromJsonString(message)
when (code) {
"UX_REQUEST_SIDE_BACK" -> Log.d("OCR_SDK", " -> Scanning the back side is requested.")
"UX_REQUEST_SIDE_FRONT" -> Log.d("OCR_SDK", " -> Scanning the front side is requested.")
// Handle other codes if necessary
}
}
override fun onFailure(error: String) {
// An error occurred that prevented the scan from completing
Log.e("OCR_SDK", "Scan error: $error")
// close or navigate away from the SDK screen and notify the user
}
override fun onCancel(message: String) {
// The scan was canceled (by the user or due to timeout)
Log.w("OCR_SDK", "Scan canceled: $message")
// close or navigate away from the SDK screen and notify the user
}
}
}
// Invoke the DicioCamera Composable
DicioCamera(
callback = ocrCallback,
applicationID = myApplicationId,
token = token, // The previously obtained token
urlBase = myUrlBase, // Your API base URL
seconds = 60, // Maximum time for the scan
)
}
// Helper function to extract the code from the JSON message
fun getCodeFromJsonString(jsonString: String): String? {
return try {
val jsonObject = JSONObject(jsonString)
if (jsonObject.has("Code")) {
jsonObject.getString("Code")
} else {
null
}
} catch (e: JSONException) {
e.printStackTrace()
null
}
}
DicioCamera Parameters
| Parameter | Type | Description | Required | Default Value |
|---|---|---|---|---|
callback | OcrCallback | Implementation of the OcrCallback interface to receive results, guidance messages, errors, and cancellations from the SDK. | Yes | None |
applicationID | String | Your application ID. Used internally by the SDK for license management. | Yes | None |
token | String | Authentication token. Used by the SDK to validate the session and get the license from your API. Must be a valid token. | Yes | None |
urlBase | String | Your API base URL where the SDK can validate the token and obtain the license configuration. | Yes | None |
seconds | Int | Maximum allowed duration for the scanning process. If exceeded, the SDK will automatically cancel with the TIMEOUT_CANCEL code. | No | 50 |
styledScreen | OcrStyled | Object that allows customizing the appearance of the SDK interface (colors, texts, logo). | No | OcrStyled() |
3. Result and Event Handling
You must implement the OcrCallback interface to receive SDK responses and events.
OcrCallback.kt
data class OcrResult(
val resultData: String,
val faceImageBase64: String,
val frontImageBase64: String,
val backImageBase64: String
)
interface OcrCallback {
// Called when the scan completes successfully and data is extracted
fun onSuccess(result: OcrResult)
// Called to provide guidance messages to the user during the scan
fun onGuidanceMessage(message: String) // JSON message with a code and description
// Called when an error occurs that prevents the scan from completing
fun onFailure(error: String) // Descriptive error message
// Called when the scanning process is canceled
fun onCancel(message: String) // Descriptive message of the cancellation (e.g. user, timeout)
}
Methods to implement
1. onSuccess:
- Description: Invoked when the OCR verification is successful.
- Parameters:
result:OcrResultobject containing theresultData(JSON) and the extracted images (faceImageBase64,frontImageBase64,backImageBase64).
2. onGuidanceMessage:
- Description: Invoked during the scanning process.
- Parameters:
message: UX events.
- Code table:
| Code | Description |
|---|---|
UX_REQUEST_SIDE_FRONT | The user is requested to scan the front side of the document. |
UX_REQUEST_SIDE_BACK | The user is requested to scan the back side of the document. |
DOCUMENT_NOT_FOUND | The document was not detected in the camera frame. |
UX_DOCUMENT_NOT_FULLY_VISIBLE | The document is not fully visible in the frame. |
UX_DOCUMENT_LOCATED | The document has been successfully detected and located in the frame. |
UX_DOCUMENT_TOO_FAR | The document is too far from the camera. |
UX_DOCUMENT_TOO_CLOSE | The document is too close to the camera. |
UX_TOO_CLOSE_TO_EDGE | The document is too close to the edge of the camera frame. |
UX_DOCUMENT_TOO_TILTED | The document is too tilted. |
UX_BLUR_DETECTED | Blur has been detected. The image is not sharp. |
UX_GLARE_DETECTED | Glare or reflection has been detected on the document. Avoid direct light. |
UX_WRONG_SIDE | An attempt is being made to scan the wrong side of the document. |
UX_SCANNING_DONE | The UX scanning process (visual capture) has finished. |
UX_UNKNOWN_EVENT | An unknown user interface event was received. |
3. onFailure:
- Description: Invoked when there is an error during the process.
- Parameter:
error: Descriptive error message in JSON format.
- Code table:
| Code | Description |
|---|---|
DOCUMEN_NOT_VALID | The scanned document is not valid. |
ERROR_PERMISSION | Camera permission denied. |
ERROR_SDK | Internal SDK error or invalid license. |
UNRECOVERABLE_ERROR | A critical unrecoverable error occurred. |
TOKEN_EMPTY | The token is empty or missing. |
NO_INTERNET | No internet connection. |
LICENCE_OR_TOKEN_ERROR | Invalid license or token. |
TOKEN_NOT_VALID | Invalid token. |
4. onCancel:
- Description: Invoked when the user cancels the verification.
- Parameter:
message: Message explaining why the process was canceled.
- Code table:
| Cancellation code | Description |
|---|---|
TIMEOUT_CANCEL | The session was canceled due to exceeding the allowed timeout (1 minute). |
USER_CANCEL | The user canceled the process. |
4. Interface Customization (Optional)
If you want to customize the appearance of the scanning screen (texts, colors, logo), you can do so by providing an OcrStyled object to the styledScreen parameter.
The OcrStyled object is a data class with the following fields:
OcrStyled.kt
val styledSdk = OcrStyled(
modalTitle = R.string.ocr_modal_title_instructions,
modalContent = R.string.ocr_modal_subtitle_instructions,
timeoutModalTitle = R.string.ocr_modal_timeout_title_instructions,
timeoutModalContent = R.string.ocr_modal_timeout_subtitle_instructions,
logo = R.drawable.logo,
titleColor = Color.Black,
contentColor = Color.Gray,
iconColor = Color.White,
scannerColor = Color.White,
timeoutModalButtonText = R.string.button_cancel,
backgroundColor = Color.White
)
Example of how to consume it:
Usage.kt
DicioCamera(
callback = sdkCallback,
applicationID = viewModel.aplicationId,
token = token,
urlBase = viewModel.urlBase,
seconds = viewModel.timeOut,
styledScreen = styledSdk
)