Integrate Android SDK using license mode

Updated at:

This guide shows developers how to integrate the Android SDK using license mode to enable device management and authentication. The multi-modal SDK supports the license billing model and offers two integration modes: semi-managed and fully-managed.

1. Modes

To use the license billing model, you must integrate the License SDK on top of the multimodal interaction development kit. For SDK integration instructions, see Section 4 of this document.

Environment requirements: The SDK supports Android 7.0 (API 24) at minimum. Configure minSdkVersion as 24 or higher in your project.

1.1. Semi-managed mode

Use case: You have your own cloud service and can manage and authenticate your devices, and a two-way communication channel exists between your cloud service and the devices.

Follow these steps to integrate:
  • Server-side development:

    • Complete cloud API integration as described in the cloud API development guide. The device metering and management service provides two APIs: deviceRegister for device registration and getToken for obtaining business interaction tokens.
  • Device-side development:

    • Call the genRegisterReq API of this SDK to get the device registration signature.
    • After you get the device registration signature, call your own cloud service to register the device. Your cloud service must integrate the POP SDK.
    • After the device registration response is returned, call the writeDeviceInfo API of this SDK to write the device information.
    • Call the genGetTokenReq API of this SDK to get the data signature for the access token information.
    • After you get the data signature for the access token information, call your own cloud service to get the token. Your cloud service must integrate the POP SDK.
    • Call the getToken API of this SDK to get the decrypted business interaction token. You can then use the token for business interactions.

1.2. Fully-managed mode

Use case: You do not have a cloud service and cannot manage your devices. In this case, Alibaba Cloud performs device management and authentication.

  • Server-side development:

    • None.
  • Device-side development

    • Call the deviceRegister API of this SDK to register the device.
    • Call the getToken API of this SDK to get the business interaction token. You can then use the token for business interactions.

2. Precautions before use

  • Before using license mode, you have created an application in the Model Studio console and purchased a license.
  • The SDK encapsulates the logic for generating a unique device identifier and persists the data on the device to prevent the same device from being registered repeatedly. Obtain the identifier by calling DeviceIdentityManager.getInstance().getDeviceIdentity(context).getId(). You must use the deviceName retrieval logic provided by the SDK, or ensure the uniqueness of deviceName yourself.

Warning⚠️ Unified deviceName retrieval: In all scenarios that involve device registration, registration status queries, or token acquisition, obtain deviceName in a unified manner by calling DeviceIdentityManager.getInstance().getDeviceIdentity(context).getId(). This API has built-in backward compatibility logic: existing devices automatically return the original legacy ID, and no additional handling is required.

2.1. Device identifier generation strategy

In the new SDK, the device identifier is generated in a unified manner by the underlying DeviceIdentityManager, which adopts a multi-level fallback strategy to ensure that all Android devices can obtain a device identifier. The priorities from high to low are:

  1. CUSTOM (custom identifier): an identifier injected by the integrator through setCustomIdentity(String) (such as one delivered by your own server or an OAID). It is used as-is, without derivation.
  2. MEDIA_DRM: the MediaDrm ID (unique at the device level and supported by most devices), derived into an app-level identifier.
  3. ANDROID_ID: used when MediaDrm is unavailable. Settings.Secure.ANDROID_ID is derived into an app-level identifier.
  4. FALLBACK_UUID: when none of the above is available, a random UUID is generated and persisted to SharedPreferences, then derived into an app-level identifier.

WarningFALLBACK_UUID applies to test environments only and must not be used in production. In this mode, the device identifier changes after the app is uninstalled and reinstalled, so device uniqueness cannot be guaranteed. Uninstallation leads to problems such as duplicate registration and failure of the token chain. In production, if the source is detected as FALLBACK_UUID, inject a stable identifier through setCustomIdentity() or prompt the user that the device is incompatible.

Compatibility notes:

  • DeviceIdentityManager.getInstance().getDeviceIdentity(context).getId() has built-in backward compatibility logic: existing devices automatically return the original legacy ID, while new devices go through the multi-level fallback strategy. DeviceUUIDUtil.getAndroidId(context) is still available (it internally delegates to DeviceIdentityManager) but has been marked as deprecated.
  • For a comparison of the format, length, and stability of identifiers from each source, see Section 7.

