Android client integration

更新时间:
复制 MD 格式

This topic describes how to integrate Captcha into an Android client and provides API usage examples.

Integration steps

Download the SDK

Log on to the Phone Number Verification Service console. On the Overview page, find the API&SDK area on the right and click Download Now. On the API&SDK page, download and decompress the SDK as instructed.

Import the SDK

Drag the .aar file (including alicom_captcha_android_vx.y.z_date.aar) from the SDK package to the libs folder in your project. Verify that the .aar file is added to the Library, and then add the following code to the project's build.gradle file:

repositories {
        flatDir {
            dirs 'libs'
        }
  }

Add a dependency for the .aar package. By default, Android Archive (AAR) files do not pass on third-party dependencies. You must add them manually.

implementation(name: 'alicom_captcha_android_vx.y.z_date', ext: 'aar')

Configuration for non-Kotlin projects

Configure the root build.gradle file:

ext.kotlin_version = "1.4.10"
dependencies {
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}

Configure the module's build.gradle file:

apply plugin: 'kotlin-android'
dependencies {
      implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
Note

If a Kotlin version conflict occurs, remove the Kotlin dependency using exclude(group:'org.jetbrains.kotlin').

Add permissions

<!--Required - Requested by default-->
<uses-permission android:name="android.permission.INTERNET" />
<!--Required - Not requested by default-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--Optional - Dynamic request required for Android 6.0 or later (Stores logs to help analyze errors. Log path: /sdcard/Android/data/Your
PackageName/files/Alicom/captcha_log.txt)-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Obfuscation rules

The validation SDK is already obfuscated. Add the following rules to your obfuscation configuration. Do not obfuscate the SDK again.

-dontwarn com.geetest.gtcaptcha4.alicom.**
-keep class com.geetest.gtcaptcha4.alicom.**{*;}

If you use a resource obfuscation tool, add the following configuration to the whitelist:

"R.string.gt4_*",
"R.style.gt4_*",

Create a verification scheme

To use the SDK, you must obtain key parameters. Go to the Captcha Scheme Management console and create a new Captcha scheme to obtain the required appId and appKey parameters.

Configuration interface

Initialization

Initialize the SDK. Place the initialization code in the onCreate or onCreateView method.

public static AlicomCaptchaClient getClient(Context context);
public AlicomCaptchaClient init(String captchaId);
public AlicomCaptchaClient init(String captchaId, AlicomCaptchaConfig config)

Parameter

Type

Description

context

context

The context object. It must be an Activity instance.

appId

String

The verification ID. Pass the appId generated after you create a verification scheme in the console. This parameter is required.

config

AlicomCaptchaConfig

The parameter configuration object. This parameter is optional.

Note

The init() method starts preloading resources. For faster validation, call this method in the onCreate or onCreateView method to load the validation flow in advance. If you call `init()` only when validation is required, the loading process is slower than preloading.

Start validation

You can start the validation flow.

public void verifyWithCaptcha();

Cancel validation

You can cancel the validation flow and close the validation window.

public void cancel();

Enable or disable log monitoring

Call this method to enable or disable log printing for monitoring.

public void setLogEnable(boolean enable);

Get validation callbacks

public AlicomCaptchaClient addOnSuccessListener(OnSuccessListener listener);
public AlicomCaptchaClient addOnFailureListener(OnFailureListener listener);

Code example

AlicomCaptchaClient.addOnSuccessListener(new
AlicomCaptchaClient.OnSuccessListener() {
   @Override
   public void onSuccess(boolean status, String response) {
       if(status){
         // TODO: Enable secondary authentication.
       }else {
         // TODO: The user's answer is incorrect.
       }
   }
}).addOnFailureListener(new AlicomCaptchaClient.OnFailureListener() {
   @Override
   public void onFailure(String error) {
   }
})

Destroy resources

Destroy the resources in the onDestroy lifecycle method.

public void onDestroy(){
    super.onDestroy();
    if(AlicomCaptchaClient != null){
       AlicomCaptchaClient.destroy();
     }
}

Screen orientation change

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    if(AlicomCaptchaClient != null){
       AlicomCaptchaClient.configurationChanged(newConfig);
    }
}

