DocumentDetector v8.x or above

Current Version

The following versions have been used since version 9.0.0:

  • Kotlin from 1.5.32 to 1.9.10

  • AGP: from 4.1.0 to 8.3.2

  • Gradle: from 6.9.1 to 8.4

NameVersion

DocumentDetector

9.1.2

Requirements

  • Minimum Android SDK API version: minSdk 26 (Android 8 Oreo)

  • Android SDK API version to compile: compileSdk 34

Runtime permissions

PermissionReasonRequired?

CAMERA

To capture photos of the documents.

Only for capture feature.

READ_EXTERNAL_STORAGE

To access the device external storage and select documents in the upload flow.

Only for upload feature.

SDK size

The SDK size is approximately 3.3 MB, which may decrease due to these elements.

Installation

If your version of Gradle is earlier than 7, add these lines to your build.gradle.

allprojects {
  repositories {
  ...
  maven { url 'https://repo.combateafraude.com/android/release' }
  maven { url 'https://jitpack.io' }

}}

If your version of Gradle is 7 or newer, add these lines to your settings.gradle.

dependencyResolutionManagement {
    repositories {
        ...
        maven { url 'https://repo.combateafraude.com/android/release' }
        maven { url 'https://jitpack.io' }
    }
}

Add support for Java 8 (skip this code if Java 8 is enabled), Data Binding and TensorFlow Model to your build.gradle file.

android {
    ...
    // Enable Data Binding, depending on the version of com.android.tools.build:gradle
    // If com.android.tools.build:gradle >= 4
    buildFeatures {
        dataBinding = true
    }
    // If com.android.tools.build:gradle < 4
    dataBinding.enabled = true

    // Java 1.8 compatibility, allowing lambda functions
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }

    aaptOptions {
        noCompress "tflite"
    }
}

As our SDKs activities use Data Binding, it is required that you enable this setting within your app. The compileOptions setting is required for SDK's built-in lambda functions, which were released in Java 8. The noCompress setting tells the compiler not to compress files with the .tflite extension used in the DocumentDetector.

Add the SDK version to the dependencies section in your build.gradle file

dependencies {
    implementation 'com.combateafraude.sdk:document-detector:{version}'
}

Supported documents

Currently, supported documents are:

public enum Document {
    RG_FRONT, // front of RG (where the photo is located)
    RG_BACK, // back of RG
    RG_FULL, // RG opened (showing front and back together)
    CNH_FRONT, // front of CNH (where the photo is located)
    CNH_BACK, // back of CNH 
    CNH_FULL, // CNH opened (showing front and back together)
    CRLV, // CRLV
    RNE_FRONT, // front of RNE or RNM
    RNE_BACK, // back of RNE or RNM
    PASSPORT, // passport (showing the photo and data)
    CTPS_FRONT, // front of CTPS (where the photo is located)
    CTPS_BACK, // back of CTPS
    ANY; // allows you to send any type of document, all those mentioned above, including any other document, as there are no typifications
}

Instantiating the SDK

First things first, instantiate an object of type DocumentDetector. This object will contain all your business rules for the SDK:

DocumentDetector mDocumentDetector = new DocumentDetector.Builder(String mobileToken)
    // see table below
    .build();

All parameters annotated with @Nullable can receive null values, useful if you want to configure only one of the parameters of the same method.

Builder method

ParameterRequired

String mobileToken

Token associated with your account, to use the SDK.

Yes.

.setDocumentCaptureFlow(@NonNull DocumentDetectorStep[] documentSteps)

Defines the document capture flow as explained here.

Yes.

.setPersonId(@Nullable String personId)

User identifier for fraud profile identification purposes and to assist in the identification of Analytics logs in cases of bugs and errors.

No.

.setCaptureStages(@NonNull CaptureStage[] captureStages)

Configures the requirements for each capture stage. Designed to make capture more flexible in cases where the user is unable to capture with all checks active, preventing them from getting stuck at this stage in their registration flow. Configure it as you prefer by following this example.

No.

.setPopupSettings(boolean show)

Enables/disables the popups displayed before each document capture.

No. The default value is true.

.setLayout(@LayoutRes Integer layoutId)

Overrides the default SDK layout. Create a file in the layout folder of your project, copy this template and make the changes you want.

No.

.setStyle(@StyleRes int styleResourceId)

Set up a new style guideline for the SDK. Create a styles.xml file in your project with this template and customize it.

No.

.setNetworkSettings(int requestTimeout)

Defines SDK's requests timeout.

No. The default value is 60 (seconds).

.setLuminositySensorSettings(@Nullable SensorLuminositySettings sensorLuminositySettings)

Defines threshold between acceptable/unacceptable ambient brightness. Set null if you don't want to use this sensor.

No. The default settings are 5 (lx).