3. API description

3.1. SDK initialization initialize

Both semi-managed and fully-managed modes require the initialization API to be called first.

Input parameters:

Field

Type

Required

Description

appId

String

Yes

The application identifier, generated after you create an application in the Model Studio console.

appSecret

String

Yes

The application secret, generated after you create an application in the Model Studio console.

deviceName

String

Yes

The unique device identifier, obtained by calling DeviceIdentityManager.getInstance().getDeviceIdentity(context).getId()

callBack

InitCallBack

Yes

The SDK initialization callback. See the InitCallBack object for details.

ImportantSecurity tip: appSecret is a sensitive credential. Do not hard-code it in client code (to prevent leakage through APK decompilation). We recommend that the integrator's server deliver it securely at runtime.

InitCallBack object

Return value

Method name

Description

void

success()

Initialization succeeded.

void

fail(ResultError error)

Initialization failed.

ResultError object

Field

Type

Required

Description

code

int

No

The returned error code.

message

String

No

The description of the returned error code.

Output parameters:

None

Code sample
DeviceAuthClient.getInstance().initialize(new InitParams(YOUY_APP_ID, YOUR_APP_SECRET, YOUR_DEVICE_NAME), new InitCallBack() {
    @Override
    public void success() {
        Log.d(TAG, "initialize success");
    }

    @Override
    public void fail(ResultError resultError) {
        Log.e(TAG, "initialize fail: " + resultError.getMessage());
    }
});

3.2. Semi-managed mode

3.2.1. Device registration APIs

3.2.1.1. Generate device registration information: genRegisterReq
Input parameters:

Field

Type

Required

Description

appId

String

Yes

The application identifier, generated after you create an application in the Model Studio console.

deviceName

String

Yes

The unique device identifier, obtained by calling DeviceIdentityManager.getInstance().getDeviceIdentity(context).getId()

payMode

String

Yes

The billing method: PAYG (pay-as-you-go) or LICENSE (license-based billing)

reqNonce

String

Yes

The request nonce, a random 26-character hex string

requestTime

String

Yes

The request timestamp.

Output parameters:

Field

Type

Required

Description

success

boolean

Yes

Whether the request was processed successfully.

code

int

No

The code returned when the request fails.

message

String

No

The description returned when the request fails.

data

String

No

The signature parameters required to call the device registration POP API.

Code sample:
DeviceRegisterInfo deviceRegisterInfo = new DeviceRegisterInfo();
deviceRegisterInfo.setAppId(YOUR_APP_ID);
deviceRegisterInfo.setDeviceName(YOUR_DEVICE_NAME);
deviceRegisterInfo.setPayMode(PayMode.LICENSE.getPayMode());
deviceRegisterInfo.setReqNonce(RandomUtil.generateRandomHexString(26));
deviceRegisterInfo.setRequestTime(String.valueOf(System.currentTimeMillis()));
Result<String> result = DeviceAuthClient.getInstance().genRegisterReq(deviceRegisterInfo);
if (result.isSuccess()) {
    Log.d(TAG, "genRegisterReq: " + result.getData());
}
3.2.1.2. Write device registration information: writeDeviceInfo

The response returned by the cloud device registration POP API must be written to the device for persistence.

Input parameters:

Field

Type

Required

Description

appId

String

Yes

The application identifier, generated after you create an application in the Model Studio console.

deviceName

String

Yes

The unique device identifier, obtained by calling DeviceIdentityManager.getInstance().getDeviceIdentity(context).getId()

reqNonce

String

Yes

The random string sent with the request, a random 26-character hex string

rspNonce

String

Yes

The random string returned with the response data, a random 26-character hex string

responseTime

String

Yes

The timestamp of the response data.

signature

String

Yes

YOUR_SIGNATURE
Output parameters:

Field

Type

Required

Description

success

boolean

Yes

Whether the request was processed successfully.

code

int

No

The code returned when the request fails.

message

String

No