Preloading code example

@Override
public void onViewCreated(View view, Bundle savedInstanceState){
   super.onViewCreated(view, savedInstanceState);
   AlicomCaptchaConfig config = new AlicomCaptchaConfig.Builder()
            .setDebug(true) // TODO: Make sure to disable this in production.
            .setLanguage("zh")
            .setTimeOut(10000)
            .setCanceledOnTouchOutside(true)
            .build();
   AlicomCaptchaClient = AlicomCaptchaClient.getClient(activity)
            .init("your captcha_id", config);
}

private void click(){
    AlicomCaptchaClient.addOnSuccessListener(new
AlicomCaptchaClient.OnSuccessListener {
             @Override
             public void onSuccess(boolean status, String response) {
                 if(status){
                     // TODO: Enable secondary authentication.
                 }else {
                    // TODO: The user's answer is incorrect.
                 }
             }
   })
   .addOnFailureListener(new AlicomCaptchaClient.OnFailureListener {
       @Override
       public void onFailure(String error) {
       }
   })
   .verifyWithCaptcha();
}

Normal loading code example

private void click(){
    AlicomCaptchaConfig config = new AlicomCaptchaConfig.Builder()
             .setDebug(true) // TODO: Make sure to disable this in production.
             .setLanguage("zh")
             .setTimeOut(10000)
             .setCanceledOnTouchOutside(true)
             .build();
   AlicomCaptchaClient = AlicomCaptchaClient.getClient(activity)
             .init("your captcha_id", config)
             .addOnSuccessListener(new AlicomCaptchaClient.OnSuccessListener {
                 @Override
                 public void onSuccess(boolean status, String response) {
                    if(status){
                        // TODO: Enable secondary authentication.
                    }else {
                        // TODO: The user's answer is incorrect.
                    }
              }
   })
   .addOnFailureListener(new AlicomCaptchaClient.OnFailureListener {
                 @Override
                 public void onFailure(String error) {
                 }
   })
   .verifyWithCaptcha();
}

Parameter settings

You can configure parameters using the AlicomCaptchaConfig.Builder class.

Definition

Description

setParams

Extra parameters that are passed to the frontend JavaScript for use.

setDebug

Specifies whether to enable debug mode. Default: false.

setLanguage

Specifies the language. By default, it follows the application language. For supported languages and their short codes, see Multi-language short codes.

setCanceledOnTouchOutside

Specifies whether to dismiss the dialog box when a user touches outside of it. Default: true.

setTimeOut

Sets the timeout period in ms. Default: 10000 ms.

setResourcePath

Sets the intermediate address. By default, the local HTML file is loaded.

setBackgroundColor

Sets the background color. Default: transparent.

setDialogStyle

Sets the theme style of the dialog box. Default: gt4_captcha_dialog_style.

setDialogShowListener

Sets the listener callback for when the validation window is displayed.

build

Builds the AlicomCaptchaConfig object.

Note
  • You can use the setParams API to configure parameters. This API accepts only basic data types, strings, and JSONArray data types.

  • Unexpected errors can occur during validation. Implement the addOnFailureListener and handle any errors in the callback method. The error callback is also triggered when a user cancels the validation. You can filter out this scenario.

  • When you display a validation error to a user, also display the error code. This helps troubleshoot issues in a production environment. For more information about error codes, see Error codes.

    AlicomCaptchaClient.addOnFailureListener(new
    AlicomCaptchaClient.OnFailureListener() {
       @Override
       public void onFailure(String error){
           // Sample error content returned
           // {"code":"-14460","msg":"Validation session canceled","desc":{"description":"User
     cancelled 'Captcha'"}}
           // You can parse the error as JSON, replace the error description, and keep the error code.
           Toast.makeText(context, "Validation error: $error", Toast.LENGTH_SHORT).show()
    }