.setOrientationSensorSettings(@Nullable SensorOrientationSettings sensorOrientationSettings)

Defines threshold between correct/incorrect device orientation. Higher the value more flexible it will be. Set null if you don't want to use this sensor.

No. The default setting is 3 (m/sยฒ).

.setStabilitySensorSettings(@Nullable SensorStabilitySettings sensorStabilitySettings)

Defines stability sensor settings. Set null if you don't want to use this sensor.

No. The default setting is time 2000 (ms) and threshold 0.5 (m/sยฒ).

.setProxySettings(ProxySettings proxySettings)

Defines proxy settings. Follow this guide.

No. The default setting is null.

.setPreviewSettings(@NonNull PreviewSettings previewSettings)

Enables/disables and allows the configuration of the visualization of the capture performed, requesting the user's confirmation to proceed.

No. The default is disabled.

.setCurrentStepDoneDelay(boolean showDelay, int delay)

Delays the activity after the completion of each step. This method can be used to display a success message on the screen itself after the capture, for example.

No. The default is false.

.setMessageSettings(MessageSettings messageSettings)

Allows customizing messages displayed in the feedback label during the capture and analysis process. See the available attributes here.

No.

.setResolutionSettings(@NonNull Resolution resolution)

Allows you to set the capture resolution. The method takes as parameter a Resolution that has the following options:

  • FULL_HD (1920 x 1080)

  • QUAD_HD (2560 x 1440)

  • ULTRA_HD (3840 x 2160)

No. The default is FULL_HD.

.setCompressSettings(@IntRange(from = 80, to = 100) int compressQuality)

Allows you to configure the quality in the compression process. By default, all captures go through compression. The method expects values between 80 and 100 as a parameter, where 100 is the best quality compression.

No. The default is 90.

.enableGoogleServices(boolean enable)

Allows you to enable/disable features of the SDK that consume GoogleServices in the SDK, we do not recommend disabling the services because of the loss of security.

No. The default is true.

.setUseDeveloperMode(boolean use)

Enables the use of developer mode when true. It is not recommended to enable this option, use it only for testing purposes.

No. The default is false.

.setUseAdb(boolean use)

Enables Android Debug Bridge (ADB) debugging mode when true. It is not recommended to enable this option, use it only for testing purposes.

No. The default is false.

.setUseDebug(boolean use)

Allows you to use the app in debug mode when true. It is not recommended to enable this option, use it only for testing purposes.

No. The default is false.

.setGetImageUrlExpireTime(String expireTime)

Sets the time the image URL will last on the server until it is expired. Expect to receive a time interval between "30m" to "30d".

Examples:

  • "30m": To set minutes only

  • "24h": To set only hour(s)

  • "1h 10m": To set hour(s) and minute(s)

  • "10d": To set day(s)

No. The default is 3h.

.setUploadSettings(UploadSettings uploadSettings)

Sets the settings for uploading documents. By enabling this option, the SDK flow will prompt the user to upload the document files instead of capturing them with the device's camera. This option also includes document type and quality checks. See how to set it here.

No. By default this option is disabled.

.setAllowedPassportCountriesList(CountryCodeList[] countryList)

Enables the option to allow passports from only a certain issuing country, or, a list of countries. See the complete list at: ISO 3166-1 alpha-3.

Example:

  • .setAllowedPassportCountriesList(new CountryCodesList[]{CountryCodesList.BRA})

No. Passports issued by any country are accepted by default.

DocumentDetectorStep

To create a capture flow, you will need to create an array of DocumentDetectorStep, where each element will be a capture step. To construct each DocumentDetectorStep object, you can enter the following elements:

DocumentDetectorStep detectorStep = new DocumentDetectorStep(Document.RG_FRONT);
ParameterRequired?

Document document

Identifies which document you want to capture in the respective step. See supported document types here.

Yes.

.setStepLabel(@StringRes int stepLabel)

Defines text to be shown in the lower part of the layout.

No. There is a pattern by Document type.

.setIllustration(@DrawableRes int illustration)

Defines illustration to be shown in the popup prior to capture.

No. There is a pattern by Document type.

.showStepLabel(boolean showStepLabel)

Present the text to be displayed at the top of the layout

No. the default is true.

CaptureStage

To improve the client's UX, we recommend creating difficulty stages for the DocumentDetector. For this, we offer the CaptureStage object, where you can set the following parameters:

Parameter

CaptureMode captureMode

Document capture mode, which can be CaptureMode.AUTOMATIC or CaptureMode.MANUAL. In manual capture, a button will be enabled for the user to perform the capture.

Long durationMillis

Duration of the stage, in milliseconds. If you do not want a timeout, parameterize null.

boolean wantSensorCheck

Enables/Disables the use of sensors for capturing the photo.

Since the .setCaptureStages parameter is not required, if it is not used, the DocumentDetector will use this default:

new CaptureStage[]{
    new CaptureStage(CaptureMode.AUTOMATIC, 30000L, true),
    new CaptureStage(CaptureMode.AUTOMATIC, 15000L, false),
    new CaptureStage(CaptureMode.MANUAL, null, false)
}

UploadSettings

To enable the document upload functionality it is necessary to instantiate an object of type UploadSettings(boolean enable) and set its parameters:

ParameterRequired?

.setEnable(Boolean enable)

Enables/disables this feature.

No. The default is true.

.setCompress(Boolean enable)

Enables/disables file compression before uploading.

No. The default is true.

.setFileFormats(FileFormat[] fileFormats)

Defines the file format(s) that will be accepted for upload.

No. By default .PDF, .JPG, .JPEG, .PNG, .HEIF are accepted.

.setMaxFileSize(Integer maxFileSize)

Sets the maximum KB limit of the file to upload.

No. The default limit is 10000 KB (10MB).

.setActivityLayout(Integer activityLayout)

Defines the background layout of the document upload.

No.

.setPopUpLayout(Integer popUpLayout)

Defines the layout of the document upload request popup.

No.

Currently, the supported file formats are:

public enum FileFormat {
    PNG("image/png"),
    JPG ("image/jpg"),
    JPEG ("image/jpeg"),
    PDF("application/pdf"),
    HEIF("image/heif");
}

MessageSettings

To use, simply instantiate a MessageSettings object and use the methods as needed for customization.

MethodDefault value

.setPopupDocumentSubtitleMessage(@NonNull @StringRes Integer message)

Message displayed in the subtitle of the pop-up that brings the illustration of the document that is being requested for capture.

โ€œDispose the document in a desk, centralize it on the markup and hold the automatic capture.โ€

.setFitTheDocumentMessage(Integer message)

Message telling you to fit the document to the mask.

"Fit the document on the markup"

.setHoldItMessage(Integer message)

Message displayed at the moment the capture is being performed.

"Keep it that way"

.setVerifyingQualityMessage(Integer message)

Message displayed when the SDK makes a request to the backend, checking for quality.

"Checking document..."

.setLowQualityDocumentMessage(Integer message)

Message displayed when the capture quality fails.

"Ops, could not read the information. Please try again."

.setUploadingImageMessage(Integer message)

Message displayed when there is no quality check and the capture is being saved on the servers.

"Sending image..."

.setShowOpenDocumentErrorMessage(boolean show, @Nullable Integer message)

Message displayed when displaying an open document, the message will be displayed together with the error message on the document being used, example: if the user displays an open CNH(Brazilian driveโ€™s license), the standard error message "Essa รฉ uma CNH Aberta" + the defined message will be displayed.

"Close your document and try again"

.setWaitMessage(boolean show, @Nullable Integer message)

Message displayed when you start the camera.

"Please wait..."

.setSensorLuminosityMessage(@NonNull @StringRes Integer message)

Message displayed when the brightness threshold is lower than expected.

"Area near you is too dark"

.setSensorOrientationMessage(@NonNull @StringRes Integer message)

Message displayed when the orientation threshold is lower than expected.

"Point the camera down"

.setSensorStabilityMessage(@NonNull @StringRes Integer message)

Message displayed when the orientation threshold is lower than expected.

"Keep the device still"

.setWrongDocumentTypeMessageResourceId(Integer message)

Message displayed when the document is displayed in a different stream than expected.

"%1$s" is optional if you want to add de expected document in your message

"Ops, this document is not %1$s"

.setPositiveButtonMessage(Integer message)

Allows for customization of the confirmation button message.

"OK, understood"

.setUploadedImageIsTooLargeTitle

Sets the title of the upload popup when the uploaded file exceeds the maximum allowed size.

"File size exceeded"

.setUploadedImageIsTooLargeMessage

Sets the upload popup message when the uploaded file exceeds the maximum allowed size. The variable %1$s has the max file size.

"It looks like the file you chose exceeds the maximum permitted. Try to upload a smaller file with a maximum size of %1$d MB."

.setUploadedImageHasInvalidFormatTitle

Sets the title of the upload popup when the format of the uploaded file is not valid.

"Invalid format."

.setUploadedImageNotSupportedFormatMessage

Sets the upload popup message when the format of the uploaded file is not valid.

"It looks like the file's format is not supported. Try uploading a new file in JPG, PNG or PDF format."

.setUploadedImageGenericErrorTitle

Sets the generic error title for the upload popup.

"Ops, something went wrong."

.setUploadedImageWrongMessage

Sets the generic error message for the upload popup.

"It looks like this isn't the expected document. Upload a photo of the requested document type."

.setUploadedImageLowQualityTitle

Sets the title of the upload popup when the quality of the uploaded image fails.

"Ops, low quality picture"