The description returned when the request fails.

data

String

No

The signature parameters required to call the device registration POP API.

Code sample:
DeviceRegisterRsp params = new DeviceRegisterRsp();
params.setAppId(YOUR_APP_ID);
params.setDeviceName(YOUR_DEVICE_NAME);
params.setReqNonce(YOUR_REQUEST_NONCE);
params.setRspNonce(YOUR_RESPONSE_NONCE);
params.setResponseTime(YOUR_RESPONSE_TIME);
params.setSignature(YOUR_RESPONSE_SIGNATURE);
Result<String> result = DeviceAuthClient.getInstance().writeDeviceInfo(params);
if (result.isSuccess()) {
    Log.d(TAG, "writeDeviceInfo success");
} else {
    Log.e(TAG, "writeDeviceInfo error: " + result.getMessage());
}

3.2.2. Business interaction token APIs

3.2.2.1. Generate access token request information: genGetTokenReq
Input parameters:

Field

Type

Required

Description

nonce

String

Yes

The request nonce, a random 26-character hex string

appId

String

Yes

The application identifier, generated after you create an application in the Model Studio console.

deviceName

String

Yes

The unique device identifier, obtained by calling DeviceIdentityManager.getInstance().getDeviceIdentity(context).getId()

payMode

String

Yes

The billing method: PAYG (pay-as-you-go) or LICENSE (license-based billing)

tokenType

String

Yes

The type of token to request (currently only the MMI type is supported)

MMI: multimodal interaction token

requestTime

String

Yes

The request timestamp, in milliseconds.

Output parameters:

Field

Type

Required

Description

success

boolean

Yes

Whether the request was processed successfully.

code

int

No

The code returned when the request fails.

message

String

No

The description returned when the request fails.

data

String

No

The signature parameters required to call the device registration POP API.

{
    "success": true,
    "data": "84uoRCyy6AG/sss/xxxxx/Qj4ZvK6vrM7QC5yxtMl3TQLHdAGSsqQLb0bP6zKOiDzoNFwqs61+GMQ7guTPjbE9Fqaf7"
}
Code sample:
GenGetTokenParams params = new GenGetTokenParams();
params.setNonce(RandomUtil.generateRandomHexString(26));
params.setAppId(YOUR_APP_ID);
params.setDeviceName(YOUR_DEVICE_NAME);
params.setPayMode(PayMode.LICENSE.getPayMode());
params.setTokenType("MMI");
params.setRequestTime(String.valueOf(System.currentTimeMillis()));
Result<String> result = DeviceAuthClient.getInstance().genGetTokenReq(params);
if (result.isSuccess()) {
    Log.d(TAG, "getTokenSign: " + result.getData());
}
3.2.2.2. Decode the token data returned by the POP API: getToken
Input parameters:

Field

Type

Required

Description

appId

String

Yes

The application identifier, generated after you create an application in the Model Studio console.

deviceName

String

Yes

The unique device identifier, obtained by calling DeviceIdentityManager.getInstance().getDeviceIdentity(context).getId()

reqNonce

String

Yes

The request nonce, a random 26-character hex string

rspNonce

String

Yes

The random string returned with the response data, a random 26-character hex string

responseTime

String

Yes

The timestamp of the response data.

signature

String

Yes

YOUR_SIGNATURE
Output parameters:

Field

Type

Required

Description

success

boolean

Yes

Whether the request was processed successfully.

code

int

No

The code returned when the request fails.

message

String

No

The description returned when the request fails.

data

String

No

The decoded data returned.

Code sample:
AnalyzeTokenSignRsp tokenSignRsp = new AnalyzeTokenSignRsp();
tokenSignRsp.setAppId(YOUR_APP_ID);
tokenSignRsp.setDeviceName(YOUR_DEVICE_NAME);
tokenSignRsp.setReqNonce(YOUR_REQUEST_NONCE);
tokenSignRsp.setRspNonce(YOUR_RESPONSE_NONCE);
tokenSignRsp.setResponseTime(YOUR_RESPONSE_TIME);
tokenSignRsp.setSignature(YOUR_RESPONSE_SIGNATURE);
Result<String> result = DeviceAuthClient.getInstance().getToken(tokenSignRsp);
if (result.isSuccess()) {
    Log.d(TAG, "analyzeTokenSign: " + result.getData());
}

