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
minSdkVersionset to 15 or laterThe 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.
| Permission | Required | Description |
|---|---|---|
android.permission.INTERNET | Yes | Access networks. Without this permission, core SDK features are unavailable. |
android.permission.ACCESS_NETWORK_STATE | Recommended | Read the device's network status. |
android.permission.READ_PHONE_STATE | Recommended | On Android 6.0 and later, grant this permission dynamically before calling the data collection function. |
android.permission.WRITE_EXTERNAL_STORAGE | Recommended | |
android.permission.READ_EXTERNAL_STORAGE | Recommended |
Download and configure the SDK
Download the Android SDK package and decompress it. The package is a standard
.aar(Android Archive) file.Copy the
.aarfile to thelibsdirectory of your project.Add the following dependencies to your app's
build.gradlefile:// 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'ImportantAdd 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.
| Parameter | Description | Example |
|---|---|---|
IPv6 | IP version for reporting device information. 0 (default): IPv4. 1: IPv6. | "1" |
CustomUrl | Domain name of your self-managed server to receive data. | "https://cloudauth-device.aliyuncs.com" |
CustomHost | Host of your self-managed server to receive data. | "cloudauth-device.aliyuncs.com" |
DataType | Types 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:
| Value | Data excluded | Affected fields |
|---|---|---|
NO_UNIQUE_DEVICE_DATA | Resettable device identifiers | Open Anonymous Device Identifier (OAID), Google advertising ID, Android ID |
NO_IDENTIFY_DEVICE_DATA | Non-resettable device identifiers | International Mobile Equipment Identity (IMEI), International Mobile Subscriber Identity (IMSI), SimSerial, BuildSerial (SN), MAC address |
NO_BASIC_DEVICE_DATA | Basic device information | Device name (Build.DEVICE), Android version (Build.VERSION#RELEASE), screen resolution |
NO_EXTRA_DEVICE_DATA | Extended sensitive information | App 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.
Call
getDevicetokenfrom a background thread. Calling it on the main thread causes ANR (application not responding) errors.Wait at least 2 seconds after
initWithOptionsbefore callinggetDevicetoken.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
SecurityCode | Code | Description |
|---|---|---|
SC_SUCCESS | 10000 | Data collection succeeded. |
SC_NOT_INIT | 10001 | Data collection failed. |
SC_NOT_PERMISSION | 10002 | One or more required Android permissions are not granted. |
SC_UNKNOWN_ERROR | 10003 | An unknown system error occurred. |
SC_NETWORK_ERROR | 10004 | A network error occurred. |
SC_NETWORK_ERROR_EMPTY | 10005 | A network error occurred, and the return value is an empty string. |
SC_NETWORK_ERROR_INVALID | 10006 | The response format is invalid. |
SC_PARSE_SRV_CFG_ERROR | 10007 | Failed to parse server-side settings. |
SC_NETWORK_RET_CODE_ERROR | 10008 | The gateway returned an error. |
SC_APPKEY_EMPTY | 10009 | The appKey parameter is empty. |
SC_PARAMS_ERROR | 10010 | A parameter error occurred. |
SC_FGKEY_ERROR | 10011 | Failed to calculate the key. |
SC_APPKEY_ERROR | 10012 | The 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.