.setUploadedImageLowQualityMessage

Sets the upload popup message when the quality of the uploaded image fails.

"The document's quality appears to be very low. Try uploading a better quality picture."

.setUploadPopupLoadingMessage

Sets the message displayed in the upload popup while the file is being uploaded.

"Sending your document"

.setPredictorScanDocumentMessage(@NonNull @StringRes Integer resId)

Message displayed to request a document to be present on the camera.

"Scan a document"

.setPredictorGetCloserMessage(@NonNull @StringRes Integer resId)

Message displayed to request to get closer to the document.

"Move the document closer"

.setPredictorCentralizeMessage(@NonNull @StringRes Integer resId)

Message displayed to request to center the document.

"Center the document"

.setPredictorMoveAwayMessage(@NonNull @StringRes Integer resId)

Message displayed to request to move away from the document.

"Move away from the document"

.setPredictorAlignDocumentMessage(@NonNull @StringRes Integer resId)

Message displayed to request to align the document.

"Align the document"

.setPredictorTurnDocumentMessage(@NonNull @StringRes Integer resId)

Message displayed to request to turn document 90 degrees.

"Turn the document โคต๏ธ"

.setPredictorCapturedMessage(@NonNull @StringRes Integer resId)

Message displayed to alert that the document was captured.

"Document captured"

.setUnsupportedDocumentMessage(@NonNull @StringRes Integer message)

Message displayed to alert that the document was not supported.

"Ops, it seems that this document is not supported."

.setDocumentNotFoundMessage(@NonNull @StringRes Integer message)

Message displayed to alert that the document was not found.

"Didn't found a document."

Example

MessageSettings messageSettings = new MessageSetings()
    .setFitTheDocumentMessage(R.string.exempleFit)
    .setHoldItMessage(R.string.exempleHoldIt);

Security validations

We are constantly taking actions to make the product more and more secure, mitigating a number of attacks observed in the capture process and, consequently, reducing as many possible identity frauds as possible. The SDK has some blocks that may prevent its execution in certain contexts. To disable them, you can use the methods as shown in the example below:

DocumentDetector.Builder("mobileToken")
    .setUseDeveloperMode(true)
    .setUseAdb(true)
    .setUseDebug(true)
    .build();

Disabling security validations is recommended for testing purposes only. For publishing your application in production, we recommend using the default settings.

Starting Activity

After creating the DocumentDetector, start the DocumentDetectorActivity by passing this object as a parameter via extra intent:

Intent mIntent = new Intent(context, DocumentDetectorActivity.class);
mIntent.putExtra(DocumentDetector.PARAMETER_NAME, mDocumentDetector);
startActivityForResult(mIntent, REQUEST_CODE);

Getting the result

To get the DocumentDetectorResult object, which contains the captures taken by the SDK, override the onActivityResult method in the same Activity that you started the DocumentDetectorActivity:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE){
        if (resultCode == RESULT_OK && data != null){
            DocumentDetectorResult mDocumentDetectorResult = (DocumentDetectorResult) data.getSerializableExtra(DocumentDetectorResult.PARAMETER_NAME);
            // check mDocumentDetectorResult.getSDKFailure() to find out why the SDK was terminated
        } else {
            // the user closed the activity
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}

DocumentDetectorResult

ParameterAllow null

Capture[] captures

The array with the respective captures of the parameterized documents.

Yes, in case of error

String type

The class of the read document stream. This parameter is useful in an integration with our OCR route. The existing types are: ["blank", "cnh", "cnh_new", "generic", "rg", "rg_new", "rne", "rnm", "ctps", "passport", "crlv", "crlv_new", "cin"].

Yes, in case of error.

String trackingId

Identifier of this execution on our servers. If possible, save this field and send it along to our API. This way we will have more data on how the user behaved during the execution.

No

SDKFailure sdkFailure

Object that tells you the reason for the SDK shutdown. For more information, see here.

Yes, in case of success.

Capture

ParameterCan it be null?

String imagePath

Full path of the image on the user's device.

No.

String imageUrl

URL of the document on the Caf's server. This URL has an expiry time, which can be set with the setGetImageUrlExpireTime method.

No.

String label

Label of the respective document within the following possibilities: ["blank", "cnh_back", "cnh_front", "cnh_full", "new_cnh_back", "new_cnh_front", "new_cnh_full", "crlv", "crlv_new", "generic", "rg_back", "rg_front", "rg_full", "rg_new_back", "rg_new_front", "rg_new_full", "rne_back", "rne_front", "rnm_back", "rnm_front", "ctps_back", "ctps_front", "passport", "cin_front", "cin_back"].

No.

Double quality

Quality inferred by the document quality algorithm. Varies between 0 and 5.

No.

Last updated

Logo

2023 ยฉ Caf. - All rights reserved