3.3. Fully-managed mode

3.3.1. Check whether the device is registered: deviceIsRegistered

Input parameters: None Output parameters:

Whether the device is registered

Code sample:
boolean deviceIsRegistered = DeviceAuthClient.getInstance().deviceIsRegistered();

3.3.2. Device registration: deviceRegister

Input parameters:

Field

Type

Required

Description

params

DeviceRegisterParams

Yes

The input object for device registration. See the DeviceRegisterParams object for details.

callBack

DeviceRegisterCallBack

Yes

The device registration callback.

DeviceRegisterParams object

Field

Type

Required

Description

nonce

String

Yes

The request nonce, a random 26-character hex string

appId

String

Yes

The application identifier, generated after you create an application in the Model Studio console.

workspaceId

String

No

The workspace ID, required only when you register the device by using a workspace quota

deviceName

String

Yes

The unique device identifier, obtained by calling DeviceIdentityManager.getInstance().getDeviceIdentity(context).getId()

requestTime

String

Yes

The request timestamp.

payMode

String

Yes

The billing method: PAYG (pay-as-you-go) or LICENSE (license-based billing)

Output parameters:

None

Code sample:
DeviceRegisterParams params = new DeviceRegisterParams();
params.setNonce(RandomUtil.generateRandomHexString(26));
params.setAppId(YOUR_APP_ID);
params.setWorkspaceId(YOUR_WORKSPACE_ID);
params.setDeviceName(YOUR_DEVICE_NAME);
params.setRequestTime(String.valueOf(System.currentTimeMillis()));
params.setPayMode(PayMode.LICENSE.getPayMode());
DeviceAuthClient.getInstance().deviceRegister(params, new DeviceRegisterCallBack() {
    @Override
    public void success() {
        Log.d(TAG, "deviceRegister success");
    }

    @Override
    public void fail(ResultError error) {
        Log.e(TAG, error.getMessage());
    }
});

3.3.3. Get the business interaction token: getToken

Input parameters:

Field

Type

Default

Required

Description

params

GenGetTokenParams

-

Yes

The parameter object required for device authentication. See the GenGetTokenParams object for details.

callBack

GetTokenCallBack

-

Yes

The callback for obtaining a token. See the GetTokenCallBack

object for details.

GenGetTokenParams object

Field

Type

Default

Required

Description

nonce

String

-

Yes

The request nonce, a random 26-character hex string

appId

String

-

Yes

The application identifier, generated after you create an application in the Model Studio console.

apiKey

String

-

Yes

The application key, created in Key Management in the Model Studio console.

deviceName

String

-

Yes

The unique device identifier, obtained by calling DeviceIdentityManager.getInstance().getDeviceIdentity(context).getId()

requestTime

String

-

Yes

The request timestamp.

payMode

String

-

Yes

The billing method: PAYG (pay-as-you-go) or LICENSE (license-based billing)

tokenType

String

-

Yes

The type of token to request (currently only the MMI type is supported)

MMI: multimodal interaction token

Output parameters:

None

Code sample:
GenGetTokenParams params = new GenGetTokenParams();
params.setNonce(RandomUtil.generateRandomHexString(26));
params.setAppId(YOUR_APP_ID);
params.setApiKey(YOUR_API_KEY);
params.setDeviceName(YOUR_DEVICE_NAME);
params.setRequestTime(String.valueOf(System.currentTimeMillis()));
params.setPayMode(PayMode.LICENSE.getPayMode());
params.setTokenType("MMI");
DeviceAuthClient.getInstance().getToken(params, new GetTokenCallBack() {
    @Override
    public void success(String tokenInfo) {
        Log.d(TAG, "getToken success: " + tokenInfo);
    }

    @Override
    public void fail(ResultError error) {
        Log.e(TAG, error.getMessage());
    }
});

3.4. Get the license signature

Input parameters:

Field

Type

