Integrate the Device Fraud Detection SDK into your Android app to collect device fingerprints, generate device tokens, and use them on your server to detect fraudulent activity.
Prerequisites
Emulators in debugger mode are not supported.
Before you integrate the SDK, ensure that your app meets the following requirements:
Android 4.0.3 or later (minSdkVersion 15 or later).
Mobile smart devices (phones or tablets) running Android 4.4 or later.
arm, armv7, or arm64 architecture.
For SDK architecture support and package size details, see FAQ.
Permissions
The SDK requires the following permissions to detect device fraud:
Permission | Required | Description |
android.permission.INTERNET | Yes | Allows the SDK to access the internet. |
android.permission.ACCESS_NETWORK_STATE | Yes | Used to obtain the device network status. |
android.permission.READ_PHONE_STATE | No (recommended) | On Android 6.0 and later, these permissions must be requested dynamically at runtime. Note If you want to enable these permissions, ensure that your app has been granted them before integrating the SDK and calling the |
android.permission.WRITE_EXTERNAL_STORAGE | No (recommended) | |
android.permission.READ_EXTERNAL_STORAGE | No (recommended) |
Download and configure the SDK
Download and extract the Android SDK. The SDK is distributed as a standard .aar package.
NoteA single-architecture SO file is approximately 2 MB.
The SDK uses obfuscation, packing, and encryption to prevent reverse engineering and secure data in transit, which contributes to the larger package size.
Copy the extracted .aar file to the
libsdirectory of your project and add the following dependencies to your app'sbuild.gradlefile:// Device Fraud Detection SDK implementation files('libs/Android-AliyunDevice-<version>.aar') // Required third-party network libraries implementation 'com.squareup.okhttp3:okhttp:3.11.0' implementation 'com.squareup.okio:okio:1.14.0'ImportantInclude the third-party network library dependencies. Without them, the SDK cannot connect to the internet.
Interface obfuscation
If your project uses code obfuscation, add the following rules to the proguard-rules.pro file to prevent the SDK interfaces from being obfuscated:
-keep class net.security.device.api.** {*;}
-dontwarn net.security.device.api.**Integrate the SDK
Complete the integration in three steps:
Initialize the SDK by calling
initWithOptions.Obtain the device token by calling
getDeviceToken.Send the token to your business server.
Initialize the SDK (initWithOptions)
Call this method early in your app lifecycle to start collecting device information. Complete all privacy compliance steps before calling this method.
Function prototype
public interface SecurityInitListener { // code indicates the API call status void onInitFinish(int code); } public void initWithOptions(Context ctx, String appKey, Map<String, String> options, SecurityInitListener securityInitListener);Parameters
ctx: The current Application Context or Activity Context.appKey: Identifies your app. Obtain this value from the Developer Center.options: Optional data collection settings. Defaults to null. Available options are as follows.Field
Description
Example
IPv6
Whether to use an IPv6 domain to report device information.
0 (default): Uses an IPv4 domain.
1: Uses an IPv6 domain.
"1"
CustomUrl
Sets the domain name of the data reporting server.
"https://cloudauth-device.aliyuncs.com"
CustomHost
Sets the host of the data reporting server.
"cloudauth-device.aliyuncs.com"
DataType
Specifies the types of sensitive data not to collect.
Default (empty): Collects all data.
Configurable values are listed in the following table.
Single selection:
NO_UNIQUE_DEVICE_DATA
Multiple selection:
NO_UNIQUE_DEVICE_DATA |
NO_IDENTIFY_DEVICE_DATA
Sensitive Data Type
Description
Device Information Fields
NO_UNIQUE_DEVICE_DATA
Resettable unique device identifiers
Includes: OAID, Google Advertising ID, Android ID.
NO_IDENTIFY_DEVICE_DATA
Non-resettable unique device identifiers
Includes: IMEI, IMSI, SimSerial, BuildSerial (SN), MAC address.
NO_BASIC_DEVICE_DATA
Basic device identifiers
Includes: Device name (Build.DEVICE), Android version (Build.VERSION#RELEASE), screen resolution.
NO_EXTRA_DEVICE_DATA
Extended sensitive information
Includes: Black/gray market app list, LAN IP, DNS IP, connected Wi-Fi info (SSID, BSSID), nearby Wi-Fi list, location info.
NoteTo report to a specific region, set CustomUrl and CustomHost to the corresponding endpoint. No configuration is needed by default.
Default endpoints:
Singapore: https://cloudauth-device.ap-southeast-1.aliyuncs.com
Hong Kong (China): https://cloudauth-device.cn-hongkong.aliyuncs.com
Germany: https://cloudauth-device.eu-central-1.aliyuncs.com
US: https://cloudauth-device.us-west-1.aliyuncs.com
securityInitListener: Initialization callback. Check the callback to determine whether initialization succeeded. You can pass null if you don't need a callback. For valid values of thecodefield, see Return codes.public interface SecurityInitListener { // code indicates the API call status void onInitFinish(int code); }Example
public class CustomApplication extends Application { private static String USER_PRODUCT_KEY = "123e4567e89b12d3a45642661417****"; @Override public void onCreate() { super.onCreate(); Map<String, String> options = new HashMap<>(); options.put("IPv6", "0"); // Use IPv4 // Configure sensitive data collection. Use | to combine multiple values, then convert to a string. //options.put("DataType", String.valueOf(NO_UNIQUE_DEVICE_DATA | NO_IDENTIFY_DEVICE_DATA)); // Set a custom data reporting endpoint // options.put("CustomUrl", "xxx"); Reporting site URL // options.put("CustomHost", "xxx"); Reporting site host // Standard call (recommended) SecurityDevice.getInstance().initWithOptions(this, USER_PRODUCT_KEY, options, null); // Callback call SecurityDevice.getInstance().initWithOptions(this, USER_PRODUCT_KEY, options, new SecurityInitListener() { @Override public void onInitFinish(int code) { if (SecurityCode.SC_SUCCESS != code) { Log.d("AliyunDeviceRisk", "Initialization failed"); } else { Log.d("AliyunDeviceRisk", "Initialization succeeded"); } } }); } }
Obtain the device token (getDeviceToken)
Obtain the device token and send it to your business server. Your server then calls the Device Fraud Detection API to check the fraud detection result.
Wait at least 3 seconds between calling
initWithOptionsandgetDeviceTokenwith an interval of at least 2 seconds with an interval of at least 3 seconds.Pass a
bizIdwhen callinggetDeviceTokento bind the token to a business-unique identifier. Use the same ID when querying results on the server to prevent token tampering.Call
getDeviceTokenon a non-main thread to avoid blocking the UI.
Function prototype
public SecurityToken getDeviceToken(); // Recommended: pass bizId public SecurityToken getDeviceToken(String bizId)Parameters
bizId: A business-specific identifier to associate with the token. Optional.Return value
Returns a
SecurityTokenobject, defined as follows:public class SecurityToken { // API call status code public int code; // Token string used to query results on the server side. public String token; }code: The API call status code. Check this value to determine whether the call succeeded. For valid values, see Return codes.token: The token string to use in subsequent calls to the Device Fraud Detection API.ImportantOn a stable network, the token is approximately 600 bytes. On a weak connection, it grows to approximately 2.5 KB with a special prefix:
International: Good connection "U0dfTkxxxx", weak connection "U0dfUFxxxx".
If you see many long tokens:
Verify that the client network is stable.
Wait at least 3 seconds between calling
initWithOptionsandgetDeviceTokenwith an interval of at least 2 seconds with an interval of at least 3 seconds.
Example
new Thread() { @Override public void run() { // Pass bizId to prevent deviceToken tampering. String bizId = "1234567890abcdef1234567890ab****"; SecurityToken deviceToken = SecurityDevice.getInstance().getDeviceToken(bizId); if(null != deviceToken){ if(SecurityCode.SC_SUCCESS == deviceToken.code){ Log.d("AliyunDevice", "token: " + deviceToken.token); } else { Log.e("AliyunDevice", "getDeviceToken error, code: " + deviceToken.code); } } else { Log.e("AliyunDevice", "getDeviceToken is null."); } } }.start();
After you obtain the deviceToken, pass it to your business server. Your server then calls the Device Fraud Detection API with this token to query and verify device risk information.
Return codes
SecurityCode | Code | Description |
SC_SUCCESS | 10000 | SDK initialization succeeded. |
SC_NOT_INIT | 10001 | SDK not initialized. |
SC_NOT_PERMISSION | 10002 | Required Android permissions are not fully granted. |
SC_UNKNOWN_ERROR | 10003 | Unknown system error. |
SC_NETWORK_ERROR | 10004 | Network error. |
SC_NETWORK_ERROR_EMPTY | 10005 | Network error. The returned content is empty. |
SC_NETWORK_ERROR_INVALID | 10006 | Invalid response format from the server. |
SC_PARSE_SRV_CFG_ERROR | 10007 | Failed to parse server configuration. |
SC_NETWORK_RET_CODE_ERROR | 10008 | Gateway returned an error. |
SC_APPKEY_EMPTY | 10009 | AppKey is empty. |
SC_PARAMS_ERROR | 10010 | Invalid parameter value. |
SC_FGKEY_ERROR | 10011 | Failed to calculate the key. |
SC_APPKEY_ERROR | 10012 | SDK version does not match the AppKey version. |
Complete code example
import net.security.device.api.SecurityDevice;
import net.security.device.api.SecurityInitListener;
import net.security.device.api.SecurityToken;
import net.security.device.api.SecurityCode;
import static net.security.device.api.SecurityDevice.NO_EXTRA_DEVICE_DATA;
public class MainActivity extends AppCompatActivity {
private static String USER_PRODUCT_KEY = "<Contact your business manager>";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
doStandard();
}
private void doStandard() {
// Initialize the SDK
// Call only once during the app lifecycle
// Recommended: call initWithOptions during SDK integration
doInit();
// The 2-second wait ensures data reporting completes
// try {
// Thread.sleep(2000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// Recommended: call getDeviceToken after initialization
new Thread() {
@Override
public void run() {
// Obtain the token
doGetToken();
}
}.start();
}
private void doInit() {
Map<String, String> options = new HashMap<>();
options.put("IPv6", "0"); // Use IPv4
// Configure sensitive data collection. Use | to combine multiple values, then convert to a string.
//options.put("DataType", String.valueOf(NO_UNIQUE_DEVICE_DATA | NO_IDENTIFY_DEVICE_DATA));
SecurityDevice.getInstance().initWithOptions(this, USER_PRODUCT_KEY, options, null);
}
private void doGetToken() {
// Pass bizId to prevent deviceToken tampering.
String bizId = "1234567890abcdef1234567890ab****";
SecurityToken deviceToken = SecurityDevice.getInstance().getDeviceToken(bizId);
if(null == deviceToken || SecurityCode.SC_SUCCESS != deviceToken.code){
Log.e("AliyunDevice", "Failed to obtain token, code: " + deviceToken.code);
} else {
Log.d("AliyunDevice", "Token obtained successfully, token: " + deviceToken.token);
}
}
}Call the Device Fraud Detection API
After you obtain the deviceToken, pass it along with other business parameters to the Device Fraud Detection API to query device risk information:
FAQ
For frequently asked questions about the Device Fraud Detection SDK, see FAQ.