All Products
Search
Document Center

Fraud Detection:Integrate the Fraud Detection SDK for Android

Last Updated:Mar 31, 2026

Integrate the Device Fraud Detection SDK into your Android app to collect device signals and retrieve a device token for server-side risk assessment.

Prerequisites

Before you begin, ensure that you have:

  • An Android app targeting Android 4.0.3 or later, with minSdkVersion set to 15 or later

  • The latest SDK version published on Alibaba Cloud's official website (required for privacy compliance)

  • Read the Fraud Detection SDK Privacy Policy and the relevant rules for processing personal information

Permissions

The SDK requires one mandatory permission and benefits from several optional ones. Grant optional permissions before SDK initialization to improve detection accuracy.

PermissionRequiredDescription
android.permission.INTERNETYesAccess networks. Without this permission, core SDK features are unavailable.
android.permission.ACCESS_NETWORK_STATERecommendedRead the device's network status.
android.permission.READ_PHONE_STATERecommendedOn Android 6.0 and later, grant this permission dynamically before calling the data collection function.
android.permission.WRITE_EXTERNAL_STORAGERecommended
android.permission.READ_EXTERNAL_STORAGERecommended

Download and configure the SDK

  1. Download the Android SDK package and decompress it. The package is a standard .aar (Android Archive) file.

  2. Copy the .aar file to the libs directory of your project.

  3. Add the following dependencies to your app's build.gradle file:

    // Device Fraud Detection SDK
    implementation files('libs/Android-AliyunDevice-<version>.aar')
    
    // Required network library dependencies
    implementation 'com.squareup.okhttp3:okhttp:3.11.0'
    implementation 'com.squareup.okio:okio:1.14.0'
    Important

    Add the network library dependencies. Without them, the SDK cannot connect to the internet.

Collect data

Call initWithOptions as early as possible in your app lifecycle — ideally in Application.onCreate() — after obtaining user privacy consent. The SDK uses the collected device signals to generate a device token.

Call this function at risk-sensitive entry points such as account registration, login, and promotional event access, where device-level fraud signals are most relevant.

Function signature

public interface SecurityInitListener {
    // code: status code indicating whether data collection succeeded
    void onInitFinish(int code);
}

public void initWithOptions(
    Context ctx,
    String appKey,
    Map<String, String> options,
    SecurityInitListener securityInitListener
);

Parameters

`ctx`

Application Context or Activity Context.

`appKey`

Your app identity key. Get this value from the Device APP management tab in the Fraud Detection console.

`options`

Optional configuration for data collection. Pass null to collect all data with default settings.

ParameterDescriptionExample
IPv6IP version for reporting device information. 0 (default): IPv4. 1: IPv6."1"
CustomUrlDomain name of your self-managed server to receive data."https://cloudauth-device.aliyuncs.com"
CustomHostHost of your self-managed server to receive data."cloudauth-device.aliyuncs.com"
DataTypeTypes of sensitive data to exclude from collection. Empty by default (all data collected). Separate multiple values with |."NO_UNIQUE_DEVICE_DATA" or "NO_UNIQUE_DEVICE_DATA|NO_IDENTIFY_DEVICE_DATA"

The DataType parameter accepts the following values:

ValueData excludedAffected fields
NO_UNIQUE_DEVICE_DATAResettable device identifiersOpen Anonymous Device Identifier (OAID), Google advertising ID, Android ID
NO_IDENTIFY_DEVICE_DATANon-resettable device identifiersInternational Mobile Equipment Identity (IMEI), International Mobile Subscriber Identity (IMSI), SimSerial, BuildSerial (SN), MAC address
NO_BASIC_DEVICE_DATABasic device informationDevice name (Build.DEVICE), Android version (Build.VERSION#RELEASE), screen resolution
NO_EXTRA_DEVICE_DATAExtended sensitive informationApp list for illicit trading, LAN IP addresses, DNS IP addresses, connected Wi-Fi (SSID, BSSID), nearby Wi-Fi list, location

`securityInitListener`

Callback invoked when data collection completes. Use the code parameter to check the result. See Status codes for details.

Return value: None.

Get the device token

After calling initWithOptions, wait at least 2 seconds, then call getDevicetoken from a background thread to retrieve the device token. Send the token to your application server, which uses it to query device risk information from the Device Fraud Detection API.

Important
  • Call getDevicetoken from a background thread. Calling it on the main thread causes ANR (application not responding) errors.

  • Wait at least 2 seconds after initWithOptions before calling getDevicetoken.

  • Token length is approximately 600 bytes on a good network connection and up to 2.5 KB on a poor connection.

Function signature

public class Securitytoken {
    // Status code indicating whether the token was retrieved successfully
    public int code;

    // Token string used to query risk results on the server side
    public String token;
}

public Securitytoken getDevicetoken();

Return values

getDevicetoken returns a Securitytoken object with two fields:

  • code: status code indicating whether the operation succeeded. See Status codes for details.

  • token: token string used to call the Device Fraud Detection API. The token is valid for 7 days and can be reused across multiple server-side API calls.

Sample code

The following example shows a complete integration: initializing data collection in Application.onCreate() and retrieving the device token in a background thread when a risk-sensitive event occurs, such as user registration or a promotional activity.

Java

public class CustomApplication extends Application {
    // Get your appKey from the Device APP management tab in the Fraud Detection console
    private static final String ALIYUN_APPKEY = "xxxx";

    @Override
    public void onCreate() {
        super.onCreate();

        // Exclude non-resettable device identifiers to meet privacy requirements.
        // Separate multiple DataType values with |.
        Map<String, String> options = new HashMap<>();
        options.put("DataType", "NO_IDENTIFY_DEVICE_DATA");

        // Call initWithOptions as early as possible after privacy consent is obtained.
        SecurityDevice.getInstance().initWithOptions(this, ALIYUN_APPKEY, options, null);
    }
}

After the app initializes, retrieve the device token in a background thread when a risk-sensitive event occurs. Wait at least 2 seconds after initWithOptions before calling getDevicetoken.

new Thread() {
    @Override
    public void run() {
        Securitytoken st = SecurityDevice.getInstance().getDevicetoken();
        if (st != null) {
            if (SecurityCode.SC_SUCCESS == st.code) {
                Log.d("AliyunDevice", "token: " + st.token);

                // Send the token to your application server.
                // Your server uses this token to call the Device Fraud Detection API.
                // sendToAppServer(st.token);
            } else {
                Log.e("AliyunDevice", "getDevicetoken error, code: " + st.code);
            }
        } else {
            Log.e("AliyunDevice", "getDevicetoken returned null.");
        }
    }
}.start();

Kotlin

class CustomApplication : Application() {
    // Get your appKey from the Device APP management tab in the Fraud Detection console
    private val ALIYUN_APPKEY = "xxxx"

    override fun onCreate() {
        super.onCreate()

        // Exclude non-resettable device identifiers to meet privacy requirements.
        val options = HashMap<String, String>()
        options["DataType"] = "NO_IDENTIFY_DEVICE_DATA"

        // Call initWithOptions as early as possible after privacy consent is obtained.
        SecurityDevice.getInstance().initWithOptions(this, ALIYUN_APPKEY, options, null)
    }
}

Retrieve the device token in a background thread using a coroutine dispatcher. Wait at least 2 seconds after initWithOptions before calling getDevicetoken.

// Use Dispatchers.IO to avoid blocking the main thread (prevents ANR errors)
CoroutineScope(Dispatchers.IO).launch {
    val st = SecurityDevice.getInstance().getDevicetoken()
    if (st != null) {
        if (SecurityCode.SC_SUCCESS == st.code) {
            Log.d("AliyunDevice", "token: ${st.token}")

            // Send the token to your application server.
            // Your server uses this token to call the Device Fraud Detection API.
            // sendToAppServer(st.token)
        } else {
            Log.e("AliyunDevice", "getDevicetoken error, code: ${st.code}")
        }
    } else {
        Log.e("AliyunDevice", "getDevicetoken returned null.")
    }
}

Obfuscation

Add the following rules to your ProGuard configuration to prevent the SDK from being obfuscated:

-keep class net.security.device.api.** {*;}
-dontwarn net.security.device.api.**

Status codes

SecurityCodeCodeDescription
SC_SUCCESS10000Data collection succeeded.
SC_NOT_INIT10001Data collection failed.
SC_NOT_PERMISSION10002One or more required Android permissions are not granted.
SC_UNKNOWN_ERROR10003An unknown system error occurred.
SC_NETWORK_ERROR10004A network error occurred.
SC_NETWORK_ERROR_EMPTY10005A network error occurred, and the return value is an empty string.
SC_NETWORK_ERROR_INVALID10006The response format is invalid.
SC_PARSE_SRV_CFG_ERROR10007Failed to parse server-side settings.
SC_NETWORK_RET_CODE_ERROR10008The gateway returned an error.
SC_APPKEY_EMPTY10009The appKey parameter is empty.
SC_PARAMS_ERROR10010A parameter error occurred.
SC_FGKEY_ERROR10011Failed to calculate the key.
SC_APPKEY_ERROR10012The SDK version does not match the appKey version.

Call the Device Fraud Detection API

After your server receives the device token, use it along with other event parameters to call the Device Fraud Detection API and retrieve the device risk result.

For the full list of request and response parameters, see Service event parameters and response parameters for Device Fraud Detection.

FAQ

Which CPU architectures does the SDK support?

The SDK supports ARM, ARMv7, and ARM64 architectures.

How large is the SDK package?

A mono-architecture Shared Object (SO) file is approximately 1.8 MB. The package is large because it includes obfuscation, dilation, and cryptographic operations to prevent reverse engineering and secure data in transit.

How long is a device token valid? Can I reuse it?

A device token is valid for 7 days. You can use the same token for multiple server-side API calls within that period.