Default

Required

Description

params

LicenseSignatureParams

-

Yes

The parameter object required for device authentication. See the LicenseSignatureParams object for details.

LicenseSignatureParams object

Field

Type

Default

Required

Description

appId

String

-

Yes

The application identifier, generated after you create an application in the Model Studio console.

deviceName

String

-

Yes

The unique device identifier, obtained by calling DeviceIdentityManager.getInstance().getDeviceIdentity(context).getId()

taskId

String

-

Yes

The unique identifier of the current connection, used to track task execution in the engineering pipeline. It is generated by the client. The recommended format is a 36-character UUID string, for example: "f894c16f-f20e-4c1d-837e-89e0fbc63a43"

Output parameters:

Field

Type

Default

Description

timestamp

String

-

The current timestamp, in milliseconds.

license_info

String

-

The signature information of license_info.

device_info

String

-

The signature information of device_info.

Code sample:
/// 获取license标识签名
String taskId = UUID.randomUUID().toString().replace("-", "");
LicenseSignatureParams params = new LicenseSignatureParams(authParams.getAppid(), YOUR_DEVICE_NAME, taskId);
JSONObject licenseInfoSignature = DeviceAuthClient.getInstance().getLicenseSignature(params);
// 返回包含timestamp和license_info、device_info的JSON字符串

3.5. Device reset: deviceReset

Tip: After you reset a device in the Model Studio console, call the SDK deviceReset API to reset the device, after which the device can be registered again.

Input parameters:

None

Output parameters:

A Boolean value indicating whether the reset succeeded.

Code sample:
boolean result = DeviceAuthClient.getInstance().deviceReset();
 if (!result) {
     showToast("设备重置失败");
 } else {
     showToast("设备重置成功,可以重新注册");
 }

3.6. Device identifier management: DeviceIdentityManager

DeviceIdentityManager is the only recommended API (a singleton) for SDK device identifiers. It provides capabilities such as the multi-level fallback strategy, backward-compatible reads, custom namespaces, and custom identifier injection. All compatibility logic of earlier SDK versions is built in, and existing devices automatically return the original legacy ID when the API is called.

ImportantDeviceUUIDUtil.getAndroidId(context) has been marked as deprecated (since 1.0.7) and fully delegates to DeviceIdentityManager internally. Existing code does not need to be changed immediately, but we recommend gradually migrating to DeviceIdentityManager.getInstance().getDeviceIdentity(context).getId().

3.6.1. API list

Method

Description

DeviceIdentityManager.getInstance()

Obtain the singleton instance.

DeviceIdentity getDeviceIdentity(Context context)

Obtain the device identifier. The namespace defaults to the application package name.

DeviceIdentity getDeviceIdentity(Context context, String namespace)

Obtain the device identifier, using a custom namespace to override the default package-name salt (pass null to use the default package name).

void setCustomIdentity(String identity)

Inject a custom device identifier, which is used as the highest-priority identifier as-is (without derivation). Pass null to clear it. A value longer than 40 characters throws IllegalArgumentException.

void setOnIdentityResolvedListener(OnIdentityResolvedListener listener)

Set the callback invoked when the identifier is resolved. It is triggered each time a device identifier is resolved (including cache hits). Pass null to remove the callback.

void clearCache(Context context)

Clear the in-memory cache and the disk cache of the MediaDrm ID. The next retrieval obtains the value from the device again and derives it. Note: the fallback UUID is not cleared by this method.

3.6.2. DeviceIdentity return values

Method

Return value

Description

getId()

String

The finally selected device identifier (the derived app-level identifier, or the injected original value when the source is CUSTOM), with a maximum length of 40 characters.

getSource()

IdentitySource

The enumeration of the identifier source. See the table below.

3.6.3. IdentitySource enumeration

Enum value

Description

CUSTOM

A custom identifier (injected externally), used as-is.

MEDIA_DRM

The MediaDrm ID (unique to the device, unchanged after reinstallation, changes after a factory reset).

ANDROID_ID

The Android ID (unique to the device, unchanged after reinstallation, changes after a factory reset).

FALLBACK_UUID

A random UUID (changes after uninstallation) — ⚠️ For test environments only

3.6.4. Code sample

// 1. 默认 namespace(应用包名)获取设备标识(推荐用于 deviceName)
DeviceIdentity identity = DeviceIdentityManager.getInstance().getDeviceIdentity(context);
String deviceId = identity.getId();                 // 40 字符固定长度哈希(CUSTOM 时为原值)
IdentitySource source = identity.getSource();       // 标识来源

// 2. 自定义 namespace(多个应用使用相同 namespace + 相同签名时可共享标识,参见第 8 节)
DeviceIdentity shared = DeviceIdentityManager.getInstance().getDeviceIdentity(context, "com.example.shared");

// 3. 注入服务端下发的自定义标识(最高优先级,按原值使用)
DeviceIdentityManager.getInstance().setCustomIdentity(identityFromServer);

// 4. 监听标识解析结果
DeviceIdentityManager.getInstance().setOnIdentityResolvedListener(new OnIdentityResolvedListener() {
    @Override
    public void onIdentityResolved(DeviceIdentity identity) {
        Log.d(TAG, "identity resolved: " + identity.getId() + ", source=" + identity.getSource());
    }
});

// 5. 清除缓存,下次获取时重新解析
DeviceIdentityManager.getInstance().clearCache(context);

4. Integrate the SDK and dependency libraries

Use the latest version of the Android SDK and reference the multimodal_dialog_tongyimetathings-<版本号>.aar file within it.

In this document, <版本号> is a placeholder. Replace it with the actual file name you obtained.

For the changes and upgrade impact of each version, see Section 10, "Version release history".

4.1. Gradle integration steps

  1. Place multimodal_dialog_tongyimetathings-<版本号>.aar in the libs/ directory of the app module.
  2. Add the dependency to build.gradle of the app module:
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.aar'])
    // 或显式引用:
    // implementation files('libs/multimodal_dialog_tongyimetathings-<版本号>.aar')

    // 必需:AAR 不内联第三方依赖,以下依赖必须由接入方显式声明
    implementation 'com.squareup.okhttp3:okhttp:4.12.0'
}
  1. Make sure minSdkVersion is 24 (Android 7.0) or higher:
android {
    defaultConfig {
        minSdkVersion 24
    }
}
  1. After you sync the project, you can use the SDK APIs.

About third-party dependencies (must read): The AAR format does not inline dependencies. The classes.jar in the SDK artifact contains only the SDK's own classes and no okhttp classes. Therefore, the dependency above must be explicitly declared in the app module. Otherwise, the SDK throws NoClassDefFoundError when it initiates network requests such as device registration and token acquisition.

Dependency

Dependency version

Version requirement

com.squareup.okhttp3:okhttp

4.12.0

Must be 4.x. The okhttp 3.x and 4.x APIs are incompatible, and using 3.x causes runtime exceptions.

If your project already includes the dependency above, you do not need to declare it again, but make sure that the okhttp major version is 4.x.

4.2. Obfuscation rules

If code obfuscation (ProGuard/R8) is enabled in your project, add the following keep rules to the obfuscation configuration file to prevent device identifier-related classes from being obfuscated or stripped:

-keep class com.aliyun.bailian.billingsignature.identity.DeviceIdentityManager { *; }
-keep class com.aliyun.bailian.billingsignature.identity.DeviceIdentity { *; }
-keep class com.aliyun.bailian.billingsignature.identity.IdentitySource { *; }
-keep class com.aliyun.bailian.billingsignature.identity.OnIdentityResolvedListener { *; }
-keep class com.aliyun.bailian.billingsignature.utils.DeviceUUIDUtil { *; }

5. Changes required for multimodal SDK integration

  1. Before starting a session, complete the initialization of the tongyimetathings SDK and check whether the device is registered. If the device is not registered, register it. For details, see the sample integration project.
  2. Initialize the SDK. After device registration is complete, obtain the multimodal session token: for fully-managed mode, see the API in Section 3.3.3 (getToken) above; for semi-managed mode, see the APIs in Section 3.2.2 above. Set the dashToken data returned by the getToken API as the apiKey. For details, see the sample project.
multimodalParams.setApiKey(jsonObject.getString("dashToken"));
  1. When creating a session, pass the license billing identifier. See the integration example:
private MultiModalRequestParam buildRequestParams() {

    MultiModalRequestParam.UpStream.ReplaceWord replaceWord = new MultiModalRequestParam.UpStream.ReplaceWord();
    replaceWord.setTarget("一加一");
    replaceWord.setSource("1加1");
    replaceWord.setMatchMode("partial");
    String deviceName = DeviceIdentityManager.getInstance().getDeviceIdentity(this).getId();
    taskId = UUID.randomUUID().toString().replace("-", "");
    //构建License计费标识
    LicenseSignatureParams params = new LicenseSignatureParams(authParams.getAppid(), deviceName, taskId);
    JSONObject licenseInfoSignature = DeviceAuthClient.getInstance().getLicenseSignature(params);
    Map<String, Object> map = new HashMap<>();
    map.put("signature", licenseInfoSignature);
    return MultiModalRequestParam.builder()
            .clientInfo(MultiModalRequestParam.ClientInfo.builder()
                    .device(MultiModalRequestParam.ClientInfo.Device.builder()
                            .uuid(deviceName).build()) // 请配置为您的设备UUID
                    .userId("123")  //userid 需要每个用户唯一,建议使用设备UUID。 对话历史会使用 userId关联
                    .passThroughParams(map) //传入License计费标识
                    .build())
            .upStream(MultiModalRequestParam.UpStream.builder()
                    .mode(authParams.getDialogMode().getValue())
                    .type("AudioAndVideo")
                    .asrPostProcessing(Collections.singletonList(replaceWord))
                    .build())
            .downStream(MultiModalRequestParam.DownStream.builder()
                    .voice(mVoiceType) //tts 音色对应的模型需要和管控台配置的模型一致。longxiaochun_v2对应了cosyvoice_v2
                    .sampleRate(48000)
                    .intermediateText(textStreamFeedback ? "dialog" : "transcript")
                    .build())
            .build();
}

6. Permissions

Permissions required for the SDK to run:

Permission

Purpose

Requirement

android.permission.INTERNET

Network requests such as device registration and token acquisition

Required

android.permission.WRITE_EXTERNAL_STORAGE

Persisting the device registration information to the external public directory in writeDeviceInfo

Required on Android 10 and earlier

android.permission.READ_EXTERNAL_STORAGE

Reading the persisted device registration information (for the deviceIsRegistered check)

Required on Android 10 and earlier

android.permission.MANAGE_EXTERNAL_STORAGE

Reading the legacy device identifier and registration information from external storage after the app is uninstalled and reinstalled on an existing device

Required on Android 11 and later

AndroidManifest.xml declaration example:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    android:maxSdkVersion="28" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
    android:maxSdkVersion="28" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

7. Device ID format and stability

Source

Format

Length

Uninstall and reinstall

Factory reset

CUSTOM

Original value

≤40

Depends on the integrator

Depends on the integrator

MEDIA_DRM

SHA-256 derived

40

Unchanged

May change

ANDROID_ID

SHA-256 derived

40

Unchanged

Changes

FALLBACK_UUID

SHA-256 derived

40

⚠️ Changes (test only)

Changes

Notes:

  • The historical IDs of devices registered with earlier SDK versions are preserved as-is (without derivation) and do not change when the SDK is upgraded.

8. Sharing a device identifier across multiple apps

By default, the namespace used for derivation is the application package name. Therefore, different apps on the same device obtain different device IDs (app-level isolation).

If multiple apps need to share the same device identifier (for example, multiple apps from the same vendor share a device registration record), you can use the following solutions:

  1. Same namespace + same signature: multiple apps call getDeviceIdentity(context, "the same namespace") with the same custom namespace, and each app is signed with the same signature (on Android 8.0+, ANDROID_ID is isolated by "device + app signature". Apps with different signatures obtain different ANDROID_ID values, which leads to inconsistent derived results).
  2. Unified server-side delivery: the integrator's server generates a unified device ID, and each app injects it after startup through DeviceIdentityManager.getInstance().setCustomIdentity(id), where it is used as the highest-priority identifier as-is.

Android 8.0+ ANDROID_ID signature isolation mechanism: Since Android 8.0 (API 26), the value of Settings.Secure.ANDROID_ID is bound to "device + app signing key + user". Apps with different signatures on the same device obtain different ANDROID_ID values. Therefore, when sharing an identifier across apps, either ensure that the signatures are the same, or use the server-side delivery (setCustomIdentity) solution.

9. FAQ

Q: What is the difference between DeviceUUIDUtil and DeviceIdentityManager?

A: DeviceIdentityManager is the only recommended device identifier API and has built-in backward compatibility logic. DeviceUUIDUtil has been marked as deprecated and fully delegates to DeviceIdentityManager internally. Existing code does not need to be changed immediately, but we recommend migrating gradually. To migrate, simply replace DeviceUUIDUtil.getAndroidId(context) with DeviceIdentityManager.getInstance().getDeviceIdentity(context).getId(). The IDs of existing devices will not change.

Q: Can FALLBACK_UUID be used in production?

A: ⚠️ No. FALLBACK_UUID applies to test environments only. In this mode, a random UUID is persisted to SharedPreferences, and the identifier changes after the app is uninstalled and reinstalled, so device uniqueness cannot be guaranteed. In production, this causes the following problems:

  • Duplicate device registration, which consumes the license quota
  • Failure of the token chain bound to the legacy device identifier, interrupting business interactions
  • Discontinuous device metering data, which affects operational statistics

Recommended practice: In production, if identity.getSource() == IdentitySource.FALLBACK_UUID is detected, you should:

  1. Inject a stable identifier through DeviceIdentityManager.getInstance().setCustomIdentity(stableId) (such as a device ID delivered by the server or an OAID);
  2. Or prompt the user that the device is incompatible and guide them to contact support.

10. Version release history

This section records the changes visible to integrators in each version.

Version

versionCode

Major changes

Upgrade impact

1.0.7

202608012

1. Added the device identifier management API DeviceIdentityManager, which supports custom identifier injection and namespace-based derivation (see Section 3.6 for details)
2. Device identifier persistence changed to app-private storage (SharedPreferences), so obtaining the device identifier no longer requires external storage permissions; device registration information is still persisted to the external public directory (see Section 6 for details)
3. Device IDs use the multi-level fallback strategy (MEDIA_DRM → ANDROID_ID → FALLBACK_UUID) and are unified as 40-character derived values (see Section 7 for details)
4. DeviceUUIDUtil is deprecated; we recommend using DeviceIdentityManager directly

Compatible upgrade. The historical IDs of existing registered devices are automatically read as-is for compatibility, deviceName remains unchanged, and re-registration is not required;

1.0.6

20260724

Optimized the IPv6-first connection logic to improve connection setup efficiency in dual-stack network environments

No API changes. Replace the AAR directly.

1.0.5

20260610

Optimized the OkHttpClient connection configuration to support IPv6-first connections

No API changes. Replace the AAR directly.

1.0.4

20260602

Added the workspaceId field to DeviceRegisterParams to support registering devices by using workspace quotas (see Section 3.3 for details)

A new optional field that does not affect existing calls.

1.0.3

20260413

1. Supported custom storage paths for storing device-related information
2. The SDK version number is dynamically associated with BuildConfig.SDK_VERSION

No API changes. Replace the AAR directly.

1.0.2

20260326

The so library supports both the armeabi-v7a and arm64-v8a CPU architectures

No API changes. Replace the AAR directly.

1.0.1

20250808

Initial release:
1. Semi-managed mode: device registration signature (genRegisterReq), device information writing (writeDeviceInfo), token request signature (genGetTokenReq), and token response decoding (getToken)
2. Fully-managed mode: device registration (deviceRegister) and token acquisition (getToken)
3. License signature (getLicenseSignature), device reset (deviceReset), and registration status query (deviceIsRegistered)
4. Communication security based on the native so library

—