diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index ac000a8f0c1e7039b6aea2c213d85a768aaeb723..783000e36123a1fe8219fdebe0d61f8f1fe4d6c5 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -40,6 +40,7 @@ - [@ohos.app.ability.appRecovery](js-apis-app-ability-appRecovery.md) - [@ohos.app.ability.Configuration](js-apis-app-ability-configuration.md) - [@ohos.app.ability.ConfigurationConstant](js-apis-app-ability-configurationConstant.md) + - [@ohos.app.ability.dataUriUtils](js-apis-app-ability-dataUriUtils.md) - [@ohos.app.ability.errorManager](js-apis-app-ability-errorManager.md) - [@ohos.app.ability.missionManager](js-apis-app-ability-missionManager.md) - [@ohos.app.ability.quickFixManager](js-apis-app-ability-quickFixManager.md) @@ -199,17 +200,19 @@ - [@ohos.data.dataSharePredicates](js-apis-data-dataSharePredicates.md) - [@ohos.data.dataShareResultSet](js-apis-data-DataShareResultSet.md) - [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md) + - [@ohos.data.distributedKVStore](js-apis-distributedKVStore.md) - [@ohos.data.preferences](js-apis-data-preferences.md) - [@ohos.data.rdb](js-apis-data-rdb.md) - [@ohos.data.ValuesBucket](js-apis-data-ValuesBucket.md) - - data/rdb/[resultSet](js-apis-data-resultset.md) + - data/rdb + - [resultSet](js-apis-data-resultset.md) - File Management - [@ohos.document](js-apis-document.md) - [@ohos.environment](js-apis-environment.md) - [@ohos.data.fileAccess](js-apis-fileAccess.md) - [@ohos.fileExtensionInfo](js-apis-fileExtensionInfo.md) - [@ohos.fileio](js-apis-fileio.md) - - [@ohos.filemanagement.userfile_manager](js-apis-userfilemanager.md) + - [@ohos.filemanagement.userFileManager](js-apis-userFileManager.md) - [@ohos.multimedia.medialibrary](js-apis-medialibrary.md) - [@ohos.securityLabel](js-apis-securityLabel.md) - [@ohos.statfs](js-apis-statfs.md) @@ -238,10 +241,13 @@ - [@ohos.nfc.controller](js-apis-nfcController.md) - [@ohos.nfc.tag](js-apis-nfcTag.md) - [@ohos.rpc](js-apis-rpc.md) + - [@ohos.wifiManager (WLAN)](js-apis-wifiManager.md) + - [@ohos.wifiManagerExt](js-apis-wifiManagerExt.md) - [@ohos.wifi](js-apis-wifi.md) - [@ohos.wifiext](js-apis-wifiext.md) - - tag/[nfctech](js-apis-nfctech.md) - - tag/[tagSession](js-apis-tagSession.md) + - tag + - [nfctech](js-apis-nfctech.md) + - [tagSession](js-apis-tagSession.md) - Basic Features - [@ohos.accessibility](js-apis-accessibility.md) - [@ohos.accessibility.config](js-apis-accessibility-config.md) @@ -340,6 +346,7 @@ - [@ohos.prompt](js-apis-prompt.md) - [@ohos.reminderAgent](js-apis-reminderAgent.md) - [@ohos.systemParameter](js-apis-system-parameter.md) + - [@ohos.usb](js-apis-usb-deprecated.md) - [@ohos.workScheduler](js-apis-workScheduler.md) - [@system.app](js-apis-system-app.md) - [@system.battery](js-apis-system-battery.md) diff --git a/en/application-dev/reference/apis/js-apis-appAccount.md b/en/application-dev/reference/apis/js-apis-appAccount.md index c98d603c0092e8f2fd9e1f9a2ce0d33ecd9cc1a7..0d2aef3e25aa21eb724c8f74f977d901ea12b290 100644 --- a/en/application-dev/reference/apis/js-apis-appAccount.md +++ b/en/application-dev/reference/apis/js-apis-appAccount.md @@ -1,8 +1,9 @@ -# App Account Management +# @ohos.account.appAccount -The **appAccount** module provides APIs for app account management. You can use the APIs to add, delete, query, modify, and authorize app accounts, write data to disks, and synchronize data. +The **appAccount** module provides APIs for adding, deleting, modifying, and querying app account information, and supports inter-app authentication and distributed data synchronization. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -17,7 +18,7 @@ import account_appAccount from '@ohos.account.appAccount'; createAppAccountManager(): AppAccountManager -Creates an **AppAccountManager** instance. +Creates an **AppAccountManager** object. **System capability**: SystemCapability.Account.AppAccount @@ -25,46 +26,59 @@ Creates an **AppAccountManager** instance. | Type | Description | | ----------------- | ------------ | -| AppAccountManager | **AppAccountManager** instance created.| +| AppAccountManager | **AppAccountManager** object created.| **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); ``` ## AppAccountManager -Provides methods to manage app accounts. +Implements app account management. -### addAccount +### createAccount9+ -addAccount(name: string, callback: AsyncCallback<void>): void +createAccount(name: string, callback: AsyncCallback<void>): void; -Adds an app account to the **AppAccountManager** service. This API uses an asynchronous callback to return the result. +Creates an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | -------------------- | -| name | string | Yes | Name of the app account to add. | -| callback | AsyncCallback<void> | Yes | Callback invoked when the app account is added.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ----- | -------------------- | +| name | string | Yes | Name of the app account to create. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name. | +| 12300004 | Account already exists. | +| 12300007 | The number of accounts reaches the upper limit. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.addAccount("WangWu", (err) => { - console.log("addAccount err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.createAccount("WangWu", (err) => { + console.log("createAccount err: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("createAccount err: " + JSON.stringify(err)); + } ``` -### addAccount +### createAccount9+ -addAccount(name: string, extraInfo: string, callback: AsyncCallback<void>): void +createAccount(name: string, options: CreateAccountOptions, callback: AsyncCallback<void>): void -Adds an app account name and additional information (information that can be converted into the string type, such as token) to the **AppAccountManager** service. This API uses an asynchronous callback to return the result. +Creates an app account with custom data. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -72,26 +86,46 @@ Adds an app account name and additional information (information that can be con | Name | Type | Mandatory | Description | | --------- | ------------------------- | ---- | ---------------------------------------- | -| name | string | Yes | Name of the app account to add. | -| extraInfo | string | Yes | Additional information to add. The additional information cannot contain sensitive information, such as the app account password.| -| callback | AsyncCallback<void> | Yes | Callback invoked when the app account name and additional information are added. | +| name | string | Yes | Name of the app account to create. | +| options | [CreateAccountOptions](#createaccountoptions9) | Yes | Options for creating the app account. You can customize data based on service requirements, but do not add sensitive data (such as passwords and tokens).| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object. | + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or options. | +| 12300004 | Account already exists. | +| 12300007 | The number of accounts reaches the upper limit. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.addAccount("LiSi", "token101", (err) => { - console.log("addAccount err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + let options = { + customData: { + "age": "10" + } + } + try { + appAccountManager.createAccount("LiSi", options, (err) => { + if (err) { + console.log("createAccount failed, error: " + JSON.stringify(err)); + } else { + console.log("createAccount successfully"); + } + }); + } catch(err) { + console.log("createAccount exception: " + JSON.stringify(err)); + } ``` +### createAccount9+ +createAccount(name: string, options?: CreateAccountOptions): Promise<void> -### addAccount - -addAccount(name: string, extraInfo?: string): Promise<void> - -Adds an app account name and additional information (information that can be converted into the string type, such as token) to the **AppAccountManager** service. This API uses a promise to return the result. +Creates an app account with custom data. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -99,31 +133,104 @@ Adds an app account name and additional information (information that can be con | Name | Type | Mandatory | Description | | --------- | ------ | ---- | ---------------------------------------- | -| name | string | Yes | Name of the app account to add. | -| extraInfo | string | No | Additional information to add. The additional information cannot contain sensitive information, such as the app account password.| +| name | string | Yes | Name of the app account to create. | +| options | [CreateAccountOptions](#createaccountoptions9) | No | Options for creating the app account. You can customize data based on service requirements, but do not add sensitive data (such as passwords and tokens). This parameter can be left empty.| **Return value** | Type | Description | | ------------------- | --------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or options. | +| 12300004 | Account already exists. | +| 12300007 | The number of accounts reaches the upper limit. | +| 12400003 | The number of custom data reaches the upper limit. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.addAccount("LiSi", "token101").then(()=> { - console.log('addAccount Success'); - }).catch((err) => { - console.log("addAccount err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + let options = { + customData: { + "age": "10" + } + } + try { + appAccountManager.createAccount("LiSi", options).then(() => { + console.log("createAccount successfully"); + }).catch((err) => { + console.log("createAccount failed, error: " + JSON.stringify(err)); + }); + } catch(err) { + console.log("createAccount exception: " + JSON.stringify(err)); + } ``` -### addAccountImplicitly8+ +### createAccountImplicitly9+ -addAccountImplicitly(owner: string, authType: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void +createAccountImplicitly(owner: string, callback: AuthCallback): void + +Creates an app account implicitly based on the specified account owner. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ---- | ----------------------- | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | +| callback | [AuthCallback](#authcallback9) | Yes | Authenticator callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid owner. | +| 12300007 | The number of accounts reaches the upper limit. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | + +**Example** + + ```js + import featureAbility from '@ohos.ability.featureAbility'; -Implicitly adds an app account based on the specified account owner, authentication type, and options. This API uses an asynchronous callback to return the result. + function onResultCallback(code, result) { + console.log("resultCode: " + code); + console.log("result: " + JSON.stringify(result)); + } + + function onRequestRedirectedCallback(request) { + let abilityStartSetting = {want: request}; + featureAbility.startAbility(abilityStartSetting, (err) => { + console.log("startAbility err: " + JSON.stringify(err)); + }); + } + + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.createAccountImplicitly("com.example.accountjsdemo", { + onResult: onResultCallback, + onRequestRedirected: onRequestRedirectedCallback + }); + } catch (err) { + console.log("createAccountImplicitly exception: " + JSON.stringify(err)); + } + ``` + +### createAccountImplicitly9+ + +createAccountImplicitly(owner: string, options: CreateAccountImplicitlyOptions, callback: AuthCallback): void + +Creates an app account implicitly based on the specified account owner and options. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -131,10 +238,20 @@ Implicitly adds an app account based on the specified account owner, authenticat | Name | Type | Mandatory | Description | | -------- | --------------------- | ---- | ----------------------- | -| owner | string | Yes | Owner of the app account to add. The value is the bundle name of the app. | -| authType | string | Yes | Authentication type of the app account to add. The authentication type is customized. | -| options | {[key: string]: any} | Yes | Authentication options, which can be set as required.| -| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the authentication result. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | +| options | [CreateAccountImplicitlyOptions](#createaccountimplicitlyoptions9) | Yes | Options for implicitly creating the account. | +| callback | [AuthCallback](#authcallback9) | Yes | Authenticator callback used to return the result. | + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or options. | +| 12300007 | The number of accounts reaches the upper limit. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | **Example** @@ -142,29 +259,37 @@ Implicitly adds an app account based on the specified account owner, authenticat import featureAbility from '@ohos.ability.featureAbility'; function onResultCallback(code, result) { - console.log("resultCode: " + code); - console.log("result: " + JSON.stringify(result)); + console.log("resultCode: " + code); + console.log("result: " + JSON.stringify(result)); } function onRequestRedirectedCallback(request) { - let abilityStartSetting = {want: request}; - featureAbility.startAbility(abilityStartSetting, (err)=>{ - console.log("startAbility err: " + JSON.stringify(err)); - }); + let abilityStartSetting = {want: request}; + featureAbility.startAbility(abilityStartSetting, (err) => { + console.log("startAbility err: " + JSON.stringify(err)); + }); } - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.addAccountImplicitly("com.example.ohos.accountjsdemo", "getSocialData", {}, { + let appAccountManager = account_appAccount.createAppAccountManager(); + let options = { + authType: "getSocialData", + requiredLabels: [ "student" ] + }; + try { + appAccountManager.createAccountImplicitly("com.example.accountjsdemo", options, { onResult: onResultCallback, onRequestRedirected: onRequestRedirectedCallback - }); + }); + } catch (err) { + console.log("createAccountImplicitly exception: " + JSON.stringify(err)); + } ``` -### deleteAccount +### removeAccount9+ -deleteAccount(name: string, callback: AsyncCallback<void>): void +removeAccount(name: string, callback: AsyncCallback<void>): void -Deletes an app account from the **AppAccountManager** service. This API uses an asynchronous callback to return the result. +Removes an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -172,23 +297,39 @@ Deletes an app account from the **AppAccountManager** service. This API uses an | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ---------------- | -| name | string | Yes | Name of the app account to delete. | -| callback | AsyncCallback<void> | Yes | Callback invoked when the app account is deleted.| +| name | string | Yes | Name of the app account to remove. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name. | +| 12300003 | Account not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.deleteAccount("ZhaoLiu", (err) => { - console.log("deleteAccount err: " + JSON.stringify(err)); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.removeAccount("ZhaoLiu", (err) => { + if (err) { + console.log("removeAccount failed, error: " + JSON.stringify(err)); + } else { + console.log("removeAccount successfully"); + } }); + } catch(err) { + console.log("removeAccount exception: " + JSON.stringify(err)); + } ``` -### deleteAccount +### removeAccount9+ -deleteAccount(name: string): Promise<void> +removeAccount(name: string): Promise<void> -Deletes an app account from the **AppAccountManager** service. This API uses a promise to return the result. +Removes an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -196,87 +337,131 @@ Deletes an app account from the **AppAccountManager** service. This API uses a p | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ----------- | -| name | string | Yes | Name of the app account to delete.| +| name | string | Yes | Name of the app account to remove.| **Return value** | Type | Description | | :------------------ | :-------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name. | +| 12300003 | Account not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.deleteAccount("ZhaoLiu").then(() => { - console.log('deleteAccount Success'); - }).catch((err) => { - console.log("deleteAccount err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.removeAccount("Lisi").then(() => { + console.log("removeAccount successfully"); + }).catch((err) => { + console.log("removeAccount failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("removeAccount exception: " + JSON.stringify(err)); + } ``` -### disableAppAccess +### setAppAccess9+ -disableAppAccess(name: string, bundleName: string, callback: AsyncCallback<void>): void +setAppAccess(name: string, bundleName: string, isAccessible: boolean, callback: AsyncCallback<void>): void -Disables an app account from accessing an app with the given bundle name. This API uses an asynchronous callback to return the result. +Sets the access to the data of an account for an app. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------------------------- | ---- | --------------------------------- | -| name | string | Yes | Name of the target app account. | -| bundleName | string | Yes | Bundle name of the app. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| ------------ | ------------------------- | ---- | --------------------------------- | +| name | string | Yes | Name of the target app account. | +| bundleName | string | Yes | Bundle name of the app. | +| isAccessible | boolean | Yes | Whether the access is allowed. The value **true** means to allow the access; the value **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or bundleName. | +| 12300003 | Account not found. | +| 12400001 | Application not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.disableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo", (err) => { - console.log("disableAppAccess err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.setAppAccess("ZhangSan", "com.example.accountjsdemo", true, (err) => { + if (err) { + console.log("setAppAccess failed: " + JSON.stringify(err)); + } else { + console.log("setAppAccess successfully"); + } + }); + } catch (err) { + console.log("setAppAccess exception: " + JSON.stringify(err)); + } ``` -### disableAppAccess +### setAppAccess9+ -disableAppAccess(name: string, bundleName: string): Promise<void> +setAppAccess(name: string, bundleName: string, isAccessible: boolean): Promise<void> -Disables an app account from accessing an app with the given bundle name. This API uses a promise to return the result. +Sets the access to the data of an account for an app. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------ | ---- | ---------------- | -| name | string | Yes | Name of the target app account.| -| bundleName | string | Yes | Bundle name of the app. | +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | --------- | +| name | string | Yes | Name of the target app account. | +| bundleName | string | Yes | Bundle name of the app.| +| isAccessible | boolean | Yes | Whether the access is allowed. The value **true** means to allow the access; the value **false** means the opposite.| **Return value** | Type | Description | | :------------------ | :-------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or bundleName. | +| 12300003 | Account not found. | +| 12400001 | Application not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.disableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo").then(() => { - console.log('disableAppAccess Success'); - }).catch((err) => { - console.log("disableAppAccess err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.setAppAccess("ZhangSan", "com.example.accountjsdemo", true).then(() => { + console.log("setAppAccess successfully"); + }).catch((err) => { + console.log("setAppAccess failed: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("setAppAccess exception: " + JSON.stringify(err)); + } ``` -### enableAppAccess +### checkAppAccess9+ -enableAppAccess(name: string, bundleName: string, callback: AsyncCallback<void>): void +checkAppAccess(name: string, bundleName: string, callback: AsyncCallback<boolean>): void -Enables an app account to access an app with the given bundle name. This API uses an asynchronous callback to return the result. +Checks whether an app can access the data of an account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -286,22 +471,39 @@ Enables an app account to access an app with the given bundle name. This API use | ---------- | ------------------------- | ---- | --------------------------------- | | name | string | Yes | Name of the target app account. | | bundleName | string | Yes | Bundle name of the app. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means the app can access the account data; the value **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or bundleName. | +| 12300003 | Account not found. | +| 12400001 | Application not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.enableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo", (err) => { - console.log("enableAppAccess: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.checkAppAccess("ZhangSan", "com.example.accountjsdemo", (err, isAccessible) => { + if (err) { + console.log("checkAppAccess failed, error: " + JSON.stringify(err)); + } else { + console.log("checkAppAccess successfully"); + } + }); + } catch (err) { + console.log("checkAppAccess exception: " + JSON.stringify(err)); + } ``` -### enableAppAccess +### checkAppAccess9+ -enableAppAccess(name: string, bundleName: string): Promise<void> +checkAppAccess(name: string, bundleName: string): Promise<boolean> -Enables an app account to access an app with the given bundle name. This API uses a promise to return the result. +Checks whether an app can access the data of an account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -314,26 +516,124 @@ Enables an app account to access an app with the given bundle name. This API use **Return value** +| Type | Description | +| ------------------- | --------------------- | +| Promise<boolean> | Promise used to return the result. The value **true** means the app can access the account data; the value **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or bundleName. | +| 12300003 | Account not found. | +| 12400001 | Application not found. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.checkAppAccess("ZhangSan", "com.example.accountjsdemo").then((isAccessible) => { + console.log("checkAppAccess successfully, isAccessible: " + isAccessible); + }).catch((err) => { + console.log("checkAppAccess failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("checkAppAccess exception: " + JSON.stringify(err)); + } + ``` + +### setDataSyncEnabled9+ + +setDataSyncEnabled(name: string, isEnabled: boolean, callback: AsyncCallback<void>): void + +Sets data synchronization for an app account. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ------------------------- | +| name | string | Yes | Name of the target app account. | +| isEnabled | boolean | Yes | Whether to enable data synchronization. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name. | +| 12300003 | Account not found. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.setDataSyncEnabled("ZhangSan", true, (err) => { + console.log("setDataSyncEnabled err: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("setDataSyncEnabled err: " + JSON.stringify(err)); + } + ``` + +### setDataSyncEnabled9+ + +setDataSyncEnabled(name: string, isEnabled: boolean): Promise<void> + +Sets data synchronization for an app account. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------- | ---- | ----------- | +| name | string | Yes | Name of the target app account. | +| isEnabled | boolean | Yes | Whether to enable data synchronization.| + +**Return value** + | Type | Description | | :------------------ | :-------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name. | +| 12300003 | Account not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.enableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo").then(() => { - console.log('enableAppAccess Success'); - }).catch((err) => { - console.log("enableAppAccess err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager .setDataSyncEnabled("ZhangSan", true).then(() => { + console.log('setDataSyncEnabled Success'); + }).catch((err) => { + console.log("setDataSyncEnabled err: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("setDataSyncEnabled err: " + JSON.stringify(err)); + } ``` -### checkAppAccountSyncEnable +### checkDataSyncEnabled9+ -checkAppAccountSyncEnable(name: string, callback: AsyncCallback<boolean>): void +checkDataSyncEnabled(name: string, callback: AsyncCallback<boolean>): void -Checks whether an app account allows app data synchronization. This API uses an asynchronous callback to return the result. +Checks whether data synchronization is enabled for an app account. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -344,23 +644,38 @@ Checks whether an app account allows app data synchronization. This API uses an | Name | Type | Mandatory | Description | | -------- | ---------------------------- | ---- | --------------------- | | name | string | Yes | Name of the target app account. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means data synchronization is enabled for the app account; the value **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name. | +| 12300003 | Account not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.checkAppAccountSyncEnable("ZhangSan", (err, result) => { - console.log("checkAppAccountSyncEnable err: " + JSON.stringify(err)); - console.log('checkAppAccountSyncEnable result: ' + result); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.checkDataSyncEnabled("ZhangSan", (err, isEnabled) => { + if (err) { + console.log("checkDataSyncEnabled failed, err: " + JSON.stringify(err)); + } else { + console.log('checkDataSyncEnabled successfully, isEnabled: ' + isEnabled); + } + }); + } catch (err) { + console.log("checkDataSyncEnabled err: " + JSON.stringify(err)); + } ``` -### checkAppAccountSyncEnable +### checkDataSyncEnabled9+ -checkAppAccountSyncEnable(name: string): Promise<boolean> +checkDataSyncEnabled(name: string): Promise<boolean> -Checks whether an app account allows app data synchronization. This API uses a promise to return the result. +Checks whether data synchronization is enabled for an app account. This API uses a promise to return the result. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -376,22 +691,34 @@ Checks whether an app account allows app data synchronization. This API uses a p | Type | Description | | :--------------------- | :-------------------- | -| Promise<boolean> | Promise used to return the result.| +| Promise<boolean> | Promise used to return the result. The value **true** means data synchronization is enabled for the app account; the value **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name. | +| 12300003 | Account not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.checkAppAccountSyncEnable("ZhangSan").then((data) => { - console.log('checkAppAccountSyncEnable, result: ' + data); - }).catch((err) => { - console.log("checkAppAccountSyncEnable err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.checkDataSyncEnabled("ZhangSan").then((isEnabled) => { + console.log("checkDataSyncEnabled successfully, isEnabled: " + isEnabled); + }).catch((err) => { + console.log("checkDataSyncEnabled failed, err: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("checkDataSyncEnabled err: " + JSON.stringify(err)); + } ``` -### setAccountCredential +### setCredential9+ -setAccountCredential(name: string, credentialType: string, credential: string,callback: AsyncCallback<void>): void +setCredential(name: string, credentialType: string, credential: string,callback: AsyncCallback<void>): void Sets a credential for an app account. This API uses an asynchronous callback to return the result. @@ -403,21 +730,37 @@ Sets a credential for an app account. This API uses an asynchronous callback to | -------------- | ------------------------- | ---- | ------------- | | name | string | Yes | Name of the target app account. | | credentialType | string | Yes | Type of the credential to set. | -| credential | string | Yes | Credential to set. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| credential | string | Yes | Credential value. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the credential is set successfully, **err** is **null**. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or credentialType or credential. | +| 12300003 | Account not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setAccountCredential("ZhangSan", "credentialType001", "credential001", (err) => { - console.log("setAccountCredential err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.setCredential("ZhangSan", "PIN_SIX", "xxxxxx", (err) => { + if (err) { + console.log("setCredential failed, error: " + JSON.stringify(err)); + } else { + console.log("setCredential successfully"); + } + }); + } catch (err) { + console.log("setCredential exception: " + JSON.stringify(err)); + } ``` -### setAccountCredential +### setCredential9+ -setAccountCredential(name: string, credentialType: string, credential: string): Promise<void> +setCredential(name: string, credentialType: string, credential: string): Promise<void> Sets a credential for an app account. This API uses a promise to return the result. @@ -429,587 +772,648 @@ Sets a credential for an app account. This API uses a promise to return the resu | -------------- | ------ | ---- | ---------- | | name | string | Yes | Name of the target app account. | | credentialType | string | Yes | Type of the credential to set.| -| credential | string | Yes | Credential to set. | +| credential | string | Yes | Credential value. | **Return value** -| Type | Description | +| Type | Description | | :------------------ | :-------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or credentialType or credential. | +| 12300003 | Account not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setAccountCredential("ZhangSan", "credentialType001", "credential001").then(() => { - console.log('setAccountCredential Success'); - }).catch((err) => { - console.log("setAccountCredential err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.setCredential("ZhangSan", "PIN_SIX", "xxxxxx").then(() => { + console.log("setCredential successfully"); + }).catch((err) => { + console.log("setCredential failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("setCredential exception: " + JSON.stringify(err)); + } ``` -### setAccountExtraInfo +### getCredential9+ -setAccountExtraInfo(name: string, extraInfo: string, callback: AsyncCallback<void>): void +getCredential(name: string, credentialType: string, callback: AsyncCallback<string>): void -Sets additional information for an app account. This API uses an asynchronous callback to return the result. +Obtains the credential of an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------------------------- | ---- | --------------- | -| name | string | Yes | Name of the target app account. | -| extraInfo | string | Yes | Additional information to set. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------------- | --------------------------- | ---- | -------------- | +| name | string | Yes | Name of the target app account. | +| credentialType | string | Yes | Type of the credential to obtain.| +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the credential obtained. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or credentialType. | +| 12300003 | Account not found. | +| 12300102 | Credential not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setAccountExtraInfo("ZhangSan", "Tk002", (err) => { - console.log("setAccountExtraInfo err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getCredential("ZhangSan", "PIN_SIX", (err, result) => { + if (err) { + console.log("getCredential failed, error: " + JSON.stringify(err)); + } else { + console.log('getCredential successfully, result: ' + result); + } + }); + } catch (err) { + console.log("getCredential err: " + JSON.stringify(err)); + } ``` -### setAccountExtraInfo +### getCredential9+ -setAccountExtraInfo(name: string, extraInfo: string): Promise<void> +getCredential(name: string, credentialType: string): Promise<string> -Sets additional information for an app account. This API uses a promise to return the result. +Obtains the credential of an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------ | ---- | --------- | -| name | string | Yes | Name of the target app account. | -| extraInfo | string | Yes | Additional information to set.| +| Name | Type | Mandatory | Description | +| -------------- | ------ | ---- | ---------- | +| name | string | Yes | Name of the target app account.| +| credentialType | string | Yes | Type of the credential to obtain.| **Return value** -| Type | Description | -| :------------------ | :-------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| :-------------------- | :-------------------- | +| Promise<string> | Promise used to return the credential obtained.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or credentialType. | +| 12300003 | Account not found. | +| 12300102 | Credential not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setAccountExtraInfo("ZhangSan", "Tk002").then(() => { - console.log('setAccountExtraInfo Success'); - }).catch((err) => { - console.log("setAccountExtraInfo err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getCredential("ZhangSan", "PIN_SIX").then((credential) => { + console.log("getCredential successfully, credential: " + credential); + }).catch((err) => { + console.log("getCredential failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("getCredential exception: " + JSON.stringify(err)); + } ``` -### setAppAccountSyncEnable - -setAppAccountSyncEnable(name: string, isEnable: boolean, callback: AsyncCallback<void>): void +### setCustomData9+ -Sets whether to enable app data synchronization for an app account. This API uses an asynchronous callback to return the result. +setCustomData(name: string, key: string, value: string, callback: AsyncCallback<void>): void -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC +Sets custom data for an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | ------------------------- | -| name | string | Yes | Name of the target app account. | -| isEnable | boolean | Yes | Whether to enable app data synchronization. | -| callback | AsyncCallback<void> | Yes | Callback invoked when app data synchronization is enabled or disabled for the app account.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----------------- | +| name | string | Yes | Name of the target app account.| +| key | string | Yes | Key of the custom data to set.| +| value | string | Yes | Value of the custom data to set.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or key or value. | +| 12300003 | Account not found. | +| 12400003 | The number of custom data reaches the upper limit. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setAppAccountSyncEnable("ZhangSan", true, (err) => { - console.log("setAppAccountSyncEnable err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.setCustomData("ZhangSan", "age", "12", (err) => { + if (err) { + console.log("setCustomData failed, error: " + JSON.stringify(err)); + } else { + console.log("setCustomData successfully"); + } + }); + } catch (err) { + console.log("setCustomData exception: " + JSON.stringify(err)); + } ``` -### setAppAccountSyncEnable - -setAppAccountSyncEnable(name: string, isEnable: boolean): Promise<void> +### setCustomData9+ -Sets whether to enable app data synchronization for an app account. This API uses a promise to return the result. +setCustomData(name: string, key: string, value: string): Promise<void> -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC +Sets custom data for an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------- | ---- | ----------- | -| name | string | Yes | Name of the target app account. | -| isEnable | boolean | Yes | Whether to enable app data synchronization.| +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------- | +| name | string | Yes | Name of the target app account. | +| key | string | Yes | Key of the custom data to set.| +| value | string | Yes | Value of the custom data to set.| **Return value** | Type | Description | | :------------------ | :-------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or key or value. | +| 12300003 | Account not found. | +| 12400003 | The number of custom data reaches the upper limit. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager .setAppAccountSyncEnable("ZhangSan", true).then(() => { - console.log('setAppAccountSyncEnable Success'); - }).catch((err) => { - console.log("setAppAccountSyncEnable err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.setCustomData("ZhangSan", "age", "12").then(() => { + console.log("setCustomData successfully"); + }).catch((err) => { + console.log("setCustomData failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("setCustomData exception: " + JSON.stringify(err)); + } ``` -### setAssociatedData +### getCustomData9+ -setAssociatedData(name: string, key: string, value: string, callback: AsyncCallback<void>): void +getCustomData(name: string, key: string, callback: AsyncCallback<string>): void -Sets data to be associated with an app account. This API uses an asynchronous callback to return the result. +Obtains the custom data of an app account based on the specified key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | ----------------- | -| name | string | Yes | Name of the target app account. | -| key | string | Yes | Key of the data to set. The private key can be customized.| -| value | string | Yes | Value of the data to be set. | -| callback | AsyncCallback<void> | Yes | Callback invoked when the data associated with the specified app account is set.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ----- | ------------------------ | +| name | string | Yes | Name of the target app account. | +| key | string | Yes | Key of the custom data to obtain. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the custom data value obtained. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or key. | +| 12300003 | Account not found. | +| 12400002 | Custom data not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setAssociatedData("ZhangSan", "k001", "v001", (err) => { - console.log("setAssociatedData err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getCustomData("ZhangSan", "age", (err, data) => { + if (err) { + console.log('getCustomData failed, error: ' + err); + } else { + console.log("getCustomData successfully, data: " + data); + } + }); + } catch (err) { + console.log("getCustomData exception: " + JSON.stringify(err)); + } ``` -### setAssociatedData +### getCustomData9+ -setAssociatedData(name: string, key: string, value: string): Promise<void> +getCustomData(name: string, key: string): Promise<string> -Sets data to be associated with an app account. This API uses a promise to return the result. +Obtains the custom data of an app account based on the specified key. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | ---- | ----------------- | -| name | string | Yes | Name of the target app account. | -| key | string | Yes | Key of the data to set. The private key can be customized.| -| value | string | Yes | Value of the data to be set. | +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | --------- | +| name | string | Yes | Name of the target app account. | +| key | string | Yes | Key of the custom data to obtain.| **Return value** -| Type | Description | -| :------------------ | :-------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| --------------------- | --------------------- | +| Promise<string> | Promise used to return the custom data value obtained.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or key. | +| 12300003 | Account not found. | +| 12400002 | Custom data not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setAssociatedData("ZhangSan", "k001", "v001").then(() => { - console.log('setAssociatedData Success'); - }).catch((err) => { - console.log("setAssociatedData err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getCustomData("ZhangSan", "age").then((data) => { + console.log("getCustomData successfully, data: " + data); + }).catch((err) => { + console.log("getCustomData failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("getCustomData exception: " + JSON.stringify(err)); + } ``` -### getAccountCredential +### getCustomDataSync9+ -getAccountCredential(name: string, credentialType: string, callback: AsyncCallback<string>): void +getCustomDataSync(name: string, key: string): string; -Obtains the credentials (such as the digital password, face image, and PIN) of an app account. This API uses an asynchronous callback to return the result. +Obtains the custom data of an app account based on the specified key. The API returns the result synchronously. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | --------------------------- | ---- | -------------- | -| name | string | Yes | Name of the target app account. | -| credentialType | string | Yes | Type of the credential to obtain.| -| callback | AsyncCallback<string> | Yes | Callback invoked to return the credential obtained.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | --------- | +| name | string | Yes | Name of the target app account. | +| key | string | Yes | Key of the custom data to obtain.| + +**Return value** + +| Type | Description | +| --------------------- | --------------------- | +| string | Value of the custom data obtained.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or key. | +| 12300003 | Account not found. | +| 12400002 | Custom data not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAccountCredential("ZhangSan", "credentialType001", (err, result) => { - console.log("getAccountCredential err: " + JSON.stringify(err)); - console.log('getAccountCredential result: ' + result); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + let value = appAccountManager.getCustomDataSync("ZhangSan", "age"); + console.info("getCustomDataSync successfully, vaue:" + value); + } catch (err) { + console.error("getCustomDataSync failed, error: " + JSON.stringify(err)); + } ``` -### getAccountCredential +### getAllAccounts9+ -getAccountCredential(name: string, credentialType: string): Promise<string> +getAllAccounts(callback: AsyncCallback<Array<AppAccountInfo>>): void -Obtains the credential of an app account. This API uses a promise to return the result. +Obtains information about all accessible app accounts. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------ | ---- | ---------- | -| name | string | Yes | Name of the target app account. | -| credentialType | string | Yes | Type of the credential to obtain.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is a list of accessible app accounts. Otherwise, **err** is an error object.| -**Return value** +**Error codes** -| Type | Description | -| :-------------------- | :-------------------- | -| Promise<string> | Promise used to return the result.| +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAccountCredential("ZhangSan", "credentialType001").then((data) => { - console.log('getAccountCredential, result: ' + data); - }).catch((err) => { - console.log("getAccountCredential err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getAllAccounts((err, data) => { + if (err) { + console.debug("getAllAccounts failed, error:" + JSON.stringify(err)); + } else { + console.debug("getAllAccounts successfully"); + } + }); + } catch (err) { + console.debug("getAllAccounts exception: " + JSON.stringify(err)); + } ``` -### getAccountExtraInfo +### getAllAccounts9+ -getAccountExtraInfo(name: string, callback: AsyncCallback<string>): void +getAllAccounts(): Promise<Array<AppAccountInfo>> + +Obtains information about all accessible app accounts. This API uses a promise to return the result. -Obtains additional information (information that can be converted into the string type) about an app account. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS **System capability**: SystemCapability.Account.AppAccount -**Parameters** +**Return value** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | ---- | --------------- | -| name | string | Yes | Name of the target app account. | -| callback | AsyncCallback<string> | Yes | Callback invoked to return the additional information of the specified app account.| +| Type | Description | +| ---------------------------------------- | --------------------- | +| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise used to return information about all accessible accounts.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAccountExtraInfo("ZhangSan", (err, result) => { - console.log("getAccountExtraInfo err: " + JSON.stringify(err)); - console.log('getAccountExtraInfo result: ' + result); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getAllAccounts().then((data) => { + console.debug("getAllAccounts successfully"); + }).catch((err) => { + console.debug("getAllAccounts failed, error:" + JSON.stringify(err)); + }); + } catch (err) { + console.debug("getAllAccounts exception: " + JSON.stringify(err)); + } ``` -### getAccountExtraInfo +### getAccountsByOwner9+ -getAccountExtraInfo(name: string): Promise<string> +getAccountsByOwner(owner: string, callback: AsyncCallback<Array<AppAccountInfo>>): void + +Obtains the app accounts that can be accessed by the invoker based on the app account owner. This API uses an asynchronous callback to return the result. -Obtains additional information of an app account. This API uses a promise to return the result. +**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ------- | -| name | string | Yes | Name of the target app account.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | +| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is null and **data** is the app account information obtained. Otherwise, **err** is an error object.| -**Return value** +**Error codes** -| Type | Description | -| :-------------------- | :-------------------- | -| Promise<string> | Promise used to return the result.| +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid owner. | +| 12400001 | Application not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAccountExtraInfo("ZhangSan").then((data) => { - console.log('getAccountExtraInfo, result: ' + data); - }).catch((err) => { - console.log("getAccountExtraInfo err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getAccountsByOwner("com.example.accountjsdemo2", (err, data) => { + if (err) { + console.debug("getAccountsByOwner failed, error:" + JSON.stringify(err)); + } else { + console.debug("getAccountsByOwner successfully, data:" + JSON.stringify(data)); + } + }); + } catch (err) { + console.debug("getAccountsByOwner exception:" + JSON.stringify(err)); + } ``` -### getAssociatedData +### getAccountsByOwner9+ -getAssociatedData(name: string, key: string, callback: AsyncCallback<string>): void +getAccountsByOwner(owner: string): Promise<Array<AppAccountInfo>> -Obtains data associated with an app account. This API uses an asynchronous callback to return the result. +Obtains the app accounts that can be accessed by the invoker based on the app account owner. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | ---- | ----------------- | -| name | string | Yes | Name of the target app account. | -| key | string | Yes | Key of the data to obtain. | -| callback | AsyncCallback<string> | Yes | Callback invoked to return the data associated with the specified app account.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ------ | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | --------------------- | +| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise used to return the app account information obtained.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid owner. | +| 12400001 | Application not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAssociatedData("ZhangSan", "k001", (err, result) => { - console.log("getAssociatedData err: " + JSON.stringify(err)); - console.log('getAssociatedData result: ' + result); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getAccountsByOwner("com.example.accountjsdemo2").then((data) => { + console.debug("getAccountsByOwner successfully, data:" + JSON.stringify(data)); + }).catch((err) => { + console.debug("getAccountsByOwner failed, error:" + JSON.stringify(err)); + }); + } catch (err) { + console.debug("getAccountsByOwner exception:" + JSON.stringify(err)); + } ``` -### getAssociatedData +### on('accountChange')9+ -getAssociatedData(name: string, key: string): Promise<string> +on(type: 'accountChange', owners: Array<string>, callback: Callback<Array<AppAccountInfo>>): void -Obtains data associated with an app account. This API uses a promise to return the result. +Subscribes to account information changes of apps. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | --------- | -| name | string | Yes | Name of the target app account. | -| key | string | Yes | Key of the data to obtain.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------ | +| type | 'accountChange' | Yes | Event type to subscribe to. The value is **'accountChange'**. An event will be reported when the account information of the target app changes.| +| owners | Array<string> | Yes | App bundle names of the account. | +| callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback invoked to return a list of app accounts whose information is changed. | -**Return value** +**Error codes** -| Type | Description | -| :-------------------- | :-------------------- | -| Promise<string> | Promise used to return the result.| +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid type or owners. | +| 12300011 | Callback has been registered. | +| 12400001 | Application not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAssociatedData("ZhangSan", "k001").then((data) => { - console.log('getAssociatedData: ' + data); - }).catch((err) => { - console.log("getAssociatedData err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + function changeOnCallback(data){ + console.log("receive change data:" + JSON.stringify(data)); + } + try{ + appAccountManager.on("accountChange", ["com.example.actsaccounttest"], changeOnCallback); + } catch(err) { + console.error("on accountChange failed, error:" + JSON.stringify(err)); + } ``` -### getAssociatedDataSync9+ +### off('accountChange')9+ -getAssociatedDataSync(name: string, key: string): string; +off(type: 'accountChange', callback?: Callback>): void -Obtains the data associated with this app account. This API returns the result synchronously. +Unsubscribes from account information changes. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | --------- | -| name | string | Yes | Name of the target app account. | -| key | string | Yes | Key of the data to obtain.| +| Name | Type | Mandatory | Description | +| -------- | -------------------------------- | ---- | ------------ | +| type | 'accountChange' | Yes | Event type to unsubscribe from. The value is **'accountChange'**. | +| callback | Callback> | No | Callback to unregister.| -**Return value** +**Error codes** -| Type | Description | -| :-------------------- | :-------------------- | -| string | Data obtained.| +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid type. | +| 12300012 | Callback has not been registered. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - var backData = appAccountManager.getAssociatedDataSync("ZhangSan", "k001"); - console.info("getAssociatedDataSync backData:" + JSON.stringify(backData)); + let appAccountManager = account_appAccount.createAppAccountManager(); + function changeOnCallback(data){ + console.log("receive change data:" + JSON.stringify(data)); + } + try{ + appAccountManager.on("accountChange", ["com.example.actsaccounttest"], changeOnCallback); + } catch(err) { + console.error("on accountChange failed, error:" + JSON.stringify(err)); + } + try{ + appAccountManager.off('accountChange', changeOnCallback); + } + catch(err){ + console.error("off accountChange failed, error:" + JSON.stringify(err)); + } ``` -### getAllAccessibleAccounts - -getAllAccessibleAccounts(callback: AsyncCallback<Array<AppAccountInfo>>): void +### auth9+ -Obtains information about all accessible app accounts. This API uses an asynchronous callback to return the result. +auth(name: string, owner: string, authType: string, callback: AuthCallback): void -**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) +Authenticates an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | --------- | -| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback invoked to return information about all accessible app accounts.| +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ---- | --------------- | +| name | string | Yes | Name of the target app account. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | +| authType | string | Yes | Authentication type. | +| callback | [AuthCallback](#authcallback9) | Yes | Callback invoked to return the authentication result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner or authType. | +| 12300003 | Account not found. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAllAccessibleAccounts((err, data)=>{ - console.debug("getAllAccessibleAccounts err:" + JSON.stringify(err)); - console.debug("getAllAccessibleAccounts data:" + JSON.stringify(data)); - }); - ``` + import featureAbility from '@ohos.ability.featureAbility'; -### getAllAccessibleAccounts + function onResultCallback(code, authResult) { + console.log("resultCode: " + code); + console.log("authResult: " + JSON.stringify(authResult)); + } -getAllAccessibleAccounts(): Promise<Array<AppAccountInfo>> + function onRequestRedirectedCallback(request) { + let abilityStartSetting = {want: request}; + featureAbility.startAbility(abilityStartSetting, (err) => { + console.log("startAbility err: " + JSON.stringify(err)); + }); + } -Obtains information about all accessible app accounts. This API uses a promise to return the result. + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.auth("LiSi", "com.example.accountjsdemo", "getSocialData", { + onResult: onResultCallback, + onRequestRedirected: onRequestRedirectedCallback + }); + } catch (err) { + console.log("auth exception: " + JSON.stringify(err)); + } + ``` -**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) +### auth9+ -**System capability**: SystemCapability.Account.AppAccount +auth(name: string, owner: string, authType: string, options: {[key: string]: Object}, callback: AuthCallback): void -**Parameters** - -| Type | Description | -| ---------------------------------------- | --------------------- | -| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise used to return the result.| - -**Example** - - ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAllAccessibleAccounts().then((data) => { - console.log('getAllAccessibleAccounts: ' + data); - }).catch((err) => { - console.log("getAllAccessibleAccounts err: " + JSON.stringify(err)); - }); - ``` - -### getAllAccounts - -getAllAccounts(owner: string, callback: AsyncCallback<Array<AppAccountInfo>>): void - -Obtains information about all app accounts of the specified app. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) - -**System capability**: SystemCapability.Account.AppAccount - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | --------- | -| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | -| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback invoked to return information about all accessible app accounts.| - -**Example** - - ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - const selfBundle = "com.example.actsgetallaaccounts"; - appAccountManager.getAllAccounts(selfBundle, (err, data)=>{ - console.debug("getAllAccounts err:" + JSON.stringify(err)); - console.debug("getAllAccounts data:" + JSON.stringify(data)); - }); - ``` - -### getAllAccounts - -getAllAccounts(owner: string): Promise<Array<AppAccountInfo>> - -Obtains information about all app accounts of the specified app. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) - -**System capability**: SystemCapability.Account.AppAccount - -**Parameters** - -| Name | Type | Mandatory | Description | -| ----- | ------ | ---- | ------ | -| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| - -**Parameters** - -| Type | Description | -| ---------------------------------------- | --------------------- | -| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise used to return the result.| - -**Example** - - ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - const selfBundle = "com.example.actsgetallaaccounts"; - appAccountManager.getAllAccounts(selfBundle).then((data) => { - console.log('getAllAccounts: ' + data); - }).catch((err) => { - console.log("getAllAccounts err: " + JSON.stringify(err)); - }); - ``` - -### on('change') - -on(type: 'change', owners: Array<string>, callback: Callback<Array<AppAccountInfo>>): void - -Subscribes to the account change events of the specified account owners. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Account.AppAccount - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ------------------------------ | -| type | 'change' | Yes | Account change events to subscribe to. The subscriber will receive a notification when the account owners update their accounts.| -| owners | Array<string> | Yes | Account owners. | -| callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback invoked to return the account changes. | - -**Example** - - ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - function changeOnCallback(data){ - console.debug("receive change data:" + JSON.stringify(data)); - } - try{ - appAccountManager.on('change', ["com.example.actsaccounttest"], changeOnCallback); - } - catch(err){ - console.error("on accountOnOffDemo err:" + JSON.stringify(err)); - } - ``` - -### off('change') - -off(type: 'change', callback?: Callback>): void - -Unsubscribes from the account change events. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Account.AppAccount - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | -------------------------------- | ---- | ------------ | -| type | 'change' | Yes | Account change events to unsubscribe from. | -| callback | Callback> | No | Callback used to report the account changes.| - -**Example** - - ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - function changeOnCallback(data){ - console.debug("receive change data:" + JSON.stringify(data)); - appAccountManager.off('change', function(){ - console.debug("off finish"); - }) - } - try{ - appAccountManager.on('change', ["com.example.actsaccounttest"], changeOnCallback); - } - catch(err){ - console.error("on accountOnOffDemo err:" + JSON.stringify(err)); - } - ``` - -### authenticate8+ - -authenticate(name: string, owner: string, authType: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void - -Authenticates an app account to obtain an Open Authorization (OAuth) token. This API uses an asynchronous callback to return the result. +Authenticates an app account with customized options. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1020,38 +1424,56 @@ Authenticates an app account to obtain an Open Authorization (OAuth) token. This | name | string | Yes | Name of the target app account. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | | authType | string | Yes | Authentication type. | -| options | {[key: string]: any} | Yes | Options for the authentication. | -| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the authentication result.| +| options | {[key: string]: Object} | Yes | Options for the authentication. | +| callback | [AuthCallback](#authcallback9) | Yes | Callback invoked to return the authentication result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner or authType. | +| 12300003 | Account not exist. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | **Example** ```js import featureAbility from '@ohos.ability.featureAbility'; - function onResultCallback(code, result) { - console.log("resultCode: " + code); - console.log("result: " + JSON.stringify(result)); + function onResultCallback(code, authResult) { + console.log("resultCode: " + code); + console.log("authResult: " + JSON.stringify(authResult)); } function onRequestRedirectedCallback(request) { - let abilityStartSetting = {want: request}; - featureAbility.startAbility(abilityStartSetting, (err)=>{ - console.log("startAbility err: " + JSON.stringify(err)); - }); + let abilityStartSetting = {want: request}; + featureAbility.startAbility(abilityStartSetting, (err) => { + console.log("startAbility err: " + JSON.stringify(err)); + }); } - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.authenticate("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", {}, { - onResult: onResultCallback, - onRequestRedirected: onRequestRedirectedCallback - }); + let options = { + "password": "xxxx", + }; + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.auth("LiSi", "com.example.accountjsdemo", "getSocialData", options, { + onResult: onResultCallback, + onRequestRedirected: onRequestRedirectedCallback + }); + } catch (err) { + console.log("auth exception: " + JSON.stringify(err)); + } ``` -### getOAuthToken8+ +### getAuthToken9+ -getOAuthToken(name: string, owner: string, authType: string, callback: AsyncCallback<string>): void +getAuthToken(name: string, owner: string, authType: string, callback: AsyncCallback<string>): void -Obtains the OAuth token of an app account based on the specified authentication type. This API uses an asynchronous callback to return the result. +Obtains the authorization token of the specified authentication type for an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1062,23 +1484,39 @@ Obtains the OAuth token of an app account based on the specified authentication | name | string | Yes | Name of the target app account. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| | authType | string | Yes | Authentication type. | -| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the authorization token value obtained. Otherwise, **err** is an error object. | + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name, owner or authType. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", (err, data) => { - console.log('getOAuthToken err: ' + JSON.stringify(err)); - console.log('getOAuthToken token: ' + data); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", (err, token) => { + if (err) { + console.log("getAuthToken failed, error: " + JSON.stringify(err)); + } else { + console.log("getAuthToken successfully, token: " + token); + } + }); + } catch (err) { + console.log("getAuthToken exception: " + JSON.stringify(err)); + } ``` -### getOAuthToken8+ +### getAuthToken9+ -getOAuthToken(name: string, owner: string, authType: string): Promise<string> +getAuthToken(name: string, owner: string, authType: string): Promise<string> -Obtains the OAuth token of an app account based on the specified authentication type. This API uses a promise to return the result. +Obtains the authorization token of the specified authentication type for an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1090,28 +1528,41 @@ Obtains the OAuth token of an app account based on the specified authentication | owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| | authType | string | Yes | Authentication type. | -**Parameters** +**Return value** -| Type | Description | +| Type | Description | | --------------------- | --------------------- | -| Promise<string> | Promise used to return the result.| +| Promise<string> | Promise used to return the authorization token obtained.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner or authType. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData").then((data) => { - console.log('getOAuthToken token: ' + data); - }).catch((err) => { - console.log("getOAuthToken err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData").then((token) => { + console.log("getAuthToken successfully, token: " + token); + }).catch((err) => { + console.log("getAuthToken failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("getAuthToken exception: " + JSON.stringify(err)); + } ``` -### setOAuthToken8+ +### setAuthToken9+ -setOAuthToken(name: string, authType: string, token: string, callback: AsyncCallback<void>): void +setAuthToken(name: string, authType: string, token: string, callback: AsyncCallback<void>): void -Sets an OAuth token for an app account. This API uses an asynchronous callback to return the result. +Sets an authorization token of the specific authentication type for an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1121,23 +1572,40 @@ Sets an OAuth token for an app account. This API uses an asynchronous callback t | -------- | ------------------------- | ---- | -------- | | name | string | Yes | Name of the target app account.| | authType | string | Yes | Authentication type. | -| token | string | Yes | OAuth token to set.| -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| +| token | string | Yes | Token to set.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or authType or token. | +| 12300003 | Account not found. | +| 12400004 | The number of token reaches the upper limit. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx", (err) => { - console.log('setOAuthToken err: ' + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.setAuthToken("LiSi", "getSocialData", "xxxx", (err) => { + if (err) { + console.log("setAuthToken failed, error: " + JSON.stringify(err)); + } else { + console.log("setAuthToken successfully"); + } + }); + } catch (err) { + console.log('setAuthToken exception: ' + JSON.stringify(err)); + } ``` -### setOAuthToken8+ +### setAuthToken9+ -setOAuthToken(name: string, authType: string, token: string): Promise<void> +setAuthToken(name: string, authType: string, token: string): Promise<void> -Sets an OAuth token for an app account. This API uses a promise to return the result. +Sets an authorization token of the specific authentication type for an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1147,30 +1615,43 @@ Sets an OAuth token for an app account. This API uses a promise to return the re | -------- | ------ | ---- | -------- | | name | string | Yes | Name of the target app account.| | authType | string | Yes | Authentication type. | -| token | string | Yes | OAuth token to set.| +| token | string | Yes | Token to set.| -**Parameters** +**Return value** | Type | Description | | ------------------- | --------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or authType or token. | +| 12300003 | Account not found. | +| 12400004 | The number of token reaches the upper limit. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx").then(() => { - console.log('setOAuthToken successfully'); - }).catch((err) => { - console.log('setOAuthToken err: ' + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.setAuthToken("LiSi", "getSocialData", "xxxx").then(() => { + console.log("setAuthToken successfully"); + }).catch((err) => { + console.log("setAuthToken failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("setAuthToken exception: " + JSON.stringify(err)); + } ``` -### deleteOAuthToken8+ +### deleteAuthToken9+ -deleteOAuthToken(name: string, owner: string, authType: string, token: string, callback: AsyncCallback<void>): void +deleteAuthToken(name: string, owner: string, authType: string, token: string, callback: AsyncCallback<void>): void -Deletes the specified OAuth token for an app account. This API uses an asynchronous callback to return the result. +Deletes the authorization token of the specified authentication type for an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1181,23 +1662,40 @@ Deletes the specified OAuth token for an app account. This API uses an asynchron | name | string | Yes | Name of the target app account. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | | authType | string | Yes | Authentication type. | -| token | string | Yes | OAuth token to delete.| -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | +| token | string | Yes | Token to delete.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object. | + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner or authType or token. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", "xxxxx", (err) => { - console.log('deleteOAuthToken err: ' + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.deleteAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", "xxxxx", (err) => { + if (err) { + console.log('deleteAuthToken failed, error: ' + JSON.stringify(err)); + } else { + console.log("deleteAuthToken successfully"); + } + }); + } catch (err) { + console.log('deleteAuthToken exception: ' + JSON.stringify(err)); + } ``` -### deleteOAuthToken8+ +### deleteAuthToken9+ -deleteOAuthToken(name: string, owner: string, authType: string, token: string): Promise<void> +deleteAuthToken(name: string, owner: string, authType: string, token: string): Promise<void> -Deletes the specified OAuth token for an app account. This API uses a promise to return the result. +Deletes the authorization token of the specified authentication type for an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1208,30 +1706,43 @@ Deletes the specified OAuth token for an app account. This API uses a promise to | name | string | Yes | Name of the target app account. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | | authType | string | Yes | Authentication type. | -| token | string | Yes | OAuth token to delete.| +| token | string | Yes | Token to delete.| -**Parameters** +**Return value** | Type | Description | | ------------------- | --------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner or authType or token. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", "xxxxx").then(() => { - console.log('deleteOAuthToken successfully'); - }).catch((err) => { - console.log("deleteOAuthToken err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.deleteAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", "xxxxx").then(() => { + console.log("deleteAuthToken successfully"); + }).catch((err) => { + console.log('deleteAuthToken failed, error: ' + JSON.stringify(err)); + }); + } catch (err) { + console.log('deleteAuthToken exception: ' + JSON.stringify(err)); + } ``` -### setOAuthTokenVisibility8+ +### setAuthTokenVisibility9+ -setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean, callback: AsyncCallback<void>): void +setAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean, callback: AsyncCallback<void>): void -Sets the visibility of an OAuth token to an app. This API uses an asynchronous callback to return the result. +Sets the visibility of an authorization token to an app. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1242,57 +1753,91 @@ Sets the visibility of an OAuth token to an app. This API uses an asynchronous c | name | string | Yes | Name of the target app account. | | authType | string | Yes | Authentication type. | | bundleName | string | Yes | Bundle name of the app. | -| isVisible | boolean | Yes | Whether the OAuth token is visible to the app. The value **true** means visible, and the value **false** means the opposite.| -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | +| isVisible | boolean | Yes | Whether the authorization token is visible to the app. The value **true** means the authorization token is visible to the app; the value **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or authType or bundleName. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | +| 12400001 | Application not found. | +| 12400005 | The size of authorization list reaches the upper limit. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", true, (err) => { - console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.setAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", true, (err) => { + if (err) { + console.log("setAuthTokenVisibility failed, error: " + JSON.stringify(err)); + } else { + console.log("setAuthTokenVisibility successfully"); + } + }); + } catch (err) { + console.log("setAuthTokenVisibility exception: " + JSON.stringify(err)); + } ``` -### setOAuthTokenVisibility8+ +### setAuthTokenVisibility9+ -setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean): Promise<void> +setAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean): Promise<void> -Sets the visibility of an OAuth token to an app. This API uses a promise to return the result. +Sets the visibility of an authorization token to an app. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------- | ---- | ------------ | -| name | string | Yes | Name of the target app account. | -| authType | string | Yes | Authentication type. | -| bundleName | string | Yes | Bundle name of the app.| -| isVisible | boolean | Yes | Whether the OAuth token is visible to the app. | +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | ---- | ------------------------- | +| name | string | Yes | Name of the target app account. | +| authType | string | Yes | Authentication type. | +| bundleName | string | Yes | Bundle name of the app. | +| isVisible | boolean | Yes | Whether the authorization token is visible to the app. The value **true** means the authorization token is visible to the app; the value **false** means the opposite.| -**Parameters** +**Return value** | Type | Description | | ------------------- | --------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or authType or bundleName. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | +| 12400001 | Application not found. | +| 12400005 | The size of authorization list reaches the upper limit. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", true).then(() => { - console.log('setOAuthTokenVisibility successfully'); - }).catch((err) => { - console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.setAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", true).then(() => { + console.log("setAuthTokenVisibility successfully"); + }).catch((err) => { + console.log("setAuthTokenVisibility failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("setAuthTokenVisibility exception: " + JSON.stringify(err)); + } ``` -### checkOAuthTokenVisibility8+ +### checkAuthTokenVisibility9+ -checkOAuthTokenVisibility(name: string, authType: string, bundleName: string, callback: AsyncCallback<boolean>): void +checkAuthTokenVisibility(name: string, authType: string, bundleName: string, callback: AsyncCallback<boolean>): void -Checks whether an OAuth token is visible to an app. This API uses an asynchronous callback to return the result. +Checks the visibility of an authorization token of the specified authentication type to an app. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1303,23 +1848,40 @@ Checks whether an OAuth token is visible to an app. This API uses an asynchronou | name | string | Yes | Name of the target app account. | | authType | string | Yes | Authentication type. | | bundleName | string | Yes | Bundle name of the app.| -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** can be **true** (the authorization token is visible to the app) or **false** (the authorization token is not visible to the app). If the operation fails, **err** is an error object. | + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or authType or bundleName. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | +| 12400001 | Application not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", (err, data) => { - console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); - console.log('checkOAuthTokenVisibility isVisible: ' + data); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.checkAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", (err, isVisible) => { + if (err) { + console.log("checkAuthTokenVisibility failed, error: " + JSON.stringify(err)); + } else { + console.log("checkAuthTokenVisibility successfully, isVisible: " + isVisible); + } + }); + } catch (err) { + console.log("checkAuthTokenVisibility exception: " + JSON.stringify(err)); + } ``` -### checkOAuthTokenVisibility8+ +### checkAuthTokenVisibility9+ -checkOAuthTokenVisibility(name: string, authType: string, bundleName: string): Promise<boolean> +checkAuthTokenVisibility(name: string, authType: string, bundleName: string): Promise<boolean> -Checks whether an OAuth token is visible to an app. This API uses a promise to return the result. +Checks the visibility of an authorization token of the specified authentication type to an app. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1331,28 +1893,42 @@ Checks whether an OAuth token is visible to an app. This API uses a promise to r | authType | string | Yes | Authentication type. | | bundleName | string | Yes | Bundle name of the app.| -**Parameters** +**Return value** | Type | Description | | ---------------------- | --------------------- | -| Promise<boolean> | Promise used to return the result.| +| Promise<boolean> | Promise used to return the result. The value **true** means the authorization token is visible to the app; the value **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or authType or bundleName. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | +| 12400001 | Application not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo").then((data) => { - console.log('checkOAuthTokenVisibility isVisible: ' + data); - }).catch((err) => { - console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.checkAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo").then((isVisible) => { + console.log("checkAuthTokenVisibility successfully, isVisible: " + isVisible); + }).catch((err) => { + console.log("checkAuthTokenVisibility failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("checkAuthTokenVisibility exception: " + JSON.stringify(err)); + } ``` -### getAllOAuthTokens8+ +### getAllAuthTokens9+ -getAllOAuthTokens(name: string, owner: string, callback: AsyncCallback<Array<OAuthTokenInfo>>): void +getAllAuthTokens(name: string, owner: string, callback: AsyncCallback<Array<AuthTokenInfo>>): void -Obtains all OAuth tokens visible to the caller for an app account. This API uses an asynchronous callback to return the result. +Obtains all tokens visible to the invoker for an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1362,23 +1938,38 @@ Obtains all OAuth tokens visible to the caller for an app account. This API uses | -------- | ---------------------------------------- | ---- | ----------- | | name | string | Yes | Name of the target app account. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| -| callback | AsyncCallback<Array< [OAuthTokenInfo](#oauthtokeninfo8)>> | Yes | Callback invoked to return the result. | +| callback | AsyncCallback<Array<[AuthTokenInfo](#authtokeninfo9)>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is a list of all tokens visible to the invoker. Otherwise, **err** is an error object. | + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner. | +| 12300003 | Account not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAllOAuthTokens("LiSi", "com.example.ohos.accountjsdemo", (err, data) => { - console.log("getAllOAuthTokens err: " + JSON.stringify(err)); - console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getAllAuthTokens("LiSi", "com.example.accountjsdemo", (err, tokenArr) => { + if (err) { + console.log("getAllAuthTokens failed, error: " + JSON.stringify(err)); + } else { + console.log('getAllAuthTokens successfully, tokenArr: ' + tokenArr); + } + }); + } catch (err) { + console.log("getAllAuthTokens exception: " + JSON.stringify(err)); + } ``` -### getAllOAuthTokens8+ +### getAllAuthTokens9+ -getAllOAuthTokens(name: string, owner: string): Promise<Array<OAuthTokenInfo>> +getAllAuthTokens(name: string, owner: string): Promise<Array<AuthTokenInfo>> -Obtains all OAuth tokens visible to the caller for an app account. This API uses a promise to return the result. +Obtains all tokens visible to the invoker for an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1389,584 +1980,2519 @@ Obtains all OAuth tokens visible to the caller for an app account. This API uses | name | string | Yes | Name of the target app account. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| -**Parameters** +**Return value** | Type | Description | | ---------------------------------------- | --------------------- | -| Promise<Array< [OAuthTokenInfo](#oauthtokeninfo8)>> | Promise used to return the result.| +| Promise<Array<[AuthTokenInfo](#authtokeninfo9)>> | Promise used to return the tokens obtained.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner. | +| 12300003 | Account not found. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getAllAuthTokens("LiSi", "com.example.accountjsdemo").then((tokenArr) => { + console.log('getAllAuthTokens successfully, tokenArr: ' + JSON.stringify(tokenArr)); + }).catch((err) => { + console.log("getAllAuthTokens failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("getAllAuthTokens exception: " + JSON.stringify(err)); + } + ``` + +### getAuthList9+ + +getAuthList(name: string, authType: string, callback: AsyncCallback<Array<string>>): void + +Obtains the authorization list of the specified authentication type for an app account. The authorization list contains all authorized bundles. The token authorization list is set by [setAuthTokenVisibility](#setauthtokenvisibility9). This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------------- | +| name | string | Yes | Name of the target app account. | +| authType | string | Yes | Authentication type.| +| callback | AsyncCallback<Array<string>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is a list of authorized bundles obtained. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or authType. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getAuthList("com.example.accountjsdemo", "getSocialData", (err, authList) => { + if (err) { + console.log("getAuthList failed, error: " + JSON.stringify(err)); + } else { + console.log("getAuthList successfully, authList: " + authList); + } + }); + } catch (err) { + console.log('getAuthList exception: ' + JSON.stringify(err)); + } + ``` + +### getAuthList9+ + +getAuthList(name: string, authType: string): Promise<Array<string>> + +Obtains the authorization list of the specified authentication type for an app account. The authorization list contains all authorized bundles. The token authorization list is set by [setAuthTokenVisibility](#setauthtokenvisibility9). This API uses a promise to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ------------------------------ | +| name | string | Yes | Name of the target app account. | +| authType | string | Yes | Authentication type.| + +**Return value** + +| Type | Description | +| ---------------------------------- | --------------------- | +| Promise<Array<string>> | Promise used to return a list of authorized bundles.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or authType. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getAuthList("com.example.accountjsdemo", "getSocialData").then((authList) => { + console.log("getAuthList successfully, authList: " + authList); + }).catch((err) => { + console.log("getAuthList failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("getAuthList exception: " + JSON.stringify(err)); + } + ``` + +### getAuthCallback9+ + +getAuthCallback(sessionId: string, callback: AsyncCallback<AuthCallback>): void + +Obtains the authenticator callback for the authentication session. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------- | +| sessionId | string | Yes | ID of the authentication session.| +| callback | AsyncCallback<[AuthCallback](#authcallback9)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the authenticator callback object obtained. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid sessionId. | +| 12300108 | Session not found. | + +**Example** + + ```js + import featureAbility from '@ohos.ability.featureAbility'; + let appAccountManager = account_appAccount.createAppAccountManager(); + featureAbility.getWant((err, want) => { + var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; + try { + appAccountManager.getAuthCallback(sessionId, (err, callback) => { + if (err.code != account_appAccount.ResultCode.SUCCESS) { + console.log("getAuthCallback err: " + JSON.stringify(err)); + return; + } + var result = { + accountInfo: { + name: "Lisi", + owner: "com.example.accountjsdemo", + }, + tokenInfo: { + token: "xxxxxx", + authType: "getSocialData" + } + }; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + }); + } catch (err) { + console.log("getAuthCallback exception: " + JSON.stringify(err)); + } + }); + ``` + +### getAuthCallback9+ + +getAuthCallback(sessionId: string): Promise<AuthCallback> + +Obtains the authenticator callback for the authentication session. This API uses a promise to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | -------- | +| sessionId | string | Yes | ID of the authentication session.| + +**Return value** + +| Type | Description | +| ------------------------------------ | --------------------- | +| Promise<[AuthCallback](#authcallback9)> | Promise used to return the authenticator callback obtained.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid sessionId. | +| 12300108 | Session not found. | + +**Example** + + ```js + import featureAbility from '@ohos.ability.featureAbility'; + + let appAccountManager = account_appAccount.createAppAccountManager(); + featureAbility.getWant().then((want) => { + var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; + try { + appAccountManager.getAuthCallback(sessionId).then((callback) => { + var result = { + accountInfo: { + name: "Lisi", + owner: "com.example.accountjsdemo", + }, + tokenInfo: { + token: "xxxxxx", + authType: "getSocialData" + } + }; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + }).catch((err) => { + console.log("getAuthCallback err: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("getAuthCallback exception: " + JSON.stringify(err)); + } + }).catch((err) => { + console.log("getWant err: " + JSON.stringify(err)); + }); + ``` + +### queryAuthenticatorInfo9+ + +queryAuthenticatorInfo(owner: string, callback: AsyncCallback<AuthenticatorInfo>): void + +Obtains the authenticator information of an app. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------------------------------------- | ---- | ----------- | +| owner | string | Yes | Bundle name of the app.| +| callback | AsyncCallback<[AuthenticatorInfo](#authenticatorinfo8)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the authenticator information obtained. Otherwise, **err** is an error object. | + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid owner. | +| 12300113 | Authenticator service not found. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.queryAuthenticatorInfo("com.example.accountjsdemo", (err, info) => { + if (err) { + console.log("queryAuthenticatorInfo failed, error: " + JSON.stringify(err)); + } else { + console.log('queryAuthenticatorInfo successfully, info: ' + JSON.stringify(info)); + } + }); + } catch (err) { + console.log("queryAuthenticatorInfo exception: " + JSON.stringify(err)); + } + ``` + +### queryAuthenticatorInfo9+ + +queryAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo> + +Obtains the authenticator information of an app. This API uses a promise to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------- | +| owner | string | Yes | Bundle name of the app.| + +**Return value** + +| Type | Description | +| -------------------------------- | --------------------- | +| Promise<[AuthenticatorInfo](#authenticatorinfo8)> | Promise used to return the authenticator information obtained.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid owner. | +| 12300113 | Authenticator service not found. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.queryAuthenticatorInfo("com.example.accountjsdemo").then((info) => { + console.log("queryAuthenticatorInfo successfully, info: " + JSON.stringify(info)); + }).catch((err) => { + console.log("queryAuthenticatorInfo failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("queryAuthenticatorInfo exception: " + JSON.stringify(err)); + } + ``` + +### checkAccountLabels9+ + +checkAccountLabels(name: string, owner: string, labels: Array<string>, callback: AsyncCallback<boolean>): void; + +Checks whether an app account has specific labels. This API uses an asynchronous callback to return the result. The labels are checked by the authenticator of the target app. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------------------------- | ----- | --------------- | +| name | string | Yes | Name of the target app account. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| +| labels | Array<string> | Yes | Labels to check. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** can be **true** or **false**. The value **true** means the app account has the labels; the value **false** means the opposite. If the operation fails, **err** is an error object. | + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner or labels. | +| 12300003 | Account not found. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + let labels = ["student"]; + try { + appAccountManager.checkAccountLabels("zhangsan", "com.example.accountjsdemo", labels, (err, hasAllLabels) => { + if (err) { + console.log("checkAccountLabels failed, error: " + JSON.stringify(err)); + } else { + console.log("checkAccountLabels successfully, hasAllLabels: " + hasAllLabels); + } + }); + } catch (err) { + console.log("checkAccountLabels exception: " + JSON.stringify(err)); + } + ``` + +### checkAccountLabels9+ + +checkAccountLabels(name: string, owner: string, labels: Array<string>): Promise<boolean> + +Checks whether an app account has specific labels. This API uses a promise to return the result. The labels are checked by the authenticator of the target app. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------------------------- | ----- | --------------- | +| name | string | Yes | Name of the target app account. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| +| labels | Array<string> | Yes | Labels to check. | + +**Return value** + +| Type | Description | +| ------------------- | -------------------------------- | +| Promise<boolean> | Promise used to return the result. The value **true** means the app account has the labels; the value **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner or labels. | +| 12300003 | Account not found. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + let labels = ["student"]; + try { + appAccountManager.checkAccountLabels("zhangsan", "com.example.accountjsdemo", labels).then((hasAllLabels) => { + console.log('checkAccountLabels successfully: ' + hasAllLabels); + }).catch((err) => { + console.log("checkAccountLabels failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("checkAccountLabels exception: " + JSON.stringify(err)); + } + ``` + +### deleteCredential9+ + +deleteCredential(name: string, credentialType: string, callback: AsyncCallback<void>): void + +Deletes the credential of the specified type from an app account. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------------------------- | ----- | -------------- | +| name | string | Yes | Name of the target app account.| +| credentialType | string | Yes | Type of the credential to delete. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or credentialType. | +| 12300003 | Account not found. | +| 12300102 | Credential not found. | **Example** - ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAllOAuthTokens("LiSi", "com.example.ohos.accountjsdemo").then((data) => { - console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); - }).catch((err) => { - console.log("getAllOAuthTokens err: " + JSON.stringify(err)); + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.deleteCredential("zhangsan", "PIN_SIX", (err) => { + if (err) { + console.log("deleteCredential failed, error: " + JSON.stringify(err)); + } else { + console.log("deleteCredential successfully"); + } + }); + } catch (err) { + console.log("deleteCredential exception: " + JSON.stringify(err)); + } + ``` + +### deleteCredential9+ + +deleteCredential(name: string, credentialType: string): Promise<void> + +Deletes the credential of the specified type from an app account. This API uses a promise to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------ | ----- | --------------- | +| name | string | Yes | Name of the target app account.| +| credentialType | string | Yes | Type of the credential to delete. | + +**Return value** + +| Type | Description | +| ------------------- | -------------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or credentialType. | +| 12300003 | Account not found. | +| 12300102 | Credential not found. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.deleteCredential("zhangsan", "PIN_SIX").then(() => { + console.log("deleteCredential successfully"); + }).catch((err) => { + console.log("deleteCredential failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("deleteCredential exception: " + JSON.stringify(err)); + } + ``` + +### selectAccountsByOptions9+ + +selectAccountsByOptions(options: SelectAccountsOptions, callback: AsyncCallback<Array<AppAccountInfo>>): void + +Selects the accounts that can be accessed by the invoker based on the options. This API uses an asynchronous callback to return the result. If the options contain label constraints, the authenticator of the target app provides the capability of checking the labels. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ----------------------------------- | ----- | --------------- | +| options | SelectAccountsOptions | Yes | Options for selecting accounts. | +| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is a list of accounts selected. Otherwise, **err** is an error object. | + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid options. | +| 12300010 | Account service busy. | +| 12300114 | Authenticator service exception. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + let options = { + allowedOwners: [ "com.example.accountjsdemo" ], + requiredLabels: [ "student" ] + }; + try { + appAccountManager.selectAccountsByOptions(options, (err, accountArr) => { + if (err) { + console.log("selectAccountsByOptions failed, error: " + JSON.stringify(err)); + } else { + console.log("selectAccountsByOptions successfully, accountArr: " + JSON.stringify(accountArr)); + } + }); + } catch (err) { + console.log("selectAccountsByOptions exception: " + JSON.stringify(err)); + } + ``` + +### selectAccountsByOptions9+ + +selectAccountsByOptions(options: SelectAccountsOptions): Promise<Array<AppAccountInfo>> + +Selects the accounts that can be accessed by the invoker based on the options. This API uses a promise to return the result. If the options contain label constraints, the authenticator of the target app provides the capability of checking the labels. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------------------------- | ----- | --------------- | +| options | [SelectAccountsOptions](#selectaccountsoptions9) | Yes | Options for selecting accounts. | + +**Return value** + +| Type | Description | +| ------------------- | -------------------------------- | +| Promise<[AppAccountInfo](#appaccountinfo)> | Promise used to return the accounts selected.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid options. | +| 12300010 | Account service busy. | +| 12300114 | Authenticator service exception. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + let options = { + allowedOwners: ["com.example.accountjsdemo"] + }; + try { + appAccountManager.selectAccountsByOptions(options).then((accountArr) => { + console.log("selectAccountsByOptions successfully, accountArr: " + JSON.stringify(accountArr)); + }).catch((err) => { + console.log("selectAccountsByOptions failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("selectAccountsByOptions exception: " + JSON.stringify(err)); + } + ``` + +### verifyCredential9+ + +verifyCredential(name: string, owner: string, callback: AuthCallback): void; + +Verifies the credential of an app account. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ----- | ----------------------- | +| name | string | Yes | Name of the target app account. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | +| callback | [AuthCallback](#authcallback9) | Yes | Callback invoked to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner. | +| 12300003 | Account not found. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.verifyCredential("zhangsan", "com.example.accountjsdemo", { + onResult: (resultCode, result) => { + console.log("verifyCredential onResult, resultCode:" + JSON.stringify(resultCode)); + console.log("verifyCredential onResult, result:" + JSON.stringify(result)); + }, + onRequestRedirected: (request) => { + console.log("verifyCredential onRequestRedirected, request:" + JSON.stringify(request)); + } + }); + } catch (err) { + console.log("verifyCredential err: " + JSON.stringify(err)); + } + ``` + +### verifyCredential9+ + +verifyCredential(name: string, owner: string, options: VerifyCredentialOptions, callback: AuthCallback): void; + +Verifies the user credential. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------- | ----- | ----------------------- | +| name | string | Yes | Name of the target app account. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | +| options | [VerifyCredentialOptions](#verifycredentialoptions9) | Yes | Options for verifying the user credential. | +| callback | [AuthCallback](#authcallback9) | Yes | Callback invoked to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner or options. | +| 12300003 | Account not found. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + let options = { + credentialType: "pin", + credential: "123456" + }; + try { + appAccountManager.verifyCredential("zhangsan", "com.example.accountjsdemo", options, { + onResult: (resultCode, result) => { + console.log("verifyCredential onResult, resultCode:" + JSON.stringify(resultCode)); + console.log("verifyCredential onResult, result:" + JSON.stringify(result)); + }, + onRequestRedirected: (request) => { + console.log("verifyCredential onRequestRedirected, request:" + JSON.stringify(request)); + } + }); + } catch (err) { + console.log("verifyCredential err: " + JSON.stringify(err)); + } + ``` + +### setAuthenticatorProperties9+ + +setAuthenticatorProperties(owner: string, callback: AuthCallback): void; + +Sets the authenticator attributes of an app. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ----- | ----------------------- | +| owner | string | Yes | Owner of the authenticator. | +| callback | [AuthCallback](#authcallback9) | Yes | Callback invoked to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid owner. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.setAuthenticatorProperties("com.example.accountjsdemo", { + onResult: (resultCode, result) => { + console.log("setAuthenticatorProperties onResult, resultCode:" + JSON.stringify(resultCode)); + console.log("setAuthenticatorProperties onResult, result:" + JSON.stringify(result)); + }, + onRequestRedirected: (request) => { + console.log("setAuthenticatorProperties onRequestRedirected, request:" + JSON.stringify(request)); + } + }); + } catch (err) { + console.log("setAuthenticatorProperties err: " + JSON.stringify(err)); + } + ``` + +### setAuthenticatorProperties9+ + +setAuthenticatorProperties(owner: string, options: SetPropertiesOptions, callback: AuthCallback): void; + +Set authenticator properties. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ----- | ----------------------- | +| owner | string | Yes | Owner of the authenticator. | +| options | [SetPropertiesOptions](#setpropertiesoptions9) | Yes | Authenticator properties to set. | +| callback | [AuthCallback](#authcallback9) | Yes | Authenticator callback invoked to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid owner or options. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + let options = { + properties: {"prop1": "value1"} + }; + try { + appAccountManager.setAuthenticatorProperties("com.example.accountjsdemo", options, { + onResult: (resultCode, result) => { + console.log("setAuthenticatorProperties onResult, resultCode:" + JSON.stringify(resultCode)); + console.log("setAuthenticatorProperties onResult, result:" + JSON.stringify(result)); + }, + onRequestRedirected: (request) => { + console.log("setAuthenticatorProperties onRequestRedirected, request:" + JSON.stringify(request)); + } + }); + } catch (err) { + console.log("setAuthenticatorProperties err: " + JSON.stringify(err)); + } + + ``` + +### addAccount(deprecated) + +addAccount(name: string, callback: AsyncCallback<void>): void + +Adds an app account. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +>This API is supported since API version 7 and deprecated since API version 9. You are advised to use [createAccount](#createaccount9). + + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | -------------------- | +| name | string | Yes | Name of the target app account. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.addAccount("WangWu", (err) => { + console.log("addAccount err: " + JSON.stringify(err)); + }); + ``` + +### addAccount(deprecated) + +addAccount(name: string, extraInfo: string, callback: AsyncCallback<void>): void + +Adds an app account name and additional information. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [createAccount](#createaccount9-1). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| name | string | Yes | Name of the target app account. | +| extraInfo | string | Yes | Additional information (information that can be converted to the string type). It cannot contain sensitive information, such as the app account password and token.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.addAccount("LiSi", "token101", (err) => { + console.log("addAccount err: " + JSON.stringify(err)); + }); + ``` + +### addAccount(deprecated) + +addAccount(name: string, extraInfo?: string): Promise<void> + +Adds an app account name and additional information. This API uses an asynchronous callback to return the result. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [createAccount](#createaccount9-2). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | ---------------------------------------- | +| name | string | Yes | Name of the target app account. | +| extraInfo | string | No | Additional information (information that can be converted to the string type). It cannot contain sensitive information, such as the app account password and token.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.addAccount("LiSi", "token101").then(()=> { + console.log('addAccount Success'); + }).catch((err) => { + console.log("addAccount err: " + JSON.stringify(err)); + }); + ``` + +### addAccountImplicitly(deprecated) + +addAccountImplicitly(owner: string, authType: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void + +Adds an app account implicitly based on the specified owner. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [createAccountImplicitly](#createaccountimplicitly9). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ---- | ----------------------- | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | +| authType | string | Yes | Authentication type. The authentication type is customized. | +| options | {[key: string]: any} | Yes | Authentication options, which can be set as required.| +| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | Yes | Authenticator callback invoked to return the result. | + +**Example** + + ```js + import featureAbility from '@ohos.ability.featureAbility'; + + function onResultCallback(code, result) { + console.log("resultCode: " + code); + console.log("result: " + JSON.stringify(result)); + } + + function onRequestRedirectedCallback(request) { + let abilityStartSetting = {want: request}; + featureAbility.startAbility(abilityStartSetting, (err)=>{ + console.log("startAbility err: " + JSON.stringify(err)); + }); + } + + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.addAccountImplicitly("com.example.accountjsdemo", "getSocialData", {}, { + onResult: onResultCallback, + onRequestRedirected: onRequestRedirectedCallback + }); + ``` + +### deleteAccount(deprecated) + +deleteAccount(name: string, callback: AsyncCallback<void>): void + +Deletes an app account. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [removeAccount](#removeaccount9). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ---------------- | +| name | string | Yes | Name of the target app account. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.deleteAccount("ZhaoLiu", (err) => { + console.log("deleteAccount err: " + JSON.stringify(err)); + }); + ``` + +### deleteAccount(deprecated) + +deleteAccount(name: string): Promise<void> + +Deletes an app account. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [removeAccount](#removeaccount9). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----------- | +| name | string | Yes | Name of the target app account.| + +**Return value** + +| Type | Description | +| :------------------ | :-------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.deleteAccount("ZhaoLiu").then(() => { + console.log('deleteAccount Success'); + }).catch((err) => { + console.log("deleteAccount err: " + JSON.stringify(err)); + }); + ``` +### disableAppAccess(deprecated) + +disableAppAccess(name: string, bundleName: string, callback: AsyncCallback<void>): void + +Disables an app account from accessing an app. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setAppAccess](#setappaccess9). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | ---- | --------------------------------- | +| name | string | Yes | Name of the target app account. | +| bundleName | string | Yes | Bundle name of the app. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.disableAppAccess("ZhangSan", "com.example.accountjsdemo", (err) => { + console.log("disableAppAccess err: " + JSON.stringify(err)); + }); + ``` + +### disableAppAccess(deprecated) + +disableAppAccess(name: string, bundleName: string): Promise<void> + +Disables an app account from accessing an app. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setAppAccess](#setappaccess9-1). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | ---------------- | +| name | string | Yes | Name of the target app account.| +| bundleName | string | Yes | Bundle name of the app. | + +**Return value** + +| Type | Description | +| :------------------ | :-------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.disableAppAccess("ZhangSan", "com.example.accountjsdemo").then(() => { + console.log('disableAppAccess Success'); + }).catch((err) => { + console.log("disableAppAccess err: " + JSON.stringify(err)); + }); + ``` + +### enableAppAccess(deprecated) + +enableAppAccess(name: string, bundleName: string, callback: AsyncCallback<void>): void + +Enables an app account to access an app. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setAppAccess](#setappaccess9). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | ---- | --------------------------------- | +| name | string | Yes | Name of the target app account. | +| bundleName | string | Yes | Bundle name of the app. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.enableAppAccess("ZhangSan", "com.example.accountjsdemo", (err) => { + console.log("enableAppAccess: " + JSON.stringify(err)); + }); + ``` + +### enableAppAccess(deprecated) + +enableAppAccess(name: string, bundleName: string): Promise<void> + +Enables an app account to access an app. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setAppAccess](#setappaccess9-1). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | --------- | +| name | string | Yes | Name of the target app account. | +| bundleName | string | Yes | Bundle name of the app.| + +**Return value** + +| Type | Description | +| :------------------ | :-------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.enableAppAccess("ZhangSan", "com.example.accountjsdemo").then(() => { + console.log('enableAppAccess Success'); + }).catch((err) => { + console.log("enableAppAccess err: " + JSON.stringify(err)); + }); + ``` + +### checkAppAccountSyncEnable(deprecated) + +checkAppAccountSyncEnable(name: string, callback: AsyncCallback<boolean>): void + +Checks whether data synchronization is enabled for an app account. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [checkDataSyncEnabled](#checkdatasyncenabled9). + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | ---- | --------------------- | +| name | string | Yes | Name of the target app account. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means data synchronization is enabled for the app account; the value **false** means the opposite.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.checkAppAccountSyncEnable("ZhangSan", (err, result) => { + console.log("checkAppAccountSyncEnable err: " + JSON.stringify(err)); + console.log('checkAppAccountSyncEnable result: ' + result); + }); + ``` + +### checkAppAccountSyncEnable(deprecated) + +checkAppAccountSyncEnable(name: string): Promise<boolean> + +Checks whether data synchronization is enabled for an app account. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [checkDataSyncEnabled](#checkdatasyncenabled9-1). + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------- | +| name | string | Yes | Name of the target app account.| + +**Return value** + +| Type | Description | +| ---------------------- | --------------------- | +| Promise<boolean> | Promise used to return the result. The value **true** means data synchronization is enabled for the app account; the value **false** means the opposite.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.checkAppAccountSyncEnable("ZhangSan").then((data) => { + console.log('checkAppAccountSyncEnable, result: ' + data); + }).catch((err) => { + console.log("checkAppAccountSyncEnable err: " + JSON.stringify(err)); + }); + ``` + +### setAccountCredential(deprecated) + +setAccountCredential(name: string, credentialType: string, credential: string,callback: AsyncCallback<void>): void + +Set credentials for an app account. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCredential](#setcredential9). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------------------------- | ---- | ------------- | +| name | string | Yes | Name of the target app account. | +| credentialType | string | Yes | Type of the credential to set. | +| credential | string | Yes | Credential value. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setAccountCredential("ZhangSan", "credentialType001", "credential001", (err) => { + console.log("setAccountCredential err: " + JSON.stringify(err)); + }); + ``` + +### setAccountCredential(deprecated) + +setAccountCredential(name: string, credentialType: string, credential: string): Promise<void> + +Set credentials for an app account. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCredential](#setcredential9-1). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------ | ---- | ---------- | +| name | string | Yes | Name of the target app account. | +| credentialType | string | Yes | Type of the credential to set.| +| credential | string | Yes | Credential value.| + +**Return value** + +| Type | Description | +| :------------------ | :-------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setAccountCredential("ZhangSan", "credentialType001", "credential001").then(() => { + console.log('setAccountCredential Success'); + }).catch((err) => { + console.log("setAccountCredential err: " + JSON.stringify(err)); + }); + ``` + +### setAccountExtraInfo(deprecated) + +setAccountExtraInfo(name: string, extraInfo: string, callback: AsyncCallback<void>): void + +Sets additional information for an app account. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCustomData](#setcustomdata9). + + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | --------------- | +| name | string | Yes | Name of the target app account. | +| extraInfo | string | Yes | Additional information (information that can be converted to the string type). It cannot contain sensitive information, such as the app account password and token. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setAccountExtraInfo("ZhangSan", "Tk002", (err) => { + console.log("setAccountExtraInfo err: " + JSON.stringify(err)); + }); + ``` + +### setAccountExtraInfo(deprecated) + +setAccountExtraInfo(name: string, extraInfo: string): Promise<void> + +Sets additional information for an app account. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCustomData](#setcustomdata9-1). + + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | --------- | +| name | string | Yes | Name of the target app account. | +| extraInfo | string | Yes | Additional information (information that can be converted to the string type). It cannot contain sensitive information, such as the app account password and token.| + +**Return value** + +| Type | Description | +| :------------------ | :-------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setAccountExtraInfo("ZhangSan", "Tk002").then(() => { + console.log('setAccountExtraInfo Success'); + }).catch((err) => { + console.log("setAccountExtraInfo err: " + JSON.stringify(err)); + }); + ``` + +### setAppAccountSyncEnable(deprecated) + +setAppAccountSyncEnable(name: string, isEnable: boolean, callback: AsyncCallback<void>): void + +Sets data synchronization for an app account. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setDataSyncEnabled](#setdatasyncenabled9). + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ------------------------- | +| name | string | Yes | Name of the target app account. | +| isEnable | boolean | Yes | Whether to enable data synchronization. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setAppAccountSyncEnable("ZhangSan", true, (err) => { + console.log("setAppAccountSyncEnable err: " + JSON.stringify(err)); + }); + ``` + +### setAppAccountSyncEnable(deprecated) + +setAppAccountSyncEnable(name: string, isEnable: boolean): Promise<void> + +Sets data synchronization for an app account. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setDataSyncEnabled](#setdatasyncenabled9-1). + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------- | ---- | ----------- | +| name | string | Yes | Name of the target app account. | +| isEnable | boolean | Yes | Whether to enable data synchronization.| + +**Return value** + +| Type | Description | +| :------------------ | :-------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager .setAppAccountSyncEnable("ZhangSan", true).then(() => { + console.log('setAppAccountSyncEnable Success'); + }).catch((err) => { + console.log("setAppAccountSyncEnable err: " + JSON.stringify(err)); + }); + ``` + +### setAssociatedData(deprecated) + +setAssociatedData(name: string, key: string, value: string, callback: AsyncCallback<void>): void + +Sets data to be associated with an app account. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCustomData](#setcustomdata9). + + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----------------- | +| name | string | Yes | Name of the target app account. | +| key | string | Yes | Key of the data to set.| +| value | string | Yes | Value of the data to set. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setAssociatedData("ZhangSan", "k001", "v001", (err) => { + console.log("setAssociatedData err: " + JSON.stringify(err)); + }); + ``` + +### setAssociatedData(deprecated) + +setAssociatedData(name: string, key: string, value: string): Promise<void> + +Sets data to be associated with an app account. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCustomData](#setcustomdata9-1). + + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------------- | +| name | string | Yes | Name of the target app account. | +| key | string | Yes | Key of the data to set.| +| value | string | Yes | Value of the data to set.| + +**Return value** + +| Type | Description | +| :------------------ | :-------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setAssociatedData("ZhangSan", "k001", "v001").then(() => { + console.log('setAssociatedData Success'); + }).catch((err) => { + console.log("setAssociatedData err: " + JSON.stringify(err)); + }); + ``` + +### getAllAccessibleAccounts(deprecated) + +getAllAccessibleAccounts(callback: AsyncCallback<Array<AppAccountInfo>>): void + +Obtains information about all accessible app accounts. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getAllAccounts](#getallaccounts9). + +**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is a list of accessible app accounts. Otherwise, **err** is an error object.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAllAccessibleAccounts((err, data)=>{ + console.debug("getAllAccessibleAccounts err:" + JSON.stringify(err)); + console.debug("getAllAccessibleAccounts data:" + JSON.stringify(data)); + }); + ``` + +### getAllAccessibleAccounts(deprecated) + +getAllAccessibleAccounts(): Promise<Array<AppAccountInfo>> + +Obtains information about all accessible app accounts. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getAllAccounts](#getallaccounts9-1). + +**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS + +**System capability**: SystemCapability.Account.AppAccount + +**Return value** + +| Type | Description | +| ---------------------------------------- | --------------------- | +| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise used to return the accessible app accounts.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAllAccessibleAccounts().then((data) => { + console.log('getAllAccessibleAccounts: ' + data); + }).catch((err) => { + console.log("getAllAccessibleAccounts err: " + JSON.stringify(err)); + }); + ``` + +### getAllAccounts(deprecated) + +getAllAccounts(owner: string, callback: AsyncCallback<Array<AppAccountInfo>>): void + +Obtains the app accounts that can be accessed by the invoker based on the app account owner. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getAccountsByOwner](#getaccountsbyowner9). + +**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | +| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback invoked to return information about all accessible app accounts.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + const selfBundle = "com.example.actsgetallaaccounts"; + appAccountManager.getAllAccounts(selfBundle, (err, data)=>{ + console.debug("getAllAccounts err:" + JSON.stringify(err)); + console.debug("getAllAccounts data:" + JSON.stringify(data)); + }); + ``` + +### getAllAccounts(deprecated) + +getAllAccounts(owner: string): Promise<Array<AppAccountInfo>> + +Obtains the app accounts that can be accessed by the invoker based on the app account owner. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getAccountsByOwner](#getaccountsbyowner9-1). + +**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ------ | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | --------------------- | +| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise use to return the app accounts that can be accessed by the invoker.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + const selfBundle = "com.example.actsgetallaaccounts"; + appAccountManager.getAllAccounts(selfBundle).then((data) => { + console.log('getAllAccounts: ' + data); + }).catch((err) => { + console.log("getAllAccounts err: " + JSON.stringify(err)); + }); + ``` + +### getAccountCredential(deprecated) + +getAccountCredential(name: string, credentialType: string, callback: AsyncCallback<string>): void + +Obtains the credential of an app account. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getCredential](#getcredential9). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | --------------------------- | ---- | -------------- | +| name | string | Yes | Name of the target app account. | +| credentialType | string | Yes | Type of the credential to obtain.| +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the credential obtained. Otherwise, **err** is an error object.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAccountCredential("ZhangSan", "credentialType001", (err, result) => { + console.log("getAccountCredential err: " + JSON.stringify(err)); + console.log('getAccountCredential result: ' + result); + }); + ``` + +### getAccountCredential(deprecated) + +getAccountCredential(name: string, credentialType: string): Promise<string> + +Obtains the credential of an app account. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getCredential](#getcredential9-1). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------ | ---- | ---------- | +| name | string | Yes | Name of the target app account. | +| credentialType | string | Yes | Type of the credential to obtain.| + +**Return value** + +| Type | Description | +| :-------------------- | :-------------------- | +| Promise<string> | Promise used to return the credential obtained.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAccountCredential("ZhangSan", "credentialType001").then((data) => { + console.log('getAccountCredential, result: ' + data); + }).catch((err) => { + console.log("getAccountCredential err: " + JSON.stringify(err)); + }); + ``` + +### getAccountExtraInfo(deprecated) + +getAccountExtraInfo(name: string, callback: AsyncCallback<string>): void + +Obtains additional information of an app account. Additional information refers to other information that can be converted to the string type. It cannot contain sensitive information, such as the app account password and token. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getCustomData](#getcustomdata9). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | --------------- | +| name | string | Yes | Name of the target app account. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the additional information obtained. Otherwise, **err** is an error object.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAccountExtraInfo("ZhangSan", (err, result) => { + console.log("getAccountExtraInfo err: " + JSON.stringify(err)); + console.log('getAccountExtraInfo result: ' + result); + }); + ``` + +### getAccountExtraInfo(deprecated) + +getAccountExtraInfo(name: string): Promise<string> + +Obtains additional information of an app account. Additional information refers to other information that can be converted to the string type. It cannot contain sensitive information, such as the app account password and token. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getCustomData](#getcustomdata9-1). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------- | +| name | string | Yes | Name of the target app account.| + +**Return value** + +| Type | Description | +| :-------------------- | :-------------------- | +| Promise<string> | Promise used to return the additional information obtained.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAccountExtraInfo("ZhangSan").then((data) => { + console.log('getAccountExtraInfo, result: ' + data); + }).catch((err) => { + console.log("getAccountExtraInfo err: " + JSON.stringify(err)); + }); + ``` + +### getAssociatedData(deprecated) + +getAssociatedData(name: string, key: string, callback: AsyncCallback<string>): void + +Obtains data associated with an app account. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getCustomData](#getcustomdata9). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ----------------- | +| name | string | Yes | Name of the target app account. | +| key | string | Yes | Key of the data to obtain. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the data obtained. Otherwise, **err** is an error object.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAssociatedData("ZhangSan", "k001", (err, result) => { + console.log("getAssociatedData err: " + JSON.stringify(err)); + console.log('getAssociatedData result: ' + result); + }); + ``` + +### getAssociatedData(deprecated) + +getAssociatedData(name: string, key: string): Promise<string> + +Obtains data associated with an app account. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getCustomData](#getcustomdata9-1). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | --------- | +| name | string | Yes | Name of the target app account. | +| key | string | Yes | Key of the data to obtain.| + +**Return value** + +| Type | Description | +| :-------------------- | :-------------------- | +| Promise<string> | Promise used to return the data obtained.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAssociatedData("ZhangSan", "k001").then((data) => { + console.log('getAssociatedData: ' + data); + }).catch((err) => { + console.log("getAssociatedData err: " + JSON.stringify(err)); + }); + ``` + +### on('change')(deprecated) + +on(type: 'change', owners: Array<string>, callback: Callback<Array<AppAccountInfo>>): void + +Subscribes to account information changes of apps. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [on('accountChange')](#onaccountchange9). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------ | +| type | 'change' | Yes | Event type to subscribe to. The value is **'change'**. An event will be reported when the account information changes.| +| owners | Array<string> | Yes | App bundle names of the account. | +| callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback invoked to return the account changes. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + function changeOnCallback(data){ + console.debug("receive change data:" + JSON.stringify(data)); + } + try{ + appAccountManager.on('change', ["com.example.actsaccounttest"], changeOnCallback); + } + catch(err){ + console.error("on accountOnOffDemo err:" + JSON.stringify(err)); + } + ``` + +### off('change')(deprecated) + +off(type: 'change', callback?: Callback>): void + +Unsubscribes from account information changes. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [off('accountChange')](#offaccountchange9). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------------------------------- | ---- | ------------ | +| type | 'change' | Yes | Event type to unsubscribe from. The value is **'change'**, which indicates the account change event. | +| callback | Callback> | No | Callback to unregister.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + function changeOnCallback(data){ + console.debug("receive change data:" + JSON.stringify(data)); + appAccountManager.off('change', function(){ + console.debug("off finish"); + }) + } + try{ + appAccountManager.on('change', ["com.example.actsaccounttest"], changeOnCallback); + } + catch(err){ + console.error("on accountOnOffDemo err:" + JSON.stringify(err)); + } + ``` + +### authenticate(deprecated) + +authenticate(name: string, owner: string, authType: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void + +Authenticates an app account with customized options. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [auth](#auth9). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ---- | --------------- | +| name | string | Yes | Name of the target app account. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | +| authType | string | Yes | Authentication type. | +| options | {[key: string]: any} | Yes | Options for the authentication. | +| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | Yes | Callback invoked to return the result.| + +**Example** + + ```js + import featureAbility from '@ohos.ability.featureAbility'; + + function onResultCallback(code, result) { + console.log("resultCode: " + code); + console.log("result: " + JSON.stringify(result)); + } + + function onRequestRedirectedCallback(request) { + let abilityStartSetting = {want: request}; + featureAbility.startAbility(abilityStartSetting, (err)=>{ + console.log("startAbility err: " + JSON.stringify(err)); + }); + } + + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.authenticate("LiSi", "com.example.accountjsdemo", "getSocialData", {}, { + onResult: onResultCallback, + onRequestRedirected: onRequestRedirectedCallback }); ``` -### getOAuthList8+ +### getOAuthToken(deprecated) -getOAuthList(name: string, authType: string, callback: AsyncCallback<Array<string>>): void +getOAuthToken(name: string, owner: string, authType: string, callback: AsyncCallback<string>): void -Obtains a list of authorized OAuth tokens of an app account. This API uses an asynchronous callback to return the result. +Obtains the authorization token of the specified authentication type for an app account. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAuthToken](#getauthtoken9). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ----------------------- | -| name | string | Yes | Name of the target app account. | -| authType | string | Yes | Authorization type.| -| callback | AsyncCallback<Array<string>> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ----------- | +| name | string | Yes | Name of the target app account. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| +| authType | string | Yes | Authentication type. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the authorization token value obtained. Otherwise, **err** is an error object. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "getSocialData", (err, data) => { - console.log('getOAuthList err: ' + JSON.stringify(err)); - console.log('getOAuthList data: ' + JSON.stringify(data)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getOAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", (err, data) => { + console.log('getOAuthToken err: ' + JSON.stringify(err)); + console.log('getOAuthToken token: ' + data); }); ``` -### getOAuthList8+ +### getOAuthToken(deprecated) -getOAuthList(name: string, authType: string): Promise<Array<string>> +getOAuthToken(name: string, owner: string, authType: string): Promise<string> -Obtains a list of authorized OAuth tokens of an app account. This API uses a promise to return the result. +Obtains the authorization token of the specified authentication type for an app account. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAuthToken](#getauthtoken9-1). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------ | ---- | ----------------------- | -| name | string | Yes | Name of the target app account. | -| authType | string | Yes | Authorization type.| +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----------- | +| name | string | Yes | Name of the target app account. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| +| authType | string | Yes | Authentication type. | -**Parameters** +**Return value** -| Type | Description | -| ---------------------------------- | --------------------- | -| Promise<Array<string>> | Promise used to return the result.| +| Type | Description | +| --------------------- | --------------------- | +| Promise<string> | Promise used to return the result.| **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "getSocialData").then((data) => { - console.log('getOAuthList data: ' + JSON.stringify(data)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getOAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData").then((data) => { + console.log('getOAuthToken token: ' + data); }).catch((err) => { - console.log("getOAuthList err: " + JSON.stringify(err)); + console.log("getOAuthToken err: " + JSON.stringify(err)); }); ``` -### getAuthenticatorCallback8+ +### setOAuthToken(deprecated) -getAuthenticatorCallback(sessionId: string, callback: AsyncCallback<AuthenticatorCallback>): void +setOAuthToken(name: string, authType: string, token: string, callback: AsyncCallback<void>): void -Obtains the authenticator callback for an authentication session. This API uses an asynchronous callback to return the result. +Sets an authorization token of the specific authentication type for an app account. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [setAuthToken](#setauthtoken9). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------------- | ---- | -------- | -| sessionId | string | Yes | ID of the authentication session.| -| callback | AsyncCallback<[AuthenticatorCallback](#authenticatorcallback8)> | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | -------- | +| name | string | Yes | Name of the target app account.| +| authType | string | Yes | Authentication type. | +| token | string | Yes | Token to set.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| **Example** ```js - import featureAbility from '@ohos.ability.featureAbility'; - const appAccountManager = account_appAccount.createAppAccountManager(); - featureAbility.getWant((err, want) => { - var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; - appAccountManager.getAuthenticatorCallback(sessionId, (err, callback) => { - if (err.code != account_appAccount.ResultCode.SUCCESS) { - console.log("getAuthenticatorCallback err: " + JSON.stringify(err)); - return; - } - var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", - [account_appAccount.Constants.KEY_OWNER]: "com.example.ohos.accountjsdemo", - [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", - [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; - callback.onResult(account_appAccount.ResultCode.SUCCESS, result); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx", (err) => { + console.log('setOAuthToken err: ' + JSON.stringify(err)); }); ``` -### getAuthenticatorCallback8+ +### setOAuthToken(deprecated) -getAuthenticatorCallback(sessionId: string): Promise<AuthenticatorCallback> +setOAuthToken(name: string, authType: string, token: string): Promise<void> -Obtains the authenticator callback for an authentication session. This API uses a promise to return the result. +Sets an authorization token of the specific authentication type for an app account. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [setAuthToken](#setauthtoken9-1). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------ | ---- | -------- | -| sessionId | string | Yes | ID of the authentication session.| +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | -------- | +| name | string | Yes | Name of the target app account.| +| authType | string | Yes | Authentication type. | +| token | string | Yes | Authorization token to set.| -**Parameters** +**Return value** -| Type | Description | -| ------------------------------------ | --------------------- | -| Promise<[AuthenticatorCallback](#authenticatorcallback8)> | Promise used to return the result.| +| Type | Description | +| ------------------- | --------------------- | +| Promise<void> | Promise that returns no value.| **Example** ```js - import featureAbility from '@ohos.ability.featureAbility'; - - const appAccountManager = account_appAccount.createAppAccountManager(); - featureAbility.getWant().then((want) => { - var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; - appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { - var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", - [account_appAccount.Constants.KEY_OWNER]: "com.example.ohos.accountjsdemo", - [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", - [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; - callback.onResult(account_appAccount.ResultCode.SUCCESS, result); - }).catch((err) => { - console.log("getAuthenticatorCallback err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx").then(() => { + console.log('setOAuthToken successfully'); }).catch((err) => { - console.log("getWant err: " + JSON.stringify(err)); + console.log('setOAuthToken err: ' + JSON.stringify(err)); }); ``` -### getAuthenticatorInfo8+ +### deleteOAuthToken(deprecated) -getAuthenticatorInfo(owner: string, callback: AsyncCallback<AuthenticatorInfo>): void +deleteOAuthToken(name: string, owner: string, authType: string, token: string, callback: AsyncCallback<void>): void + +Deletes the authorization token of the specified authentication type for an app account. This API uses an asynchronous callback to return the result. -Obtains authenticator information of an app account. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [deleteAuthToken](#deleteauthtoken9). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------------------------- | ---- | ----------- | -| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| -| callback | AsyncCallback<[AuthenticatorInfo](#authenticatorinfo8)> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ------------ | +| name | string | Yes | Name of the target app account. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | +| authType | string | Yes | Authentication type. | +| token | string | Yes | Authorization token to delete.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAuthenticatorInfo("com.example.ohos.accountjsdemo", (err, data) => { - console.log("getAuthenticatorInfo err: " + JSON.stringify(err)); - console.log('getAuthenticatorInfo data: ' + JSON.stringify(data)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.deleteOAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", "xxxxx", (err) => { + console.log('deleteOAuthToken err: ' + JSON.stringify(err)); }); ``` -### getAuthenticatorInfo8+ +### deleteOAuthToken(deprecated) -getAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo> +deleteOAuthToken(name: string, owner: string, authType: string, token: string): Promise<void> + +Deletes the authorization token of the specified authentication type for an app account. This API uses a promise to return the result. -Obtains authenticator information of an app account. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [deleteAuthToken](#deleteauthtoken9-1). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | ---- | ----------- | -| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ------------ | +| name | string | Yes | Name of the target app account. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | +| authType | string | Yes | Authentication type. | +| token | string | Yes | Authorization token to delete.| -**Parameters** +**Return value** -| Type | Description | -| -------------------------------- | --------------------- | -| Promise<[AuthenticatorInfo](#authenticatorinfo8)> | Promise used to return the result.| +| Type | Description | +| ------------------- | --------------------- | +| Promise<void> | Promise that returns no value.| **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAuthenticatorInfo("com.example.ohos.accountjsdemo").then((data) => { - console.log('getAuthenticatorInfo: ' + JSON.stringify(data)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.deleteOAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", "xxxxx").then(() => { + console.log('deleteOAuthToken successfully'); }).catch((err) => { - console.log("getAuthenticatorInfo err: " + JSON.stringify(err)); + console.log("deleteOAuthToken err: " + JSON.stringify(err)); }); ``` -### checkAppAccess9+ +### setOAuthTokenVisibility(deprecated) -checkAppAccess(name: string, bundleName: string, callback: AsyncCallback<boolean>): void +setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean, callback: AsyncCallback<void>): void + +Sets the visibility of an authorization token to an app. This API uses an asynchronous callback to return the result. -Checks whether an app account is authorized to access an app. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [setAuthTokenVisibility](#setauthtokenvisibility9). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ---------------------------- | ----- | ---------------- | -| name | string | Yes | Name of the target app account. | -| bundleName | string | Yes | Bundle name of the app to access. | -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | ---- | ------------------------- | +| name | string | Yes | Name of the target app account. | +| authType | string | Yes | Authentication type. | +| bundleName | string | Yes | Bundle name of the app. | +| isVisible | boolean | Yes | Whether the authorization token is visible to the app. The value **true** means the authorization token is visible to the app; the value **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.checkAppAccess("zhangsan", "com.example.ohos.accountjsdemo", (err, data) => { - console.log('checkAppAccess: ' + JSON.stringify(data)); - console.log("checkAppAccess err: " + JSON.stringify(err)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", true, (err) => { + console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); }); ``` -### checkAppAccess9+ +### setOAuthTokenVisibility(deprecated) -checkAppAccess(name: string, bundleName: string): Promise<boolean> +setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean): Promise<void> + +Sets the visibility of an authorization token to an app. This API uses a promise to return the result. -Checks whether an app account is authorized to access an app. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [setAuthTokenVisibility](#setauthtokenvisibility9-1). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------ | ----- | ---------------- | -| name | string | Yes | Name of the target app account. | -| bundleName | string | Yes | Bundle name of the app to access. | +| Name | Type | Mandatory | Description | +| ---------- | ------- | ---- | ------------ | +| name | string | Yes | Name of the target app account. | +| authType | string | Yes | Authentication type. | +| bundleName | string | Yes | Bundle name of the app.| +| isVisible | boolean | Yes | Whether the authorization token is visible to the app. The value **true** means the authorization token is visible to the app; the value **false** means the opposite. | -**Parameters** +**Return value** -| Type | Description | -| ---------------------- | --------------------------------- | -| Promise<boolean> | Promise used to return the result.| +| Type | Description | +| ------------------- | --------------------- | +| Promise<void> | Promise that returns no value.| **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.checkAppAccess("zhangsan", "com.example.ohos.accountjsdemo").then((data) => { - console.log('checkAppAccess: ' + JSON.stringify(data)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", true).then(() => { + console.log('setOAuthTokenVisibility successfully'); }).catch((err) => { - console.log("checkAppAccess err: " + JSON.stringify(err)); + console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); }); ``` -### deleteAccountCredential9+ +### checkOAuthTokenVisibility(deprecated) -deleteAccountCredential(name: string, credentialType: string, callback: AsyncCallback<void>): void +checkOAuthTokenVisibility(name: string, authType: string, bundleName: string, callback: AsyncCallback<boolean>): void + +Checks the visibility of an authorization token of the specified authentication type to an app. This API uses an asynchronous callback to return the result. -Deletes the credential of an app account. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [checkAuthTokenVisibility](#checkauthtokenvisibility9). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------------------------- | ----- | -------------- | -| name | string | Yes | Name of the target app account.| -| credentialType | string | Yes | Type of the credential to delete. | -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory | Description | +| ---------- | ---------------------------- | ---- | ----------- | +| name | string | Yes | Name of the target app account. | +| authType | string | Yes | Authentication type. | +| bundleName | string | Yes | Bundle name of the app.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** can be **true** (the authorization token is visible to the app) or **false** (the authorization token is not visible to the app). If the operation fails, **err** is an error object. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.deleteAccountCredential("zhangsan", "pin", (err, data) => { - console.log('deleteAccountCredential: ' + JSON.stringify(data)); - console.log("deleteAccountCredential err: " + JSON.stringify(err)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", (err, data) => { + console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); + console.log('checkOAuthTokenVisibility isVisible: ' + data); }); ``` -### deleteAccountCredential9+ +### checkOAuthTokenVisibility(deprecated) + +checkOAuthTokenVisibility(name: string, authType: string, bundleName: string): Promise<boolean> -deleteAccountCredential(name: string, credentialType: string): Promise<void> +Checks the visibility of an authorization token of the specified authentication type to an app. This API uses a promise to return the result. -Deletes the credential of an app account. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [checkAuthTokenVisibility](#checkauthtokenvisibility9-1). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------ | ----- | --------------- | -| name | string | Yes | Name of the target app account.| -| credentialType | string | Yes | Type of the credential to delete. | +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | ------------- | +| name | string | Yes | Name of the target app account. | +| authType | string | Yes | Authentication type. | +| bundleName | string | Yes | Bundle name of the app.| -**Parameters** +**Return value** -| Type | Description | -| ------------------- | -------------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| ---------------------- | --------------------- | +| Promise<boolean> | Promise used to return the result. The value **true** means the authorization token is visible to the app; the value **false** means the opposite.| **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.deleteAccountCredential("zhangsan", "pin").then((data) => { - console.log('deleteAccountCredential: ' + JSON.stringify(data)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo").then((data) => { + console.log('checkOAuthTokenVisibility isVisible: ' + data); }).catch((err) => { - console.log("deleteAccountCredential err: " + JSON.stringify(err)); + console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); }); ``` -### checkAccountLabels9+ +### getAllOAuthTokens(deprecated) -checkAccountLabels(name: string, owner: string, labels: Array<string>, callback: AsyncCallback<boolean>): void; +getAllOAuthTokens(name: string, owner: string, callback: AsyncCallback<Array<OAuthTokenInfo>>): void + +Obtains all tokens visible to the invoker for an app account. This API uses an asynchronous callback to return the result. -Checks whether an app account has specific labels. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAllAuthTokens](#getallauthtokens9). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------------------------- | ----- | --------------- | -| name | string | Yes | Name of the target app account. | -| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| -| labels | Array<string> | Yes | Labels to check. | -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------- | +| name | string | Yes | Name of the target app account. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| +| callback | AsyncCallback<Array<[OAuthTokenInfo](#oauthtokeninfodeprecated)>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is a list of all tokens visible to the invoker. Otherwise, **err** is an error object. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - var labels = ["student"]; - appAccountManager.checkAccountLabels("zhangsan", "com.example.ohos.accountjsdemo", labels, (err, data) => { - console.log('checkAccountLabels: ' + JSON.stringify(data)); - console.log("checkAccountLabels err: " + JSON.stringify(err)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAllOAuthTokens("LiSi", "com.example.accountjsdemo", (err, data) => { + console.log("getAllOAuthTokens err: " + JSON.stringify(err)); + console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); }); ``` -### checkAccountLabels9+ +### getAllOAuthTokens(deprecated) -checkAccountLabels(name: string, owner: string, labels: Array<string>): Promise<boolean> +getAllOAuthTokens(name: string, owner: string): Promise<Array<OAuthTokenInfo>> -Checks whether an app account has specific labels. This API uses a promise to return the result. +Obtains all tokens visible to the invoker for an app account. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAllAuthTokens](#getallauthtokens9-1). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------------------------- | ----- | --------------- | -| name | string | Yes | Name of the target app account. | -| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| -| labels | Array<string> | Yes | Labels to check. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------- | +| name | string | Yes | Name of the target app account. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| -**Parameters** +**Return value** -| Type | Description | -| ------------------- | -------------------------------- | -| Promise<boolean> | Promise used to return the result.| +| Type | Description | +| ---------------------------------------- | --------------------- | +| Promise<Array< [OAuthTokenInfo](#oauthtokeninfodeprecated)>> | Promise used to return the tokens obtained.| **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - var labels = ["student"]; - appAccountManager.checkAccountLabels("zhangsan", "com.example.ohos.accountjsdemo", labels).then((data) => { - console.log('checkAccountLabels: ' + JSON.stringify(data)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAllOAuthTokens("LiSi", "com.example.accountjsdemo").then((data) => { + console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); }).catch((err) => { - console.log("checkAccountLabels err: " + JSON.stringify(err)); + console.log("getAllOAuthTokens err: " + JSON.stringify(err)); }); ``` -### selectAccountsByOptions9+ +### getOAuthList(deprecated) + +getOAuthList(name: string, authType: string, callback: AsyncCallback<Array<string>>): void -selectAccountsByOptions(options: SelectAccountsOptions, callback: AsyncCallback<Array<AppAccountInfo>>); +Obtains the authorization list of the specified authentication type for an app account. The authorization list contains all authorized bundles. The token authorization list is set by setOAuthTokenVisibility(#setoauthtokenvisibilitydeprecated). This API uses an asynchronous callback to return the result. -Selects the accounts accessible to the requester based on the options. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAuthList](#getauthlist9). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ----------------------------------- | ----- | --------------- | -| options | SelectAccountsOptions | Yes | Options for selecting accounts. | -| callback | AsyncCallback<[AppAccountInfo](#appaccountinfo)> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------------- | +| name | string | Yes | Name of the target app account. | +| authType | string | Yes | Authentication type.| +| callback | AsyncCallback<Array<string>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is a list of authorized bundles obtained. Otherwise, **err** is an error object. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - var options = { - allowedOwners: ["com.example.ohos.accountjsdemo"] - }; - appAccountManager.selectAccountsByOptions(options, (err, data) => { - console.log('selectAccountsByOptions: ' + JSON.stringify(data)); - console.log("selectAccountsByOptions err: " + JSON.stringify(err)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getOAuthList("com.example.accountjsdemo", "getSocialData", (err, data) => { + console.log('getOAuthList err: ' + JSON.stringify(err)); + console.log('getOAuthList data: ' + JSON.stringify(data)); }); ``` -### selectAccountsByOptions9+ +### getOAuthList(deprecated) -selectAccountsByOptions(options: SelectAccountsOptions): Promise<Array<AppAccountInfo>> +getOAuthList(name: string, authType: string): Promise<Array<string>> -Selects the accounts accessible to the requester based on the options. This API uses a promise to return the result. +Obtains the authorization list of the specified authentication type for an app account. The authorization list contains all authorized bundles. The token authorization list is set by setOAuthTokenVisibility(#setoauthtokenvisibilitydeprecated). This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAuthList](#getauthlist9-1). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------------------------- | ----- | --------------- | -| options | [SelectAccountsOptions](#selectaccountsoptions9) | Yes | Options for selecting accounts. | +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----------------------- | +| name | string | Yes | Name of the target app account. | +| authType | string | Yes | Authentication type.| -**Parameters** +**Return value** -| Type | Description | -| ------------------- | -------------------------------- | -| Promise<[AppAccountInfo](#appaccountinfo)> | Promise used to return the result.| +| Type | Description | +| ---------------------------------- | --------------------- | +| Promise<Array<string>> | Promise used to return a list of authorized bundles.| **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - var options = { - allowedOwners: ["com.example.ohos.accountjsdemo"] - }; - appAccountManager.selectAccountsByOptions(options).then((data) => { - console.log('selectAccountsByOptions: ' + JSON.stringify(data)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getOAuthList("com.example.accountjsdemo", "getSocialData").then((data) => { + console.log('getOAuthList data: ' + JSON.stringify(data)); }).catch((err) => { - console.log("selectAccountsByOptions err: " + JSON.stringify(err)); + console.log("getOAuthList err: " + JSON.stringify(err)); }); ``` -### verifyCredential9+ +### getAuthenticatorCallback(deprecated) -verifyCredential(name: string, owner: string, callback: AuthenticatorCallback): void; +getAuthenticatorCallback(sessionId: string, callback: AsyncCallback<AuthenticatorCallback>): void -Verifies the user credential. This API uses an asynchronous callback to return the result. +Obtains the authenticator callback for an authentication session. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAuthCallback](#getauthcallback9). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------- | ----- | ----------------------- | -| name | string | Yes | Name of the target app account. | -| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | -| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the verification result.| +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------- | +| sessionId | string | Yes | ID of the authentication session.| +| callback | AsyncCallback<[AuthenticatorCallback](#authenticatorcallbackdeprecated)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the authenticator callback obtained. Otherwise, **err** is an error object.| **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.verifyCredential("zhangsan", "com.example.ohos.accountjsdemo", { - onResult: (resultCode, result) => { - console.log("verifyCredential onResult, resultCode:" + JSON.stringify(resultCode)); - console.log("verifyCredential onResult, result:" + JSON.stringify(result)); - }, - onRequestRedirected: (request) => { - console.log("verifyCredential onRequestRedirected, request:" + JSON.stringify(request)); - } + import featureAbility from '@ohos.ability.featureAbility'; + let appAccountManager = account_appAccount.createAppAccountManager(); + featureAbility.getWant((err, want) => { + var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; + appAccountManager.getAuthenticatorCallback(sessionId, (err, callback) => { + if (err.code != account_appAccount.ResultCode.SUCCESS) { + console.log("getAuthenticatorCallback err: " + JSON.stringify(err)); + return; + } + var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", + [account_appAccount.Constants.KEY_OWNER]: "com.example.accountjsdemo", + [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", + [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + }); }); ``` -### verifyCredential9+ +### getAuthenticatorCallback(deprecated) -verifyCredential(name: string, owner: string, options: VerifyCredentialOptions, callback: AuthenticatorCallback): void; +getAuthenticatorCallback(sessionId: string): Promise<AuthenticatorCallback> -Verifies the user credential. This API uses an asynchronous callback to return the result. +Obtains the authenticator callback for an authentication session. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAuthCallback](#getauthcallback9-1). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ----------------------- | ----- | ----------------------- | -| name | string | Yes | Name of the target app account. | -| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | -| options | [VerifyCredentialOptions](#verifycredentialoptions9) | Yes | Options for verifying the user credential. | -| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the verification result.| +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | -------- | +| sessionId | string | Yes | ID of the authentication session.| + +**Return value** + +| Type | Description | +| ------------------------------------ | --------------------- | +| Promise<[AuthenticatorCallback](#authenticatorcallbackdeprecated)> | Promise used to return the authenticator callback obtained.| **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - var options = { - credentialType: "pin", - credential: "123456" - }; - appAccountManager.verifyCredential("zhangsan", "com.example.ohos.accountjsdemo", options, { - onResult: (resultCode, result) => { - console.log("verifyCredential onResult, resultCode:" + JSON.stringify(resultCode)); - console.log("verifyCredential onResult, result:" + JSON.stringify(result)); - }, - onRequestRedirected: (request) => { - console.log("verifyCredential onRequestRedirected, request:" + JSON.stringify(request)); - } + import featureAbility from '@ohos.ability.featureAbility'; + + let appAccountManager = account_appAccount.createAppAccountManager(); + featureAbility.getWant().then((want) => { + var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; + appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { + var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", + [account_appAccount.Constants.KEY_OWNER]: "com.example.accountjsdemo", + [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", + [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + }).catch((err) => { + console.log("getAuthenticatorCallback err: " + JSON.stringify(err)); + }); + }).catch((err) => { + console.log("getWant err: " + JSON.stringify(err)); }); ``` -### setAuthenticatorProperties9+ +### getAuthenticatorInfo(deprecated) + +getAuthenticatorInfo(owner: string, callback: AsyncCallback<AuthenticatorInfo>): void -setAuthenticatorProperties(owner: string, callback: AuthenticatorCallback): void; +Obtains the authenticator information of an app. This API uses an asynchronous callback to return the result. -Sets authenticator properties. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [queryAuthenticatorInfo](#queryauthenticatorinfo9). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------- | ----- | ----------------------- | -| owner | string | Yes | Owner of the authenticator. | -| options | [SetPropertiesOptions](#setpropertiesoptions9) | Yes | Authenticator properties to set. | -| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the result.| +| Name | Type | Mandatory | Description | +| -------- | -------------------------------------- | ---- | ----------- | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| +| callback | AsyncCallback<[AuthenticatorInfo](#authenticatorinfo8)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the authenticator information obtained. Otherwise, **err** is an error object. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setAuthenticatorProperties("com.example.ohos.accountjsdemo", { - onResult: (resultCode, result) => { - console.log("setAuthenticatorProperties onResult, resultCode:" + JSON.stringify(resultCode)); - console.log("setAuthenticatorProperties onResult, result:" + JSON.stringify(result)); - }, - onRequestRedirected: (request) => { - console.log("setAuthenticatorProperties onRequestRedirected, request:" + JSON.stringify(request)); - } + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAuthenticatorInfo("com.example.accountjsdemo", (err, data) => { + console.log("getAuthenticatorInfo err: " + JSON.stringify(err)); + console.log('getAuthenticatorInfo data: ' + JSON.stringify(data)); }); ``` -### setAuthenticatorProperties9+ +### getAuthenticatorInfo(deprecated) + +getAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo> -setAuthenticatorProperties(owner: string, options: SetPropertiesOptions, callback: AuthenticatorCallback): void; +Obtains the authenticator information of an app. This API uses a promise to return the result. -Sets authenticator properties. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [queryAuthenticatorInfo](#queryauthenticatorinfo9-1). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------- | ----- | ----------------------- | -| owner | string | Yes | Owner of the authenticator. | -| options | [SetPropertiesOptions](#setpropertiesoptions9) | Yes | Authenticator properties to set. | -| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the result.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------- | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| + +**Return value** + +| Type | Description | +| -------------------------------- | --------------------- | +| Promise<[AuthenticatorInfo](#authenticatorinfo8)> | Promise used to return the authenticator information obtained.| **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - var options = { - properties: {"prop1": "value1"} - }; - appAccountManager.setAuthenticatorProperties("com.example.ohos.accountjsdemo", options, { - onResult: (resultCode, result) => { - console.log("setAuthenticatorProperties onResult, resultCode:" + JSON.stringify(resultCode)); - console.log("setAuthenticatorProperties onResult, result:" + JSON.stringify(result)); - }, - onRequestRedirected: (request) => { - console.log("setAuthenticatorProperties onRequestRedirected, request:" + JSON.stringify(request)); - } + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAuthenticatorInfo("com.example.accountjsdemo").then((data) => { + console.log('getAuthenticatorInfo: ' + JSON.stringify(data)); + }).catch((err) => { + console.log("getAuthenticatorInfo err: " + JSON.stringify(err)); }); ``` @@ -1979,19 +4505,35 @@ Defines app account information. | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----------- | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| -| name | string | Yes | Name of the app account. | +| name | string | Yes | Name of the target app account. | + +## AuthTokenInfo9+ + +Defines authorization token information. + +**System capability**: SystemCapability.Account.AppAccount + +| Name | Type | Mandatory | Description | +| -------------------- | -------------- | ----- | ---------------- | +| authType9+ | string | Yes | Authentication type. | +| token9+ | string | Yes | Value of the authorization token. | +| account9+ | [AppAccountInfo](#appaccountinfo) | No | Account information of the authorization token.| + +## OAuthTokenInfo(deprecated) -## OAuthTokenInfo8+ +Defines authorization token information. -Defines OAuth token information. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AuthTokenInfo](#authtokeninfo9). **System capability**: SystemCapability.Account.AppAccount | Name | Type | Mandatory | Description | | -------------------- | -------------- | ----- | ---------------- | | authType | string | Yes | Authentication type. | -| token | string | Yes | Value of the token. | -| account9+ | AppAccountInfo | No | Account information of the token.| +| token | string | Yes | Value of the authorization token. | +| account9+ | [AppAccountInfo](#appaccountinfo) | No | Account information of the authorization token.| ## AuthenticatorInfo8+ @@ -2005,9 +4547,41 @@ Defines OAuth authenticator information. | iconId | number | Yes | ID of the authenticator icon. | | labelId | number | Yes | ID of the authenticator label. | +## AuthResult9+ + +Defines the authentication result. + +**System capability**: SystemCapability.Account.AppAccount + +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---------- | +| account | [AppAccountInfo](#appaccountinfo) | No | Account information of the authorization token.| +| tokenInfo | [AuthTokenInfo](#authtokeninfo9) | No | Token information. | + +## CreateAccountOptions9+ + +Defines the options for creating an app account. + +**System capability**: SystemCapability.Account.AppAccount + +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---------- | +| customData | {[key: string]: string} | No | Custom data.| + +## CreateAccountImplicitlyOptions9+ + +Defines the options for implicitly creating an app account. + +**System capability**: SystemCapability.Account.AppAccount + +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---------- | +| requiredLabels | Array<string> | No | Labels required.| +| authType | string | No | Authentication type.| +| parameters | {[key: string]: Object} | No | Customized parameters.| ## SelectAccountsOptions9+ -Represents the options for selecting accounts. +Defines the options for selecting accounts. **System capability**: SystemCapability.Account.AppAccount @@ -2027,7 +4601,7 @@ Represents the options for verifying the user credential. | -------------- | ---------------------- | ----- | -------------- | | credentialType | string | No | Type of the credential to verify. | | credential | string | No | Credential value. | -| parameters | {[key:string]: Object} | No | Customized parameters.| +| parameters | {[key: string]: Object} | No | Customized parameters.| ## SetPropertiesOptions9+ @@ -2038,8 +4612,8 @@ Represents the options for setting authenticator properties. | Name | Type | Mandatory | Description | | ---------- | ---------------------- | ----- | -------------- | -| properties | {[key:string]: Object} | No | Authenticator properties. | -| parameters | {[key:string]: Object} | No | Customized parameters.| +| properties | {[key: string]: Object} | No | Authenticator properties. | +| parameters | {[key: string]: Object} | No | Customized parameters.| ## Constants8+ @@ -2047,12 +4621,16 @@ Enumerates the constants. **System capability**: SystemCapability.Account.AppAccount -| Name | Default Value | Description | +| Name | Value | Description | | -------------------------------- | ---------------------- | ----------------------- | -| ACTION_ADD_ACCOUNT_IMPLICITLY | "addAccountImplicitly" | Operation of adding an account implicitly. | -| ACTION_AUTHENTICATE | "authenticate" | Authentication operation. | -| KEY_NAME | "name" | App account name. | -| KEY_OWNER | "owner" | Owner of an app account.| +| ACTION_ADD_ACCOUNT_IMPLICITLY(deprecated) | "addAccountImplicitly" | Operation of adding an account implicitly. | +| ACTION_AUTHENTICATE(deprecated) | "authenticate" | Authentication operation. | +| ACTION_CREATE_ACCOUNT_IMPLICITLY9+ | "createAccountImplicitly" | Operation of creating an account implicitly. | +| ACTION_AUTH9+ | "auth" | Authentication operation. | +| ACTION_VERIFY_CREDENTIAL9+ | "verifyCredential" | Operation of verifying credentials. | +| ACTION_SET_AUTHENTICATOR_PROPERTIES9+ | "setAuthenticatorProperties" | Operation of setting authenticator properties. | +| KEY_NAME | "name" | Name of the app account. | +| KEY_OWNER | "owner" | Owner of the app account.| | KEY_TOKEN | "token" | Token. | | KEY_ACTION | "action" | Operation. | | KEY_AUTH_TYPE | "authType" | Authentication type. | @@ -2069,7 +4647,7 @@ Enumerates the result codes. **System capability**: SystemCapability.Account.AppAccount -| Name | Default Value | Description | +| Name | Value | Description | | ----------------------------------- | ----- | ------------ | | SUCCESS | 0 | The operation is successful. | | ERROR_ACCOUNT_NOT_EXIST | 10001 | The app account does not exist. | @@ -2085,16 +4663,122 @@ Enumerates the result codes. | ERROR_OAUTH_SERVICE_EXCEPTION | 10011 | The OAuth service is abnormal. | | ERROR_OAUTH_SESSION_NOT_EXIST | 10012 | The session to be authenticated does not exist. | | ERROR_OAUTH_TIMEOUT | 10013 | The authentication timed out. | -| ERROR_OAUTH_TOKEN_NOT_EXIST | 10014 | The OAuth token does not exist.| +| ERROR_OAUTH_TOKEN_NOT_EXIST | 10014 | The authorization token does not exist.| | ERROR_OAUTH_TOKEN_TOO_MANY | 10015 | The number of OAuth tokens reaches the limit. | | ERROR_OAUTH_UNSUPPORT_ACTION | 10016 | The authentication operation is not supported. | | ERROR_OAUTH_UNSUPPORT_AUTH_TYPE | 10017 | The authentication type is not supported. | | ERROR_PERMISSION_DENIED | 10018 | The required permission is missing. | -## AuthenticatorCallback8+ +## AuthCallback9+ + +Implements authenticator callbacks. + +### onResult9+ + +onResult: (code: number, result?: AuthResult) => void + +Called to return the result of an authentication request. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | -------------------- | ---- | ------ | +| code | number | Yes | Authentication result code.| +| result | [AuthResult](#authresult9) | No | Authentication result. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + var sessionId = "1234"; + appAccountManager.getAuthCallback(sessionId).then((callback) => { + var result = { + accountInfo: { + name: "Lisi", + owner: "com.example.accountjsdemo", + }, + tokenInfo: { + token: "xxxxxx", + authType: "getSocialData" + } + }; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + }).catch((err) => { + console.log("getAuthCallback err: " + JSON.stringify(err)); + }); + ``` + +### onRequestRedirected9+ + +onRequestRedirected: (request: Want) => void + +Called to redirect a request. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ---- | ---- | ---------- | +| request | Want | Yes | Request to be redirected.| + +**Example** + + ```js + class MyAuthenticator extends account_appAccount.Authenticator { + createAccountImplicitly(options, callback) { + callback.onRequestRedirected({ + bundleName: "com.example.accountjsdemo", + abilityName: "com.example.accountjsdemo.LoginAbility", + }); + } + + auth(name, authType, options, callback) { + var result = { + accountInfo: { + name: "Lisi", + owner: "com.example.accountjsdemo", + }, + tokenInfo: { + token: "xxxxxx", + authType: "getSocialData" + } + }; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + } + } + ``` + +### onRequestContinued9+ + +onRequestContinued?: () => void + +Called to continue to process the request. + +**System capability**: SystemCapability.Account.AppAccount + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + var sessionId = "1234"; + appAccountManager.getAuthCallback(sessionId).then((callback) => { + callback.onRequestContinued(); + }).catch((err) => { + console.log("getAuthCallback err: " + JSON.stringify(err)); + }); + ``` + +## AuthenticatorCallback(deprecated) Provides OAuth authenticator callbacks. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AuthCallback](#authcallback9). + ### onResult8+ onResult: (code: number, result: {[key: string]: any}) => void @@ -2113,11 +4797,11 @@ Called to return the result of an authentication request. **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); var sessionId = "1234"; appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", - [account_appAccount.Constants.KEY_OWNER]: "com.example.ohos.accountjsdemo", + [account_appAccount.Constants.KEY_OWNER]: "com.example.accountjsdemo", [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; callback.onResult(account_appAccount.ResultCode.SUCCESS, result); @@ -2146,8 +4830,8 @@ Called to redirect a request. class MyAuthenticator extends account_appAccount.Authenticator { addAccountImplicitly(authType, callerBundleName, options, callback) { callback.onRequestRedirected({ - bundleName: "com.example.ohos.accountjsdemo", - abilityName: "com.example.ohos.accountjsdemo.LoginAbility", + bundleName: "com.example.accountjsdemo", + abilityName: "com.example.accountjsdemo.LoginAbility", }); } @@ -2171,7 +4855,7 @@ Called to continue to process the request. **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); var sessionId = "1234"; appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { callback.onRequestContinued(); @@ -2184,11 +4868,30 @@ Called to continue to process the request. Provides APIs to operate the authenticator. -### addAccountImplicitly8+ +### createAccountImplicitly9+ + +createAccountImplicitly(options: CreateAccountImplicitlyOptions, callback: AuthCallback): void + +Creates an app account implicitly based on the specified account owner. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------------- | --------------------- | ---- | --------------- | +| options | [CreateAccountImplicitlyOptions](#createaccountimplicitlyoptions9) | Yes | Options for implicitly creating the account. | +| callback | [AuthCallback](#authcallback9) | Yes | Authenticator callback invoked to return the result.| + +### addAccountImplicitlydeprecated addAccountImplicitly(authType: string, callerBundleName: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void -Implicitly adds an app account based on the specified authentication type and options. This API uses an asynchronous callback to return the result. +Adds an app account implicitly based on the specified authentication type and options. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [createAccountImplicitly](#createaccountimplicitly9-2). **System capability**: SystemCapability.Account.AppAccount @@ -2199,13 +4902,35 @@ Implicitly adds an app account based on the specified authentication type and op | authType | string | Yes | Authentication type. | | callerBundleName | string | Yes | Bundle name of the authentication requester. | | options | {[key: string]: any} | Yes | Options for the authentication. | -| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the authentication result.| +| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | Yes | Authenticator callback invoked to return the authentication result.| + +### auth9+ + +auth(name: string, authType: string, options: {[key:string]: Object}, callback: AuthCallback): void + +Authenticates an app account to obtain the authorization token. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------------- | --------------------- | ---- | --------------- | +| name | string | Yes | Name of the target app account. | +| authType | string | Yes | Authentication type. | +| callerBundleName | string | Yes | Authentication type. | +| options | {[key: string]: Object} | Yes | Options for the authentication. | +| callback | [AuthCallback](#authcallback9) | Yes | Callback invoked to return the result.| -### authenticate8+ +### authenticatedeprecated authenticate(name: string, authType: string, callerBundleName: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void -Authenticates an app account to obtain the OAuth token. This API uses an asynchronous callback to return the result. +Authenticates an app account to obtain the authorization token. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [auth](#auth9-2). **System capability**: SystemCapability.Account.AppAccount @@ -2217,11 +4942,11 @@ Authenticates an app account to obtain the OAuth token. This API uses an asynchr | authType | string | Yes | Authentication type. | | callerBundleName | string | Yes | Bundle name of the authentication requester. | | options | {[key: string]: any} | Yes | Options for the authentication. | -| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the authentication result.| +| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | Yes | Authenticator callback invoked to return the authentication result.| ### verifyCredential9+ -verifyCredential(name: string, options: VerifyCredentialOptions, callback: AuthenticatorCallback): void; +verifyCredential(name: string, options: VerifyCredentialOptions, callback: AuthCallback): void; Verifies the credential of an app account. This API uses an asynchronous callback to return the result. @@ -2233,13 +4958,13 @@ Verifies the credential of an app account. This API uses an asynchronous callbac | ---------------- | --------------------- | ---- | --------------- | | name | string | Yes | Name of the target app account. | | options | [VerifyCredentialOptions](#verifycredentialoptions9) | Yes | Options for credential verification. | -| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the verification result.| +| callback | [AuthCallback](#authcallback9) | Yes | Authenticator callback invoked to return the verification result.| ### setProperties9+ -setProperties(options: SetPropertiesOptions, callback: AuthenticatorCallback): void; +setProperties(options: SetPropertiesOptions, callback: AuthCallback): void; -Sets authenticator properties. This API uses an asynchronous callback to return the result. +Sets the authenticator properties. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -2248,11 +4973,11 @@ Sets authenticator properties. This API uses an asynchronous callback to return | Name | Type | Mandatory | Description | | ---------------- | --------------------- | ---- | --------------- | | options | [SetPropertiesOptions](#setpropertiesoptions9) | Yes | Authenticator properties to set. | -| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the result.| +| callback | [AuthCallback](#authcallback9) | Yes | Authenticator callback invoked to return the result.| ### checkAccountLabels9+ -checkAccountLabels(name: string, labels: Array<string>, callback: AuthenticatorCallback): void; +checkAccountLabels(name: string, labels: Array<string>, callback: AuthCallback): void; Checks the account labels. This API uses an asynchronous callback to return the result. @@ -2264,11 +4989,11 @@ Checks the account labels. This API uses an asynchronous callback to return the | ---------------- | --------------------- | ---- | --------------- | | name | string | Yes | Name of the target app account. | | labels | Array<string> | Yes | Labels to check. | -| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the check result.| +| callback | [AuthCallback](#authcallback9) | Yes | Authenticator callback invoked to return the check result.| ### isAccountRemovable9+ -isAccountRemovable(name: string, callback: AuthenticatorCallback): void; +isAccountRemovable(name: string, callback: AuthCallback): void; Checks whether an app account can be deleted. This API uses an asynchronous callback to return the result. @@ -2279,7 +5004,7 @@ Checks whether an app account can be deleted. This API uses an asynchronous call | Name | Type | Mandatory | Description | | ---------------- | --------------------- | ---- | --------------- | | name | string | Yes | Name of the target app account. | -| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the result.| +| callback | [AuthCallback](#authcallback9) | Yes | Authenticator callback invoked to return the result.| ### getRemoteObject9+ @@ -2293,49 +5018,49 @@ Obtains the remote object of an authenticator. This API cannot be overloaded. ```js class MyAuthenticator extends account_appAccount.Authenticator { - addAccountImplicitly(authType, callerBundleName, options, callback) { - callback.onRequestRedirected({ - bundleName: "com.example.ohos.accountjsdemo", - abilityName: "com.example.ohos.accountjsdemo.LoginAbility", - }); - } + addAccountImplicitly(authType, callerBundleName, options, callback) { + callback.onRequestRedirected({ + bundleName: "com.example.accountjsdemo", + abilityName: "com.example.accountjsdemo.LoginAbility", + }); + } - authenticate(name, authType, callerBundleName, options, callback) { - var result = {[account_appAccount.Constants.KEY_NAME]: name, - [account_appAccount.Constants.KEY_AUTH_TYPE]: authType, - [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; - callback.onResult(account_appAccount.ResultCode.SUCCESS, result); - } + authenticate(name, authType, callerBundleName, options, callback) { + var result = {[account_appAccount.Constants.KEY_NAME]: name, + [account_appAccount.Constants.KEY_AUTH_TYPE]: authType, + [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + } - verifyCredential(name, options, callback) { - callback.onRequestRedirected({ - bundleName: "com.example.ohos.accountjsdemo", - abilityName: "com.example.ohos.accountjsdemo.VerifyAbility", - parameters: { - name: name - } - }); - } + verifyCredential(name, options, callback) { + callback.onRequestRedirected({ + bundleName: "com.example.accountjsdemo", + abilityName: "com.example.accountjsdemo.VerifyAbility", + parameters: { + name: name + } + }); + } - setProperties(options, callback) { - callback.onResult(account_appAccount.ResultCode.SUCCESS, {}); - } + setProperties(options, callback) { + callback.onResult(account_appAccount.ResultCode.SUCCESS, {}); + } - checkAccountLabels(name, labels, callback) { - var result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: false}; - callback.onResult(account_appAccount.ResultCode.SUCCESS, result); - } - - isAccountRemovable(name, callback) { - var result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: true}; - callback.onResult(account_appAccount.ResultCode.SUCCESS, result); - } + checkAccountLabels(name, labels, callback) { + var result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: false}; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + } + + isAccountRemovable(name, callback) { + var result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: true}; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + } } var authenticator = null; export default { - onConnect(want) { - authenticator = new MyAuthenticator(); - return authenticator.getRemoteObject(); - } + onConnect(want) { + authenticator = new MyAuthenticator(); + return authenticator.getRemoteObject(); + } } ``` diff --git a/en/application-dev/reference/apis/js-apis-bluetooth.md b/en/application-dev/reference/apis/js-apis-bluetooth.md index b852a673ab6ca120497e1c40443d19990cfbd74b..aa9e1937cd66e83262211280f42f11f468e2d200 100644 --- a/en/application-dev/reference/apis/js-apis-bluetooth.md +++ b/en/application-dev/reference/apis/js-apis-bluetooth.md @@ -1,8 +1,9 @@ -# Bluetooth +# @ohos.bluetooth The **Bluetooth** module provides classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -202,7 +203,7 @@ Obtains the connection state of a profile. | Name | Type | Mandatory | Description | | --------- | --------- | ---- | ------------------------------------- | -| ProfileId | profileId | Yes | ID of the target profile, for example, **PROFILE_A2DP_SOURCE**.| +| ProfileId | profileId | Yes | ID of the profile to obtain, for example, **PROFILE_A2DP_SOURCE**.| **Return value** @@ -1280,10 +1281,6 @@ Obtains the connected devices. **System capability**: SystemCapability.Communication.Bluetooth.Core -**Parameters** - -No value is returned. - **Return value** | Type | Description | @@ -2695,8 +2692,6 @@ Obtains all services of the remote BLE device. This API uses a promise to return **System capability**: SystemCapability.Communication.Bluetooth.Core -**Parameters** - **Return value** | Type | Description | @@ -2830,7 +2825,7 @@ Reads the descriptor contained in the specific characteristic of the remote BLE | Name | Type | Mandatory | Description | | ---------- | ---------------------------------------- | ---- | ----------------------- | | descriptor | [BLEDescriptor](#bledescriptor) | Yes | Descriptor to read. | -| callback | AsyncCallback<[BLECharacteristic](#blecharacteristic)> | Yes | Callback invoked to return the descriptor read.| +| callback | AsyncCallback<[BLEDescriptor](#bledescriptor)> | Yes | Callback invoked to return the descriptor read.| **Return value** @@ -3309,7 +3304,7 @@ Enumerates the scan modes. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ---------------------------------------- | ---- | --------------- | | SCAN_MODE_NONE | 0 | No scan mode. | | SCAN_MODE_CONNECTABLE | 1 | Connectable mode. | @@ -3324,7 +3319,7 @@ Enumerates the pairing states. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ------------------ | ---- | ------ | | BOND_STATE_INVALID | 0 | Invalid pairing.| | BOND_STATE_BONDING | 1 | Pairing. | @@ -3350,7 +3345,7 @@ Enumerates the SPP link types. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ---------- | ---- | ------------- | | SPP_RFCOMM | 0 | Radio frequency communication (RFCOMM) link type.| @@ -3510,7 +3505,7 @@ Enumerates the profile connection states. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ------------------- | ---- | -------------- | | STATE_DISCONNECTED | 0 | Disconnected. | | STATE_CONNECTING | 1 | Connecting.| @@ -3558,7 +3553,7 @@ Enumerates the scan duty options. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | --------------------- | ---- | ------------ | | SCAN_MODE_LOW_POWER | 0 | Low-power mode, which is the default value.| | SCAN_MODE_BALANCED | 1 | Balanced mode. | @@ -3571,7 +3566,7 @@ Enumerates the hardware match modes of BLE scan filters. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | --------------------- | ---- | ---------------------------------------- | | MATCH_MODE_AGGRESSIVE | 1 | Hardware reports the scan result with a lower threshold of signal strength and few number of matches in a duration. This is the default value.| | MATCH_MODE_STICKY | 2 | Hardware reports the scan result with a higher threshold of signal strength and sightings. | @@ -3596,7 +3591,7 @@ Enumerates the Bluetooth states. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | --------------------- | ---- | ------------------ | | STATE_OFF | 0 | Bluetooth is turned off. | | STATE_TURNING_ON | 1 | Bluetooth is being turned on. | @@ -3641,7 +3636,7 @@ Defines the content of a BLE advertisement packet. | Name | Type | Readable | Writable | Description | | ---------------- | ------------------- | ---- | ---- | ------------------ | -| manufactureId | Array<string> | Yes | Yes | Manufacturer ID allocated by the Bluetooth SIG.| +| manufactureId | number | Yes | Yes | Manufacturer ID allocated by the Bluetooth SIG.| | manufactureValue | ArrayBuffer | Yes | Yes | Manufacturer data. | @@ -3713,7 +3708,7 @@ Enumerates the major classes of Bluetooth devices. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ------------------- | ------ | ---------- | | MAJOR_MISC | 0x0000 | Miscellaneous device. | | MAJOR_COMPUTER | 0x0100 | Computer. | @@ -3734,7 +3729,7 @@ Enumerates the major and minor classes of Bluetooth devices. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ---------------------------------------- | ------ | --------------- | | COMPUTER_UNCATEGORIZED | 0x0100 | Unclassified computer. | | COMPUTER_DESKTOP | 0x0104 | Desktop computer. | @@ -3830,7 +3825,7 @@ Enumerates the A2DP playing states. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ----------------- | ------ | ------- | | STATE_NOT_PLAYING | 0x0000 | Not playing. | | STATE_PLAYING | 0x0001 | Playing.| @@ -3842,9 +3837,9 @@ Enumerates the Bluetooth profiles. API version 9 is added with **PROFILE_HID_HOS **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | -------------------------------- | ------ | --------------- | -| PROFILE_A2DP_SOURCE | 0x0001 | A2DP profile.| -| PROFILE_HANDS_FREE_AUDIO_GATEWAY | 0x0004 | HFP profile. | -| PROFILE_HID_HOST9+ | 0x0006 | Human Interface Device (HID) profile. | -| PROFILE_PAN_NETWORK9+ | 0x0007 | PAN profile. | +| PROFILE_A2DP_SOURCE | 1 | A2DP profile.| +| PROFILE_HANDS_FREE_AUDIO_GATEWAY | 4 | HFP profile. | +| PROFILE_HID_HOST9+ | 6 | Human Interface Device (HID) profile. | +| PROFILE_PAN_NETWORK9+ | 7 | PAN profile. | diff --git a/en/application-dev/reference/apis/js-apis-cardEmulation.md b/en/application-dev/reference/apis/js-apis-cardEmulation.md index b4f3906b02b1dea7dabd558173010a37e65c2c19..329a2e6126de45fe401a748bd580a372cd1dc18e 100644 --- a/en/application-dev/reference/apis/js-apis-cardEmulation.md +++ b/en/application-dev/reference/apis/js-apis-cardEmulation.md @@ -1,11 +1,11 @@ -# Standard NFC Card Emulation +# @ohos.nfc.cardEmulation The **cardEmulation** module implements Near-Field Communication (NFC) card emulation. You can use the APIs provided by this module to determine the card emulation type supported and implement Host-based Card Emulation (HCE). -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. - ## Modules to Import ``` @@ -18,7 +18,7 @@ Enumerates the NFC card emulation types. **System capability**: SystemCapability.Communication.NFC.Core -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | HCE | 0 | HCE.| | UICC | 1 | Subscriber identity module (SIM) card emulation.| @@ -30,8 +30,6 @@ isSupported(feature: number): boolean Checks whether a certain type of card emulation is supported. -**Required permissions**: ohos.permission.NFC_CARD_EMULATION - **System capability**: SystemCapability.Communication.NFC.Core **Parameters** @@ -42,9 +40,9 @@ Checks whether a certain type of card emulation is supported. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the card emulation type is supported; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the card emulation type is supported; returns **false** otherwise.| ## HceService8+ diff --git a/en/application-dev/reference/apis/js-apis-connectedTag.md b/en/application-dev/reference/apis/js-apis-connectedTag.md index 57cf8eadb5a07bcd3038c67d4d582ab4359d2ea2..1bfb1231c3c4584fe4d608891bdf2be54458e425 100644 --- a/en/application-dev/reference/apis/js-apis-connectedTag.md +++ b/en/application-dev/reference/apis/js-apis-connectedTag.md @@ -1,18 +1,17 @@ -# Active Tag +# @ohos.connectedTag -The **connectedTag** module provides methods for using active tags. You can use the APIs provided by this module to initialize the active tag chip and read and write active tags. +The **connectedTag** module provides APIs for using active tags. You can use the APIs to initialize the active tag chip and read and write active tags. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. - ## Modules to Import -``` +```js import connectedTag from '@ohos.connectedTag'; ``` - ## connectedTag.init init(): boolean @@ -23,11 +22,11 @@ Initializes the active tag chip. **System capability**: SystemCapability.Communication.ConnectedTag -- Return value - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the initialization is successful; returns **false** otherwise.| +**Return value** +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## connectedTag.uninit @@ -39,125 +38,136 @@ Uninitializes the active tag resources. **System capability**: SystemCapability.Communication.ConnectedTag -- Return value - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Return value** +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## connectedTag.readNdefTag readNdefTag(): Promise<string> -Reads the content of this active tag. This method uses a promise to return the result. +Reads the content of this active tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.ConnectedTag -- Return value - | **Type**| **Description**| - | -------- | -------- | - | Promise<string> | Promise used to return the content of the active tag.| +**Return value** -- Example - ``` - import connectedTag from '@ohos.connectedTag'; +| **Type**| **Description**| +| -------- | -------- | +| Promise<string> | Promise used to return the content of the active tag.| - connectedTag.readNdefTag().then(result => { - console.log("promise recv ndef response: " + result); - }); - ``` +**Example** + +```js +import connectedTag from '@ohos.connectedTag'; + +connectedTag.readNdefTag().then((data) => { + console.log("connectedTag readNdefTag Promise data = " + data); +}).catch((err)=> { + console.log("connectedTag readNdefTag Promise err: " + err); +}); +``` ## connectedTag.readNdefTag readNdefTag(callback: AsyncCallback<string>): void -Reads the content of this active tag. This method uses an asynchronous callback to return the result. +Reads the content of this active tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.ConnectedTag -- Parameters - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<string> | Yes| Callback invoked to return the active tag content obtained.| +**Parameters** -- Example - ``` - import connectedTag from '@ohos.connectedTag'; - - connectedTag.readNdefTag(result => { - console.log("callback recv ndef response: " + result); - }); - ``` +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<string> | Yes| Callback invoked to return the active tag content obtained.| + +**Example** + +```js +import connectedTag from '@ohos.connectedTag'; + +connectedTag.readNdefTag((err, data)=> { + if (err) { + console.log("connectedTag readNdefTag AsyncCallback err: " + err); + } else { + console.log("connectedTag readNdefTag AsyncCallback data: " + data); + } +}); +``` ## connectedTag.writeNdefTag writeNdefTag(data: string): Promise<void> -Writes data to this active tag. This method uses a promise to return the result. +Writes data to this active tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.ConnectedTag -- Parameters - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | data | string | Yes| Data to write. The maximum length is 1024 bytes.| - -- Return value - | **Type**| **Description**| - | -------- | -------- | - | Promise<void> | Promise used to return the result. This method returns no value.| - -- Example - ``` - import connectedTag from '@ohos.connectedTag'; - - writeNdefTag.write("010203") - .then((value) => { - // Data is written to the tag. - console.log(`success to write event: ${value}`); - }).catch((err) => { - // Failed to write data to the tag. - console.error(`failed to write event because ${err.code}`); - }); - ``` +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| data | string | Yes| Data to write. The maximum length is 1024 bytes.| + +**Return value** + +| **Type**| **Description**| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +import connectedTag from '@ohos.connectedTag'; + +var rawData = "010203"; // change it tobe correct. +connectedTag.writeNdefTag(rawData).then(() => { + console.log("connectedTag writeNdefTag Promise success."); +}).catch((err)=> { + console.log("connectedTag writeNdefTag Promise err: " + err); +}); +``` ## connectedTag.writeNdefTag writeNdefTag(data: string, callback: AsyncCallback<void>): void -Writes data to this active tag. This method uses an asynchronous callback to return the result. +Writes data to this active tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.ConnectedTag -- Parameters - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | data | string | Yes| Data to write. The maximum length is 1024 bytes.| - | callback | AsyncCallback<string> | Yes| Callback invoked to return the active tag content obtained.| - -- Example - ``` - import connectedTag from '@ohos.connectedTag'; - - connectedTag.writeNdefTag("010203", (err, value) => { - if (err) { - // Failed to write data to the tag. - console.error(`failed to write event because ${err.code}`); - return; - } - - // Data is written to the tag. - console.log(`success to write event: ${value}`); - }); - ``` +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| data | string | Yes| Data to write. The maximum length is 1024 bytes.| +| callback | AsyncCallback<void> | Yes| Callback invoked to return the active tag content obtained.| + +**Example** + +```js +import connectedTag from '@ohos.connectedTag'; + +var rawData = "010203"; // change it tobe correct. +connectedTag.writeNdefTag(rawData, (err)=> { + if (err) { + console.log("connectedTag writeNdefTag AsyncCallback err: " + err); + } else { + console.log("connectedTag writeNdefTag AsyncCallback success."); + } +}); +``` ## connectedTag.on('notify') @@ -169,18 +179,12 @@ Registers the NFC field strength state events. **System capability**: SystemCapability.Communication.ConnectedTag -- Parameters - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **notify**.| - | callback | Callback<number> | Yes| Callback invoked to return the field strength state.| - -- Enumerates the field strength states. - | **Value**| **Description**| - | -------- | -------- | - | 0 | Field off.| - | 1 | Field on.| +**Parameters** +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **notify**.| +| callback | Callback<number> | Yes| Callback used to return the [NfcRfType](#nfcrftype).| ## connectedTag.off('notify') @@ -192,36 +196,54 @@ Unregisters the NFC field strength state events. **System capability**: SystemCapability.Communication.ConnectedTag -- Parameters - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **notify**.| - | callback | Callback<number> | No| Callback used to return the field strength state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| - -- Example - ``` - import connectedTag from '@ohos.connectedTag'; - - var NFC_RF_NOTIFY = "notify"; - - var recvNfcRfNotifyFunc = result => { - console.info("nfc rf receive state: " + result); - } - - // Register event notification. - connectedTag.on(NFC_RF_NOTIFY, recvNfcRfNotifyFunc); - - // Unregister event notification. - connectedTag.off(NFC_RF_NOTIFY, recvNfcRfNotifyFunc); - ``` +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **notify**.| +| callback | Callback<number> | No| Callback used to return the field strength state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + +**Example** + +```js +import connectedTag from '@ohos.connectedTag'; + +// Register the event. +connectedTag.on("notify", (err, rfState)=> { + if (err) { + console.log("connectedTag on Callback err: " + err); + } else { + console.log("connectedTag on Callback rfState: " + rfState); + } +}); + +var initStatus = connectedTag.init(); +console.log("connectedTag init status: " + initStatus); + +// Add nfc connecected tag business oprations here... +// connectedTag.writeNdefTag(rawData) +// connectedTag.readNdefTag() + +var uninitStatus = connectedTag.uninit(); +console.log("connectedTag uninit status: " + uninitStatus); + +// Unregister the event. +connectedTag.off("notify", (err, rfState)=> { + if (err) { + console.log("connectedTag off Callback err: " + err); + } else { + console.log("connectedTag off Callback rfState: " + rfState); + } +}); +``` ## NfcRfType -Enumerates the NFC states. +Enumerates the NFC field strength states. **System capability**: SystemCapability.Communication.ConnectedTag -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | -| NFC_RF_LEAVE | 0 | Field on.| +| NFC_RF_LEAVE | 0 | Field off.| | NFC_RF_ENTER | 1 | Field on.| diff --git a/en/application-dev/reference/apis/js-apis-distributed-account.md b/en/application-dev/reference/apis/js-apis-distributed-account.md index 4dc76cd2d39f631d74d5c51b61259bd88a1ea924..5a4a93c46fbe2492cecf4569f8e4e7db63469371 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-account.md +++ b/en/application-dev/reference/apis/js-apis-distributed-account.md @@ -1,18 +1,17 @@ -# Distributed Account Management +# @ohos.account.distributedAccount -The distributedAccount module provides basic functions for managing distributed accounts, including querying and updating account login status. +The **distributedAccount** module provides APIs for managing distributed accounts, including querying and updating account login states. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. - ## Modules to Import ```js import account_distributedAccount from '@ohos.account.distributedAccount'; ``` - ## account_distributedAccount.getDistributedAccountAbility getDistributedAccountAbility(): DistributedAccountAbility @@ -25,7 +24,7 @@ Obtains a **DistributedAccountAbility** instance. | Type| Description| | -------- | -------- | - | [DistributedAccountAbility](#distributedaccountability) | **DistributedAccountAbility** instance obtained. This instance provides methods for querying and updating the login state of a distributed account.| + | [DistributedAccountAbility](#distributedaccountability) | **DistributedAccountAbility** instance obtained. This instance provides APIs for querying and updating the login state of a distributed account.| **Example** ```js @@ -34,13 +33,88 @@ Obtains a **DistributedAccountAbility** instance. ## DistributedAccountAbility -Provides methods for querying and updating the login state of a distributed account. You must obtain a **DistributedAccountAbility** instance first. +Provides APIs for querying and updating the login state of a distributed account. You must obtain a **DistributedAccountAbility** instance first. + +### getOsAccountDistributedInfo9+ + +getOsAccountDistributedInfo(callback: AsyncCallback<DistributedInfo>): void + +Obtains distributed account information. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS, ohos.permission.GET_DISTRIBUTED_ACCOUNTS, or ohos.permission.DISTRIBUTED_DATASYNC + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the distributed account information obtained. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message| +| -------- | ------------------- | +| 12300001 | System service exception. | + +**Example** + ```js + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + try { + accountAbility.getOsAccountDistributedInfo((err, data) => { + console.log("getOsAccountDistributedInfo err: " + JSON.stringify(err)); + console.log('Query account info name: ' + data.name); + console.log('Query account info id: ' + data.id); + }); + } catch (e) { + console.log("getOsAccountDistributedInfo exception: " + JSON.stringify(e)); + } + ``` -### queryOsAccountDistributedInfo +### getOsAccountDistributedInfo9+ + +getOsAccountDistributedInfo(): Promise<DistributedInfo> + +Obtains distributed account information. This API uses a promise to return the result. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS, ohos.permission.GET_DISTRIBUTED_ACCOUNTS, or ohos.permission.DISTRIBUTED_DATASYNC + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[DistributedInfo](#distributedinfo)> | Promise used to return the distributed account information obtained.| + +**Error codes** + +| ID| Error Message| +| -------- | ------------------- | +| 12300001 | System service exception. | + +**Example** + ```js + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + try { + accountAbility.getOsAccountDistributedInfo().then((data) => { + console.log('Query account info name: ' + data.name); + console.log('Query account info id: ' + data.id); + }).catch((err) => { + console.log("getOsAccountDistributedInfo err: " + JSON.stringify(err)); + }); + } catch (e) { + console.log("getOsAccountDistributedInfo exception: " + JSON.stringify(e)); + } + ``` +### queryOsAccountDistributedInfo(deprecated) queryOsAccountDistributedInfo(callback: AsyncCallback<DistributedInfo>): void Obtains distributed account information. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getOsAccountDistributedInfo](#getosaccountdistributedinfo9). **System capability**: SystemCapability.Account.OsAccount @@ -50,24 +124,28 @@ Obtains distributed account information. This API uses an asynchronous callback | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | Yes| Callback invoked to return the distributed account information obtained.| + | callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the distributed account information obtained. Otherwise, **err** is an error object.| **Example** ```js const accountAbility = account_distributedAccount.getDistributedAccountAbility(); - accountAbility.queryOsAccountDistributedInfo((err, data) => { + accountAbility.queryOsAccountDistributedInfo((err, data) => { console.log("queryOsAccountDistributedInfo err: " + JSON.stringify(err)); console.log('Query account info name: ' + data.name); console.log('Query account info id: ' + data.id); }); ``` -### queryOsAccountDistributedInfo +### queryOsAccountDistributedInfo(deprecated) queryOsAccountDistributedInfo(): Promise<DistributedInfo> Obtains distributed account information. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getOsAccountDistributedInfo](#getosaccountdistributedinfo9-1). + **System capability**: SystemCapability.Account.OsAccount **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC @@ -81,7 +159,7 @@ Obtains distributed account information. This API uses a promise to return the r **Example** ```js const accountAbility = account_distributedAccount.getDistributedAccountAbility(); - accountAbility.queryOsAccountDistributedInfo().then((data) => { + accountAbility.queryOsAccountDistributedInfo().then((data) => { console.log('Query account info name: ' + data.name); console.log('Query account info id: ' + data.id); }).catch((err) => { @@ -89,12 +167,97 @@ Obtains distributed account information. This API uses a promise to return the r }); ``` -### updateOsAccountDistributedInfo +### setOsAccountDistributedInfo9+ + +setOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCallback<void>): void + +Sets the distributed account information. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information to set.| + | callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the distributed account information is set successfully, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message| +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid accountInfo. | +| 12300003 | Account not found. | + +**Example** + ```js + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; + try { + accountAbility.setOsAccountDistributedInfo(accountInfo, (err) => { + console.log("setOsAccountDistributedInfo err: " + JSON.stringify(err)); + }); + } catch (e) { + console.log("setOsAccountDistributedInfo exception: " + JSON.stringify(e)); + } + ``` + +### setOsAccountDistributedInfo9+ + +setOsAccountDistributedInfo(accountInfo: DistributedInfo): Promise<void> + +Sets the distributed account information. This API uses a promise to return the result. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information to set.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message| +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | invalid accountInfo. | + +**Example** + ```js + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; + try { + accountAbility.setOsAccountDistributedInfo(accountInfo).then(() => { + console.log('setOsAccountDistributedInfo Success'); + }).catch((err) => { + console.log("setOsAccountDistributedInfo err: " + JSON.stringify(err)); + }); + } catch (e) { + console.log("setOsAccountDistributedInfo exception: " + JSON.stringify(e)); + } + ``` +### updateOsAccountDistributedInfo(deprecated) updateOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCallback<void>): void Updates distributed account information. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setOsAccountDistributedInfo](#setosaccountdistributedinfo9). + **System capability**: SystemCapability.Account.OsAccount **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -103,24 +266,26 @@ Updates distributed account information. This API uses an asynchronous callback | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the distributed account information is updated.| + | accountInfo | [DistributedInfo](#distributedinfo) | Yes| New distributed account information.| + | callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the distributed account information is set successfully, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** ```js const accountAbility = account_distributedAccount.getDistributedAccountAbility(); let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; - accountAbility.updateOsAccountDistributedInfo(accountInfo, (err) => { + accountAbility.updateOsAccountDistributedInfo(accountInfo, (err) => { console.log("queryOsAccountDistributedInfo err: " + JSON.stringify(err)); }); ``` -### updateOsAccountDistributedInfo +### updateOsAccountDistributedInfo(deprecated) updateOsAccountDistributedInfo(accountInfo: DistributedInfo): Promise<void> -Updates distributed account information. This API uses a promise to return the result. - +Updates the distributed account information. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setOsAccountDistributedInfo](#setosaccountdistributedinfo9-1). **System capability**: SystemCapability.Account.OsAccount **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -129,13 +294,13 @@ Updates distributed account information. This API uses a promise to return the r | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information.| + | accountInfo | [DistributedInfo](#distributedinfo) | Yes| New distributed account information.| **Return value** | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result.| + | Promise<void> | Promise that returns no value.| **Example** ```js @@ -147,8 +312,6 @@ Updates distributed account information. This API uses a promise to return the r console.log("updateOsAccountDistributedInfo err: " + JSON.stringify(err)); }); ``` - - ## DistributedInfo Defines distributed OS account information. @@ -157,7 +320,9 @@ Defines distributed OS account information. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of a distributed account. It must be a non-null string.| -| id | string | Yes| UID of a distributed account. It must be a non-null string.| -| event | string | Yes| Login state of a distributed account. The state can be login, logout, token invalid, or logoff, which correspond to the following strings respectively:
- Ohos.account.event.LOGIN
- Ohos.account.event.LOGOUT
- Ohos.account.event.TOKEN_INVALID
- Ohos.account.event.LOGOFF | -| scalableData | object | No| Extended information about a distributed account. Customized information is passed in key-value pairs.
Note: This parameter is reserved and not used in query and update methods.| +| name | string | Yes| Name of the distributed account. It must be a non-null string.| +| id | string | Yes| UID of the distributed account. It must be a non-null string.| +| event | string | Yes| Login state of the distributed account. The state can be login, logout, token invalid, or logoff, which correspond to the following strings respectively:
- Ohos.account.event.LOGIN
- Ohos.account.event.LOGOUT
- Ohos.account.event.TOKEN_INVALID
- Ohos.account.event.LOGOFF | +| nickname9+ | string | No| Nickname of the distributed account. It must be a non-null string.| +| avatar9+ | string | No| Avatar of the distributed account. It must be a non-null string.| +| scalableData | object | No| Extended information about the distributed account, passed in key-value (KV) pairs.
**NOTE**
This parameter is reserved and not used in the setters and getters.| diff --git a/en/application-dev/reference/apis/js-apis-distributedKVStore.md b/en/application-dev/reference/apis/js-apis-distributedKVStore.md new file mode 100644 index 0000000000000000000000000000000000000000..940fec508984a1a6dea0718888b51eb2e4b43e47 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-distributedKVStore.md @@ -0,0 +1,6657 @@ +# # @ohos.data.distributedKVStore + +The **distributedKVStore** module implements collaboration between databases for different devices that forms a Super Device. The APIs provided by this module can be used to save data to a distributed key-value (KV) store and perform operations, such as adding, deleting, modifying, querying, and synchronizing data in distributed KV stores. + +The **distributedKVStore** module provides the following functions: + +- [KVManager](#kvmanager): provides a **KVManager** instance to obtain KV store information. +- [KVStoreResultSet](#kvstoreresultset): provides APIs for obtaining KV store result sets. +- [Query](#query): provides APIs for setting predicates and querying data using predicates. +- [SingleKVStore](#singlekvstore): provides APIs for querying data in single KV stores and synchronizing data. The single KV stores manage data without distinguishing devices. +- [DeviceKVStore](#devicekvstore): provides APIs for querying in device KV stores and synchronizing data. This class inherits from [SingleKVStore](#singlekvstore). The device KV stores manage data by device. + +> **NOTE**
+> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import distributedKVStore from '@ohos.data.distributedKVStore'; +``` + +## KVManagerConfig + +Provides the **KVManager** instance configuration, including the bundle name of the invoker and the application context. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Type | Mandatory| Description | +| ---------- | --------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes |Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| bundleName | string | Yes | Bundle name. | + +## Constants + +Provides constants of the distributed KV store. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Value | Description | +| --------------------- | ------- | --------------------------------------- | +| MAX_KEY_LENGTH | 1024 | Maximum length of a key in the distributed KV store, in bytes. | +| MAX_VALUE_LENGTH | 4194303 | Maximum length of a value in the distributed KV store, in bytes.| +| MAX_KEY_LENGTH_DEVICE | 896 | Maximum length of a device key, in bytes. | +| MAX_STORE_ID_LENGTH | 128 | Maximum length of a KV store ID, in bytes. | +| MAX_QUERY_LENGTH | 512000 | Maximum query length, in bytes. | +| MAX_BATCH_SIZE | 128 | Maximum number of batch operations. | + +## ValueType + +Enumerates the data types. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Description | +| ---------- | ---------------------- | +| STRING | String. | +| INTEGER | Integer. | +| FLOAT | Float (single-precision floating point). | +| BYTE_ARRAY | Byte array.| +| BOOLEAN | Boolean. | +| DOUBLE | Double (double-precision floating point).| + +## Value + +Defines the **value** object in a KV store. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Type |Mandatory | Description | +| ----- | ------- |-----|------------------------ | +| type | [ValueType](#valuetype) | Yes|Type of the value. | +| value | Uint8Array \| string \| number \| boolean| Yes|Value of the KV pair stored in the KV store. | + +## Entry + +Defines the KV pairs stored in the KV store. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Type | Mandatory| Description | +| ----- | --------------- | ---- | -------- | +| key | string | Yes | Key of the KV pair stored in the KV store. | +| value | [Value](#value) | Yes | Value of the KV pair stored in the KV store.| + +## ChangeNotification + +Defines the content of a data change notification, including inserted data, updated data, deleted data, and device ID. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Type | Mandatory | Description | +| ------------- | ----------------- | ---- | ------------------------ | +| insertEntries | [Entry](#entry)[] | Yes | Data inserted. | +| updateEntries | [Entry](#entry)[] | Yes | Data updated. | +| deleteEntries | [Entry](#entry)[] | Yes | Data deleted. | +| deviceId | string | Yes | UUID of the device.| + +## SyncMode + +Enumerates the synchronization modes. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Description | +| --------- | ---------------------------------------------------- | +| PULL_ONLY | Pull data from the peer end to the local end only. | +| PUSH_ONLY | Push data from the local end to the peer end only. | +| PUSH_PULL | Push data from the local end to the peer end and then pull data from the peer end to the local end.| + +## SubscribeType + +Enumerates the subscription types. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Description | +| --------------------- | ---------------------------- | +| SUBSCRIBE_TYPE_LOCAL | Local data changes. | +| SUBSCRIBE_TYPE_REMOTE | Remote data changes. | +| SUBSCRIBE_TYPE_ALL | Local and remote data changes.| + +## KVStoreType + +Enumerates the distributed KV store types. + +| Name | Description | +| -------------------- | ------------------------------------------------------------ | +| DEVICE_COLLABORATION | Device KV store.
The device KV store manages data by device, which eliminates conflicts. Data can be queried by device.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| +| SINGLE_VERSION | Single KV store.
The single KV store does not differentiate data by device. If the same key is modified by different devices, the data will be overwritten.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| + +## SecurityLevel + +Enumerates the KV store security levels. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Description | +| -------: | ------------------------------------------------------------ | +| S1 | The KV store security level is low. If data leakage occurs, minor impact will be caused on the database. For example, a KV store that contains system data such as wallpapers.| +| S2 | The KV store security level is medium. If data leakage occurs, moderate impact will be caused on the database. For example, a KV store that contains information created by users or call records, such as audio or video clips.| +| S3 | The KV store security level is high. If data leakage occurs, major impact will be caused on the database. For example, a KV store that contains information such as user fitness, health, and location data.| +| S4 | The KV store security level is critical. If data leakage occurs, severe impact will be caused on the database. For example, a KV store that contains information such as authentication credentials and financial data.| + +## Options + +Provides KV store configuration. + +| Name | Type | Mandatory| Description | +| --------------- | -------------- | ---- | -------------------------| +| createIfMissing | boolean | No | Whether to create a KV store if no database file exists. By default, a KV store is created.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| +| encrypt | boolean | No | Whether to encrypt database files. By default, database files are not encrypted.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| +| backup | boolean | No | Whether to back up database files. By default, database files are backed up.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| +| autoSync | boolean | No | Whether database files are automatically synchronized. By default, database files are not automatically synchronized.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC| +| kvStoreType | [KVStoreType](#kvstoretype) | No | Type of the KV store to create. By default, a device KV store is created. The device KV store stores data for multiple devices that collaborate with each other.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| +| securityLevel | [SecurityLevel](#securitylevel) | Yes |Security level of the KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| +| schema | [Schema](#schema) | No | Schema used to define the values stored in the KV store. By default, **schema** is not used.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| + +## Schema + +Defines the schema of a KV store. You can create a **Schema** object and place it in [Options](#options) when creating or opening a KV store. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +| Name | Type | Readable| Writable| Description | +| ------- | ----------------------- | ---- | ---- | -------------------------- | +| root | [FieldNode](#fieldnode) | Yes | Yes | JSON root object. | +| indexes | Array\ | Yes | Yes | String array in JSON format.| +| mode | number | Yes | Yes | Schema mode. | +| skip | number | Yes | Yes | Size of a skip of the schema. | + +### constructor + +constructor() + +A constructor used to create a **Schema** instance. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +## FieldNode + +Represents a **Schema** instance, which provides the methods for defining the values stored in a KV store. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +| Name | Type | Readable| Writable| Description | +| -------- | ------- | ---- | ---- | ------------------------------ | +| nullable | boolean | Yes | Yes | Whether the database field can be null. | +| default | string | Yes | Yes | Default value of a **FieldNode**. | +| type | number | Yes | Yes | Value of the data type corresponding to the specified node.| + +### constructor + +constructor(name: string) + +A constructor used to create a **FieldNode** instance with a string field. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | --------------- | +| name | string | Yes | Value of **FieldNode**.| + +### appendChild + +appendChild(child: FieldNode): boolean + +Appends a child node to this **FieldNode**. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------- | +| child | [FieldNode](#fieldnode) | Yes | Child node to append.| + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +import ddm from '@ohos.data.distributedKVStore'; + +try { + let node = new ddm.FieldNode("root"); + let child1 = new ddm.FieldNode("child1"); + let child2 = new ddm.FieldNode("child2"); + let child3 = new ddm.FieldNode("child3"); + node.appendChild(child1); + node.appendChild(child2); + node.appendChild(child3); + console.log("appendNode " + JSON.stringify(node)); + child1 = null; + child2 = null; + child3 = null; + node = null; +} catch (e) { + console.log("AppendChild " + e); +} +``` + +## distributedKVStore.createKVManager + +createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void + +Creates a **KVManager** instance to manage KV stores. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ----------------------------------------------------------- | +| config | [KVManagerConfig](#kvmanagerconfig) | Yes | **KVManager** instance configuration, including the bundle name of the invoker and the context of the application.| +| callback | AsyncCallback<[KVManager](#kvmanager)> | Yes | Callback invoked to return the **KVManager** instance created. | + +**Example** + +Stage model: + +```js +import AbilityStage from '@ohos.application.Ability' +let kvManager; +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage onCreate") + let context = this.context + const kvManagerConfig = { + context: context, + bundleName: 'com.example.datamanagertest', + } + try { + distributedKVStore.createKVManager(kvManagerConfig, function (err, manager) { + if (err) { + console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`); + return; + } + console.log("Created KVManager successfully"); + kvManager = manager; + }); + } catch (e) { + console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); + } + } +} +``` + +FA model: + +```js +import featureAbility from '@ohos.ability.featureAbility' +let kvManager; +let context = featureAbility.getContext() +const kvManagerConfig = { + context: context, + bundleName: 'com.example.datamanagertest', +} +try { + distributedKVStore.createKVManager(kvManagerConfig, function (err, manager) { + if (err) { + console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`); + return; + } + console.log("Created KVManager successfully"); + kvManager = manager; + }); +} catch (e) { + console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); +} +``` + +## distributedKVStore.createKVManager + +createKVManager(config: KVManagerConfig): Promise<KVManager> + +Creates a **KVManager** instance to manage KV stores. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | --------------------------------------------------------- | +| config | [KVManagerConfig](#kvmanager) | Yes | Configuration of the **KVManager** instance, including the bundle name and user information of the caller.| + +**Return value** + +| Type | Description | +| -------------------------------------- | ------------------------------------------ | +| Promise<[KVManager](#kvmanager)> | Promise used to return the **KVManager** instance created.| + +**Example** + +Stage model: + +```js +import AbilityStage from '@ohos.application.Ability' +let kvManager; +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage onCreate") + let context = this.context + const kvManagerConfig = { + context: context, + bundleName: 'com.example.datamanagertest', + } + try { + distributedKVStore.createKVManager(kvManagerConfig).then((manager) => { + console.log("Created KVManager successfully"); + kvManager = manager; + }).catch((err) => { + console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`); + }); + } catch (e) { + console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); + } + } +} +``` + +FA model: + +```js +import featureAbility from '@ohos.ability.featureAbility' +let kvManager; +let context = featureAbility.getContext() +const kvManagerConfig = { + context: context, + bundleName: 'com.example.datamanagertest', +} +try { + distributedKVStore.createKVManager(kvManagerConfig).then((manager) => { + console.log("Created KVManager successfully"); + kvManager = manager; + }).catch((err) => { + console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); +} +``` + +## KVManager + +Provides an instance to obtain information about a distributed KV store. Before calling any API in **KVManager**, you must use [createKVManager](#distributedkvstorecreatekvmanager) to create a **KVManager** instance. + +### getKVStore + +getKVStore<T >(storeId: string, options: Options, callback: AsyncCallback<T>): void + +Creates and obtains a distributed KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------------------------------ | +| storeId | string | Yes | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| +| options | [Options](#options) | Yes | Configuration of the KV store to create. | +| callback | AsyncCallback<T> | Yes | Callback invoked to return the distributed single or device KV store created. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| ID| **Error Message** | +| ------------ | ------------------------------------------- | +| 15100002 | Open existed database with changed options. | +| 15100003 | Database corrupted. | + +**Example** + +```js +let kvStore; +let kvManager; +try { + const options = { + createIfMissing: true, + encrypt: false, + backup: false, + autoSync: true, + kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, + securityLevel: distributedKVStore.SecurityLevel.S2, + }; + kvManager.getKVStore('storeId', options, function (err, store) { + if (err) { + console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); + return; + } + console.log("Obtained the KVStore successfully."); + kvStore = store; + }); +} catch (e) { + console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### getKVStore + +getKVStore<T >(storeId: string, options: Options): Promise<T> + +Creates and obtains a distributed KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ------------------------------------------------------------ | +| storeId | string | Yes | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| +| options | [Options](#options) | Yes | Configuration of the distributed KV store to create. | + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------------------------------------ | +| Promise<T> | Promise used to return the distributed single or device KV store created.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| ID| **Error Message** | +| ------------ | ------------------------------------------- | +| 15100002 | Open existed database with changed options. | +| 15100003 | Database corrupted. | + +**Example** + +```js +let kvStore; +let kvManager; +try { + const options = { + createIfMissing: true, + encrypt: false, + backup: false, + autoSync: true, + kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, + securityLevel: distributedKVStore.SecurityLevel.S2, + }; + kvManager.getKVStore('storeId', options).then((store) => { + console.log("Obtained the KVStore successfully."); + kvStore = store; + }).catch((err) => { + console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### closeKVStore + +closeKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): void + +Closes a distributed KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| appId | string | Yes | Bundle name of the app that invokes the KV store. | +| storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +let kvStore; +let kvManager; +const options = { + createIfMissing: true, + encrypt: false, + backup: false, + autoSync: true, + kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, + schema: '', + securityLevel: distributedKVStore.SecurityLevel.S2, +} +try { + kvManager.getKVStore('storeId', options, async function (err, store) { + console.log('Obtained the KVStore successfully.'); + kvStore = store; + kvManager.closeKVStore('appId', 'storeId', function (err, data) { + if (err != undefined) { + console.error(`Fail to close KVStore.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Closed the KVStore successfully.'); + }); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### closeKVStore + +closeKVStore(appId: string, storeId: string): Promise<void> + +Closes a distributed KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| ------- | -------- | ---- | ------------------------------------------------------------ | +| appId | string | Yes | Bundle name of the app that invokes the KV store. | +| storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise that returns no value.| + +**Example** + +```js +let kvManager; +let kvStore; +const options = { + createIfMissing: true, + encrypt: false, + backup: false, + autoSync: true, + kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, + schema: '', + securityLevel: distributedKVStore.SecurityLevel.S2, +} +try { + kvManager.getKVStore('storeId', options).then(async (store) => { + console.log('Obtained the KVStore successfully.'); + kvStore = store; + kvManager.closeKVStore('appId', 'storeId').then(() => { + console.log('Closed the KVStore successfully.'); + }).catch((err) => { + console.error(`Fail to close KVStore.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to close KVStore.code is ${e.code},message is ${e.message}`); +} +``` + +### deleteKVStore + +deleteKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): void + +Deletes a distributed KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| appId | string | Yes | Bundle name of the app that invokes the KV store. | +| storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message**| +| ------------ | ------------ | +| 15100004 | Not found. | + +**Example** + +```js +let kvManager; +let kvStore; +const options = { + createIfMissing: true, + encrypt: false, + backup: false, + autoSync: true, + kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, + schema: '', + securityLevel: distributedKVStore.SecurityLevel.S2, +} +try { + kvManager.getKVStore('store', options, async function (err, store) { + if (err != undefined) { + console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the KVStore successfully.'); + kvStore = store; + kvManager.deleteKVStore('appId', 'storeId', function (err, data) { + if (err != undefined) { + console.error(`Fail to delete KVStore.code is ${err.code},message is ${err.message}`); + return; + } + console.log(`Deleted the KVStore successfully.`); + }); + }); +} catch (e) { + console.error(`Fail to delete KVStore.code is ${e.code},message is ${e.message}`); +} +``` + +### deleteKVStore + +deleteKVStore(appId: string, storeId: string): Promise<void> + +Deletes a distributed KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| ------- | -------- | ---- | ------------------------------------------------------------ | +| appId | string | Yes | Bundle name of the app that invokes the KV store. | +| storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message**| +| ------------ | ------------ | +| 15100004 | Not found. | + +**Example** + +```js +let kvManager; +let kvStore; +const options = { + createIfMissing: true, + encrypt: false, + backup: false, + autoSync: true, + kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, + schema: '', + securityLevel: distributedKVStore.SecurityLevel.S2, +} +try { + kvManager.getKVStore('storeId', options).then(async (store) => { + console.log('Obtained the KVStore successfully.'); + kvStore = store; + kvManager.deleteKVStore('appId', 'storeId').then(() => { + console.log('Deleted the KVStore successfully.'); + }).catch((err) => { + console.error(`Fail to delete KVStore.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to delete KVStore.code is ${e.code},message is ${e.message}`); +} +``` + +### getAllKVStoreId + +getAllKVStoreId(appId: string, callback: AsyncCallback<string[]>): void + +Obtains the IDs of all distributed KV stores that are created by [getKVStore](#getkvstore) and have not been deleted by [deleteKVStore](#deletekvstore). This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | --------------------------------------------------- | +| appId | string | Yes | Bundle name of the app that invokes the KV store. | +| callback | AsyncCallback<string[]> | Yes | Callback invoked to return the IDs of the distributed KV stores obtained.| + +**Example** + +```js +let kvManager; +try { + kvManager.getAllKVStoreId('appId', function (err, data) { + if (err != undefined) { + console.error(`Fail to get AllKVStoreId.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained all KV store IDs successfully.'); + console.log(`GetAllKVStoreId size = ${data.length}`); + }); +} catch (e) { + console.error(`Fail to get AllKVStoreId.code is ${e.code},message is ${e.message}`); +} +``` + +### getAllKVStoreId + +getAllKVStoreId(appId: string): Promise<string[]> + +Obtains the IDs of all distributed KV stores that are created by [getKVStore](#getkvstore) and have not been deleted by [deleteKVStore](#deletekvstore). This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ---------------------- | +| appId | string | Yes | Bundle name of the app that invokes the KV store.| + +**Return value** + +| Type | Description | +| ----------------------- | ------------------------------------------------------ | +| Promise<string[]> | Promise used to return the IDs of the distributed KV stores obtained.| + +**Example** + +```js +let kvManager; +try { + console.log('GetAllKVStoreId'); + kvManager.getAllKVStoreId('appId').then((data) => { + console.log('Obtained all KV store IDs successfully.'); + console.log(`GetAllKVStoreId size = ${data.length}`); + }).catch((err) => { + console.error(`Fail to get AllKVStoreId.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to get AllKVStoreId.code is ${e.code},message is ${e.message}`); +} +``` + +### on('distributedDataServiceDie') + +on(event: 'distributedDataServiceDie', deathCallback: Callback<void>): void + +Subscribes to service status changes. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------- | ---- | ------------------------------------------------------------ | +| event | string | Yes | Event to subscribe to. The value is **distributedDataServiceDie**, which indicates a service status change event.| +| deathCallback | Callback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +let kvManager; +try { + console.log('KVManagerOn'); + const deathCallback = function () { + console.log('death callback call'); + } + kvManager.on('distributedDataServiceDie', deathCallback); +} catch (e) { + console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### off('distributedDataServiceDie') + +off(event: 'distributedDataServiceDie', deathCallback?: Callback<void>): void + +Unsubscribes from service status changes. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------- | ---- | ------------------------------------------------------------ | +| event | string | Yes | Event to unsubscribe from. The value is **distributedDataServiceDie**, which indicates a service status change event.| +| deathCallback | Callback<void> | No | Callback for the service status change event. | + +**Example** + +```js +let kvManager; +try { + console.log('KVManagerOff'); + const deathCallback = function () { + console.log('death callback call'); + } + kvManager.off('distributedDataServiceDie', deathCallback); +} catch (e) { + console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +## KVStoreResultSet + +Provides APIs for obtaining the distributed KV store result sets. + +Before calling any API in **KVStoreResultSet**, you must use **[getKVStore](#getkvstore)** to construct a **SingleKVStore** or **DeviceKVStore** instance. + +### getCount + +getCount(): number + +Obtains the total number of rows in the result set. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| number | Total number of rows obtained.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const count = resultSet.getCount(); + console.log("getCount succeed:" + count); +} catch (e) { + console.log("getCount failed: " + e); +} +``` + +### getPosition + +getPosition(): number + +Obtains the current data read position (position from which data is read) in the result set. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| number | Current data read position obtained.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('Obtained the result set successfully.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const position = resultSet.getPosition(); + console.log("getPosition succeed:" + position); +} catch (e) { + console.log("getPosition failed: " + e); +} +``` + +### moveToFirst + +moveToFirst(): boolean + +Moves the data read position to the first row. If the result set is empty, **false** will be returned. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------- | ----------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const moved1 = resultSet.moveToFirst(); + console.log("moveToFirst succeed: " + moved1); +} catch (e) { + console.log("moveToFirst failed " + e); +} +``` + +### moveToLast + +moveToLast(): boolean + +Moves the data read position to the last row. If the result set is empty, **false** will be returned. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------- | ----------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const moved2 = resultSet.moveToLast(); + console.log("moveToLast succeed:" + moved2); +} catch (e) { + console.log("moveToLast failed: " + e); +} +``` + +### moveToNext + +moveToNext(): boolean + +Moves the data read position to the next row. If the result set is empty, **false** will be returned. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------- | ----------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const moved3 = resultSet.moveToNext(); + console.log("moveToNext succeed: " + moved3); +} catch (e) { + console.log("moveToNext failed: " + e); +} +``` + +### moveToPrevious + +moveToPrevious(): boolean + +Moves the data read position to the previous row. If the result set is empty, **false** will be returned. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------- | ----------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const moved4 = resultSet.moveToPrevious(); + console.log("moveToPrevious succeed:" + moved4); +} catch (e) { + console.log("moveToPrevious failed: " + e); +} +``` + +### move + +move(offset: number): boolean + +Moves the data read position with the specified offset from the current position. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| offset | number | Yes | Offset to move the data read position. A negative value means to move backward, and a positive value means to move forward.| + +**Return value** + +| Type | Description | +| ------- | ----------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('Obtained the result set successfully.'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + }); + const moved5 = resultSet.move(1); + console.log(`Succeeded in moving.moved5 = ${moved5}`); +} catch (e) { + console.log(`Fail to move.code is ${e.code},message is ${e.message}`); +} +``` + +### moveToPosition + +moveToPosition(position: number): boolean + +Moves the data read position from 0 to an absolute position. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| -------- | -------- | ---- | -------------- | +| position | number | Yes | Absolute position to move to.| + +**Return value** + +| Type | Description | +| ------- | ----------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('Obtained the result set successfully.'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + }); + const moved6 = resultSet.moveToPosition(1); + console.log(`Succeeded in moving to position.moved6=${moved6}`); +} catch (e) { + console.error(`Fail to move to position.code is ${e.code},message is ${e.message}`); +} +``` + +### isFirst + +isFirst(): boolean + +Checks whether the data read position is the first row. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | Returns **true** if the first row is being read; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const isfirst = resultSet.isFirst(); + console.log("Check isFirst succeed:" + isfirst); +} catch (e) { + console.log("Check isFirst failed: " + e); +} +``` + +### isLast + +isLast(): boolean + +Checks whether the data read position is the last row. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | Returns **true** if the last row is being read; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const islast = resultSet.isLast(); + console.log("Check isLast succeed: " + islast); +} catch (e) { + console.log("Check isLast failed: " + e); +} +``` + +### isBeforeFirst + +isBeforeFirst(): boolean + +Checks whether the data read position is before the first row. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | Returns **true** if the data read position is before the first row; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const isbeforefirst = resultSet.isBeforeFirst(); + console.log("Check isBeforeFirst succeed: " + isbeforefirst); +} catch (e) { + console.log("Check isBeforeFirst failed: " + e); +} +``` + +### isAfterLast + +isAfterLast(): boolean + +Checks whether the data read position is after the last row. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | Returns **true** if the data read position is after the last row; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const isafterlast = resultSet.isAfterLast(); + console.log("Check isAfterLast succeed:" + isafterlast); +} catch (e) { + console.log("Check isAfterLast failed: " + e); +} +``` + +### getEntry + +getEntry(): Entry + +Obtains the KV pair from the current position. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| --------------- | ------------ | +| [Entry](#entry) | KV pair obtained.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const entry = resultSet.getEntry(); + console.log("getEntry succeed:" + JSON.stringify(entry)); +} catch (e) { + console.log("getEntry failed: " + e); +} +``` + +## Query + +Provides methods to create a **Query** object, which defines different data query criteria. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +### constructor + +constructor() + +A constructor used to create a **Schema** instance. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +### reset + +reset(): Query + +Resets the **Query** object. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| -------------- | --------------------- | +| [Query](query) | **Query** object reset.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.equalTo("key", "value"); + console.log("query is " + query.getSqlLike()); + query.reset(); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("simply calls should be ok :" + e); +} +``` + +### equalTo + +equalTo(field: string, value: number|string|boolean): Query + +Creates a **Query** object to match the specified field whose value is equal to the given value. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| fieId | string | Yes |Field to match. It cannot contain '^'. | +| value | number\|string\|boolean | Yes | Value specified.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.equalTo("field", "value"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.ode is ${e.code},message is ${e.message}`); +} +``` + +### notEqualTo + +notEqualTo(field: string, value: number|string|boolean): Query + +Creates a **Query** object to match the specified field whose value is not equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| fieId | string | Yes |Field to match. It cannot contain '^'. | +| value | number\|string\|boolean | Yes | Value specified.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.notEqualTo("field", "value"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### greaterThan + +greaterThan(field: string, value: number|string|boolean): Query + +Creates a **Query** object to match the specified field whose value is greater than the specified value. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| fieId | string | Yes |Field to match. It cannot contain '^'. | +| value | number\|string\|boolean | Yes | Value specified.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.greaterThan("field", "value"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### lessThan + +lessThan(field: string, value: number|string): Query + +Creates a **Query** object to match the specified field whose value is less than the specified value. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| fieId | string | Yes |Field to match. It cannot contain '^'. | +| value | number\|string | Yes | Value specified.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.lessThan("field", "value"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### greaterThanOrEqualTo + +greaterThanOrEqualTo(field: string, value: number|string): Query + +Creates a **Query** object to match the specified field whose value is greater than or equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| fieId | string | Yes |Field to match. It cannot contain '^'. | +| value | number\|string | Yes | Value specified.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.greaterThanOrEqualTo("field", "value"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### lessThanOrEqualTo + +lessThanOrEqualTo(field: string, value: number|string): Query + +Creates a **Query** object to match the specified field whose value is less than or equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| fieId | string | Yes |Field to match. It cannot contain '^'. | +| value | number\|string | Yes | Value specified.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.lessThanOrEqualTo("field", "value"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### isNull + +isNull(field: string): Query + +Creates a **Query** object to match the specified field whose value is **null**. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.isNull("field"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### inNumber + +inNumber(field: string, valueList: number[]): Query + +Creates a **Query** object to match the specified field whose value is within the specified list of numbers. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| +| valueList | number[] | Yes | List of numbers. | + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.inNumber("field", [0, 1]); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### inString + +inString(field: string, valueList: string[]): Query + +Creates a **Query** object to match the specified field whose value is within the specified list of strings. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| +| valueList | string[] | Yes | List of strings. | + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.inString("field", ['test1', 'test2']); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### notInNumber + +notInNumber(field: string, valueList: number[]): Query + +Creates a **Query** object to match the specified field whose value is not within the specified list of numbers. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| +| valueList | number[] | Yes | List of numbers. | + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.notInNumber("field", [0, 1]); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### notInString + +notInString(field: string, valueList: string[]): Query + +Creates a **Query** object to match the specified field whose value is not within the specified list of strings. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| +| valueList | string[] | Yes | List of strings. | + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.notInString("field", ['test1', 'test2']); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### like + +like(field: string, value: string): Query + +Creates a **Query** object to match the specified field whose value is similar to the specified string. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| +| value | string | Yes | String specified. | + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.like("field", "value"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### unlike + +unlike(field: string, value: string): Query + +Creates a **Query** object to match the specified field whose value is not similar to the specified string. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| +| value | string | Yes | String specified. | + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.unlike("field", "value"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### and + +and(): Query + +Creates a **Query** object with the AND condition. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| -------------- | -------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.notEqualTo("field", "value1"); + query.and(); + query.notEqualTo("field", "value2"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("duplicated calls should be ok :" + e); +} +``` + +### or + +or(): Query + +Creates a **Query** object with the OR condition. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| -------------- | -------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.notEqualTo("field", "value1"); + query.or(); + query.notEqualTo("field", "value2"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("duplicated calls should be ok :" + e); +} +``` + +### orderByAsc + +orderByAsc(field: string): Query + +Creates a **Query** object to sort the query results in ascending order. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.notEqualTo("field", "value"); + query.orderByAsc("field"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### orderByDesc + +orderByDesc(field: string): Query + +Creates a **Query** object to sort the query results in descending order. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.notEqualTo("field", "value"); + query.orderByDesc("field"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### limit + +limit(total: number, offset: number): Query + +Creates a **Query** object to specify the number of results and where to start. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------ | +| total | number | Yes | Number of results to query.| +| offset | number | Yes | Start position for query. | + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +let total = 10; +let offset = 1; +try { + let query = new distributedKVStore.Query(); + query.notEqualTo("field", "value"); + query.limit(total, offset); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### isNotNull + +isNotNull(field: string): Query + +Creates a **Query** object to match the specified field whose value is not **null**. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.isNotNull("field"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### beginGroup + +beginGroup(): Query + +Creates a **Query** object for a query condition group with a left parenthesis. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.beginGroup(); + query.isNotNull("field"); + query.endGroup(); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("duplicated calls should be ok :" + e); +} +``` + +### endGroup + +endGroup(): Query + +Creates a **Query** object for a query condition group with a right parenthesis. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.beginGroup(); + query.isNotNull("field"); + query.endGroup(); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("duplicated calls should be ok :" + e); +} +``` + +### prefixKey + +prefixKey(prefix: string): Query + +Creates a **Query** object with a specified key prefix. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------ | +| prefix | string | Yes | Key prefix.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.prefixKey("$.name"); + query.prefixKey("0"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### setSuggestIndex + +setSuggestIndex(index: string): Query + +Creates a **Query** object with an index preferentially used for query. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------ | +| index | string | Yes | Index preferentially used for query.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.setSuggestIndex("$.name"); + query.setSuggestIndex("0"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### deviceId + +deviceId(deviceId:string):Query + +Creates a **Query** object with the device ID as the key prefix. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| -------- | -------- | ---- | ------------------ | +| deviceId | string | Yes | Device ID.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.deviceId("deviceId"); + console.log(`query is ${query.getSqlLike()}`); +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### getSqlLike + +getSqlLike():string + +Obtains the query statement of the **Query** object. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------ | ------------------------------------ | +| string | Returns the query statement obtained.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + let sql1 = query.getSqlLike(); + console.log(`GetSqlLike sql= ${sql1}`); +} catch (e) { + console.log("duplicated calls should be ok : " + e); +} +``` + +## SingleKVStore + +Implements data management in a single KV store, such as adding data, deleting data, and subscribing to data changes or data synchronization completion. + +Before calling any method in **SingleKVStore**, you must use [getKVStore](#getkvstore) to obtain a **SingleKVStore** instance. + +### put + +put(key: string, value: Uint8Array | string | number | boolean, callback: AsyncCallback<void>): void + +Adds a KV pair of the specified type to this KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| key | string | Yes |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | +| value | Uint8Array \| string \| number \| boolean | Yes |Value of the KV pair to add. The value type can be Uint8Array, number, string, or boolean. A value of the Uint8Array or string type cannot exceed [MAX_VALUE_LENGTH](#constants). | +| callback | AsyncCallback<void> | Yes |Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + return; + } + console.log("Put data successfully."); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### put + +put(key: string, value: Uint8Array | string | number | boolean): Promise<void> + +Adds a KV pair of the specified type to this KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| key | string | Yes |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | +| value | Uint8Array \| string \| number \| boolean | Yes |Value of the KV pair to add. The value type can be Uint8Array, number, string, or boolean. A value of the Uint8Array or string type cannot exceed [MAX_VALUE_LENGTH](#constants). | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { + console.log(`Put data successfully. data=${data}`); + }).catch((err) => { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### putBatch + +putBatch(entries: Entry[], callback: AsyncCallback<void>): void + +Batch inserts KV pairs to this single KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------ | +| entries | [Entry](#entry)[] | Yes | KV pairs to insert in batches.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + kvStore.getEntries('batch_test_string_key', function (err, entries) { + if (err != undefined) { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + } + console.log('Obtained the entries successfully.'); + console.log(`entries.length: ${entries.length}`); + console.log(`entries[0]: ${entries[0]}`); + }); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); +} +``` + +### putBatch + +putBatch(entries: Entry[]): Promise<void> + +Batch inserts KV pairs to this single KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ----------------- | ---- | ------------------------ | +| entries | [Entry](#entry)[] | Yes | KV pairs to insert in batches.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries).then(async (entries) => { + console.log('Batch put data successfully.'); + kvStore.getEntries('batch_test_string_key').then((entries) => { + console.log('Obtained the entries successfully.'); + console.log(`PutBatch ${entries}`); + }).catch((err) => { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); +} +``` + +### putBatch + +putBatch(value: Array<ValuesBucket>, callback: AsyncCallback<void>): void + +Writes data to this single KV store. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------ | +| value | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to write.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let v8Arr = []; + let arr = new Uint8Array([4, 5, 6, 7]); + let vb1 = { key: "name_1", value: 32 } + let vb2 = { key: "name_2", value: arr }; + let vb3 = { key: "name_3", value: "lisi" }; + + v8Arr.push(vb1); + v8Arr.push(vb2); + v8Arr.push(vb3); + kvStore.putBatch(v8Arr, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + }) +} catch (e) { + console.error(`Fail to put batch.code is ${e.code},message is ${e.message}`); +} +``` + +### putBatch + +putBatch(value: Array<ValuesBucket>): Promise<void> + +Write data to this KV store. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------ | +| value | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to write. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let v8Arr = []; + let arr = new Uint8Array([4, 5, 6, 7]); + let vb1 = { key: "name_1", value: 32 } + let vb2 = { key: "name_2", value: arr }; + let vb3 = { key: "name_3", value: "lisi" }; + + v8Arr.push(vb1); + v8Arr.push(vb2); + v8Arr.push(vb3); + kvStore.putBatch(v8Arr).then(async (data) => { + console.log(`Batch put data successfully.`); + }).catch((err) => { + console.error(`putBatch fail.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`putBatch fail.code is ${e.code},message is ${e.message}`); +} +``` + +### delete + +delete(key: string, callback: AsyncCallback<void>): void + +Deletes a KV pair from this KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Put data successfully.'); + kvStore.delete(KEY_TEST_STRING_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to delete.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Deleted data successfully.'); + }); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### delete + +delete(key: string): Promise<void> + +Deletes a KV pair from this KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { + console.log(`Put data successfully: ${data}`); + kvStore.delete(KEY_TEST_STRING_ELEMENT).then((data) => { + console.log('Deleted data successfully.'); + }).catch((err) => { + console.error(`Fail to delete.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### delete + +delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<void>) + +Deletes KV pairs from this KV store. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the KV pairs to delete. If this parameter is **null**, define the processing logic.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates'; +let kvStore; +try { + let predicates = new dataSharePredicates.DataSharePredicates(); + kvStore.delete(predicates, function (err, data) { + if (err == undefined) { + console.log('Deleted data successfully.'); + } else { + console.error(`Fail to delete.code is ${err.code},message is ${err.message}`); + } + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### delete + +delete(predicates: dataSharePredicates.DataSharePredicates): Promise<void> + +Deletes KV pairs from this KV store. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the KV pairs to delete. If this parameter is **null**, define the processing logic.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let kvStore; +try { + let predicates = new dataSharePredicates.DataSharePredicates(); + let arr = ["name"]; + predicates.inKeys(arr); + kvStore.put("name", "bob").then((data) => { + console.log(`Put data successfully: ${data}`); + kvStore.delete(predicates).then((data) => { + console.log('Deleted data successfully.'); + }).catch((err) => { + console.error(`Fail to delete.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### deleteBatch + +deleteBatch(keys: string[], callback: AsyncCallback<void>): void + +Batch deletes KV pairs from this single KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------ | +| keys | string[] | Yes | KV pairs to delete in batches.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + let keys = []; + for (var i = 0; i < 5; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + keys.push(key + i); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + kvStore.deleteBatch(keys, async function (err, data) { + if (err != undefined) { + console.error(`Fail to delete Batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch deleted data successfully.'); + }); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### deleteBatch + +deleteBatch(keys: string[]): Promise<void> + +Batch deletes KV pairs from this single KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------ | +| keys | string[] | Yes | KV pairs to delete in batches.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + let keys = []; + for (var i = 0; i < 5; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + keys.push(key + i); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries).then(async (data) => { + console.log('Batch put data successfully.'); + kvStore.deleteBatch(keys).then((err) => { + console.log('Batch deleted data successfully.'); + }).catch((err) => { + console.error(`Fail to delete Batch.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### removeDeviceData + +removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void + +Deletes data of a device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------- | +| deviceId | string | Yes | ID of the target device.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; +const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err, data) { + console.log('Put data successfully.'); + const deviceid = 'no_exist_device_id'; + kvStore.removeDeviceData(deviceid, async function (err, data) { + if (err == undefined) { + console.log('Removed device data successfully.'); + } else { + console.error(`Fail to remove device data.code is ${err.code},message is ${err.message} `); + kvStore.get(KEY_TEST_STRING_ELEMENT, async function (err, data) { + console.log('Obtained data successfully.'); + }); + } + }); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`) +} +``` + +### removeDeviceData + +removeDeviceData(deviceId: string): Promise<void> + +Deletes data of a device. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type| Mandatory| Description | +| -------- | -------- | ---- | ---------------------- | +| deviceId | string | Yes | ID of the target device.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; +const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => { + console.log('Put data successfully.'); + }).catch((err) => { + console.error(`Fail to put data.code is ${err.code},message is ${err.message} `); + }); + const deviceid = 'no_exist_device_id'; + kvStore.removeDeviceData(deviceid).then((err) => { + console.log('Removed device data successfully.'); + }).catch((err) => { + console.error(`Fail to remove device data.code is ${err.code},message is ${err.message} `); + }); + kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { + console.log('Obtained data successfully.'); + }).catch((err) => { + console.error(`Fail to get data.code is ${err.code},message is ${err.message} `); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`) +} +``` + +### get + +get(key: string, callback: AsyncCallback): void + +Obtains the value of the specified key. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| key |string | Yes |Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | +| callback |AsyncCallback<boolean \| string \| number \| Uint8Array> | Yes |Callback invoked to return the value obtained. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100004 | Not found. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + return; + } + console.log("Put data successfully."); + kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to get.code is ${err.code},message is ${err.message}`); + return; + } + console.log(`Obtained data successfully. data=${data}`); + }); + }); +} catch (e) { + console.error(`Fail to get.code is ${e.code},message is ${e.message}`); +} +``` + +### get + +get(key: string): Promise<boolean | string| number | Uint8Array> + +Obtains the value of the specified key. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| ------ | ------- | +|Promise<Uint8Array \| string \| boolean \| number> |Promise used to return the value obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100004 | Not found. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { + console.log(`Put data successfully. data=${data}`); + kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { + console.log(`Obtained data successfully. data=${data}`); + }).catch((err) => { + console.error(`Fail to get.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to get.code is ${e.code},message is ${e.message}`); +} +``` + +### getEntries + +getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void + +Obtains all KV pairs that match the specified key prefix. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | -------------------------------------- | ---- | ---------------------------------------- | +| keyPrefix | string | Yes | Key prefix to match. | +| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + kvStore.getEntries('batch_test_string_key', function (err, entries) { + if (err != undefined) { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the entries successfully.'); + console.log(`entries.length: ${entries.length}`); + console.log(`entries[0]: ${entries[0]}`); + }); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); +} +``` + +### getEntries + +getEntries(keyPrefix: string): Promise<Entry[]> + +Obtains all KV pairs that match the specified key prefix. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | -------------------- | +| keyPrefix | string | Yes | Key prefix to match.| + +**Return value** + +| Type | Description | +| -------------------------------- | ------------------------------------------- | +| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries).then(async (entries) => { + console.log('Batch put data successfully.'); + kvStore.getEntries('batch_test_string_key').then((entries) => { + console.log('Obtained the entries successfully.'); + console.log(`PutBatch ${entries}`); + }).catch((err) => { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); +} +``` + +### getEntries + +getEntries(query: Query, callback: AsyncCallback<Entry[]>): void + +Obtains the KV pairs that match the specified **Query** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ----------------------------------------------- | +| query | [Query](query) | Yes | Key prefix to match. | +| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + var arr = new Uint8Array([21, 31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.BYTE_ARRAY, + value: arr + } + } + entries.push(entry); + } + console.log(`entries: {entries}`); + kvStore.putBatch(entries, async function (err, data) { + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getEntries(query, function (err, entries) { + if (err != undefined) { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the entries successfully.'); + console.log(`entries.length: ${entries.length}`); + console.log(`entries[0]: ${entries[0]}`); + }); + }); +} catch (e) { + console.error(`Fail to get Entries.code is ${e.code},message is ${e.message}`); +} +``` + +### getEntries + +getEntries(query: Query): Promise<Entry[]> + +Obtains the KV pairs that match the specified **Query** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------- | ---- | -------------- | +| query | [Query](query) | Yes | **Query** object to match.| + +**Return value** + +| Type | Description | +| -------------------------------- | -------------------------------------------------- | +| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + var arr = new Uint8Array([21, 31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.BYTE_ARRAY, + value: arr + } + } + entries.push(entry); + } + console.log(`entries: {entries}`); + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getEntries(query).then((entries) => { + console.log('Obtained the entries successfully.'); + }).catch((err) => { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`) + }); + console.log('Obtained the entries successfully.'); +} catch (e) { + console.error(`Fail to get Entries.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(keyPrefix: string, callback: AsyncCallback<KVStoreResultSet>): void + +Obtains a result set with the specified prefix from this single KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ---------------------------------------------------------- | ---- | ------------------------------------ | +| keyPrefix | string | Yes | Key prefix to match. | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the result set obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + kvStore.getResultSet('batch_test_string_key', async function (err, result) { + if (err != undefined) { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set successfully'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err != undefined) { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Closed the result set successfully'); + }) + }); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(keyPrefix: string): Promise<KVStoreResultSet> + +Obtains a result set with the specified prefix from this single KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | -------------------- | +| keyPrefix | string | Yes | Key prefix to match.| + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | --------------------------------------- | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the result set obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('Obtained the result set successfully'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + }); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('Closed the result set successfully'); + }).catch((err) => { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSet + +getResultSet(query: Query, callback: AsyncCallback<KVStoreResultSet>): void + +Obtains a **KVStoreResultSet** object that matches the specified **Query** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------------- | ---- | --------------------------------------------------------- | +| query | Query | Yes | **Query** object to match. | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSet(query, async function (err, result) { + if (err != undefined) { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set successfully'); + }); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(query: Query): Promise<KVStoreResultSet> + +Obtains a **KVStoreResultSet** object that matches the specified **Query** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------- | ---- | -------------- | +| query | [Query](query) | Yes | **Query** object to match.| + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------------------------------------------------------------ | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSet(query).then((result) => { + console.log('Obtained the result set successfully'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSet + +getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KVStoreResultSet>): void + +Obtains a **KVStoreResultSet** object that matches the specified predicate object. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic. | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let kvStore; +try { + let resultSet; + let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.prefixKey("batch_test_string_key"); + kvStore.getResultSet(predicates, async function (err, result) { + if (err != undefined) { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set successfully'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err != undefined) { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Closed the result set successfully'); + }) + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSet + +getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KVStoreResultSet> + +Obtains a **KVStoreResultSet** object that matches the specified predicate object. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic.| + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------------------------- | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let kvStore; +try { + let resultSet; + let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.prefixKey("batch_test_string_key"); + kvStore.getResultSet(predicates).then((result) => { + console.log('Obtained the result set successfully'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + }); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('Closed the result set successfully'); + }).catch((err) => { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### closeResultSet + +closeResultSet(resultSet: KVStoreResultSet, callback: AsyncCallback<void>): void + +Closes the **KVStoreResultSet** object returned by [SingleKvStore.getResultSet](#getresultset-1). This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------- | ---- | ---------------------------------- | +| resultSet | [KVStoreResultSet](#kvstoreresultset) | Yes | **KVStoreResultSet** object to close.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +let kvStore; +try { + let resultSet = null; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err == undefined) { + console.log('Closed the result set successfully'); + } else { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + } + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### closeResultSet + +closeResultSet(resultSet: KVStoreResultSet): Promise<void> + +Closes the **KVStoreResultSet** object returned by [SingleKvStore.getResultSet](#getresultset-1). This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------- | ---- | ---------------------------------- | +| resultSet | [KVStoreResultSet](#kvstoreresultset) | Yes | **KVStoreResultSet** object to close.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let kvStore; +try { + let resultSet = null; + kvStore.closeResultSet(resultSet).then(() => { + console.log('Closed the result set successfully'); + }).catch((err) => { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSize + +getResultSize(query: Query, callback: AsyncCallback<number>): void + +Obtains the number of results that matches the specified **Query** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------- | +| query | [Query](query) | Yes | **Query** object to match. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of results obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries, async function (err, data) { + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSize(query, async function (err, resultSize) { + if (err != undefined) { + console.error(`Fail to get result size.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set size successfully'); + }); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSize + +getResultSize(query: Query): Promise<number> + +Obtains the number of results that matches the specified **Query** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------- | ---- | -------------- | +| query | [Query](query) | Yes | **Query** object to match.| + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------------- | +| Promise<number> | Promise used to return the number of results obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSize(query).then((resultSize) => { + console.log('Obtained the result set size successfully'); + }).catch((err) => { + console.error(`Fail to get result size.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### backup + +backup(file:string, callback: AsyncCallback<void>):void + +Backs up a distributed KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| file | string | Yes | Name of the KV store. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +let file = "BK001"; +try { + kvStore.backup(file, (err, data) => { + if (err) { + console.error(`Fail to backup.code is ${err.code},message is ${err.message} `); + } else { + console.info(`Backed up data successfully. data=${data}`); + } + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### backup + +backup(file:string): Promise<void> + +Backs up an RDB store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| file | string | Yes | Name of the KV store. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +let file = "BK001"; +try { + kvStore.backup(file).then((data) => { + console.info(`Backed up data successfully. data=${data}`); + }).catch((err) => { + console.error(`Fail to backup.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### restore + +restore(file:string, callback: AsyncCallback<void>):void + +Restores a distributed KV store from a database file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| file | string | Yes | Name of the database file. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +let file = "BK001"; +try { + kvStore.restore(file, (err, data) => { + if (err) { + console.error(`Fail to restore.code is ${err.code},message is ${err.message}`); + } else { + console.info(`Restored data successfully. data=${data}`); + } + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### restore + +restore(file:string): Promise<void> + +Restores a distributed KV store from a database file. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| file | string | Yes | Name of the database file. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +let file = "BK001"; +try { + kvStore.restore(file).then((data) => { + console.info(`Restored data successfully. data=${data}`); + }).catch((err) => { + console.error(`Fail to restore.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### deleteBackup + +deleteBackup(files:Array<string>, callback: AsyncCallback<Array<[string, number]>>):void + +Deletes a backup file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | +| files | Array<string> | Yes | Name of the backup file to delete. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| +| callback | AsyncCallback<Array<[string, number]>> | Yes | Callback invoked to return the name of the backup file deleted and the operation result. | + +**Example** + +```js +let kvStore; +let files = ["BK001", "BK002"]; +try { + kvStore.deleteBackup(files, (err, data) => { + if (err) { + console.error(`Fail to delete Backup.code is ${err.code},message is ${err.message}`); + } else { + console.info(`Deleted the backup file successfully. data=${data}`); + } + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### deleteBackup + +deleteBackup(files:Array<string>): Promise<Array<[string, number]>> + +Deletes a backup file. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------- | ---- | ------------------------------------------------------------ | +| files | Array<string> | Yes | Name of the backup file to delete. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| -------------------------------------------- | ----------------------------------------------- | +| Promise<Array<[string, number]>> | Promise used to return the name of the backup file deleted and the operation result.| + +**Example** + +```js +let kvStore; +let files = ["BK001", "BK002"]; +try { + kvStore.deleteBackup(files).then((data) => { + console.info(`Deleted the backup file successfully. data=${data}`); + }).catch((err) => { + console.error(`Fail to delete Backup.code is ${err.code},message is ${err.message}`); + }) +} catch (e) { + console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### startTransaction + +startTransaction(callback: AsyncCallback<void>): void + +Starts the transaction in this single KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +function putBatchString(len, prefix) { + let entries = []; + for (var i = 0; i < len; i++) { + var entry = { + key: prefix + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + return entries; +} + +try { + var count = 0; + kvStore.on('dataChange', 0, function (data) { + console.log(`startTransaction 0 ${data}`); + count++; + }); + kvStore.startTransaction(async function (err, data) { + if (err != undefined) { + console.error(`Fail to start Transaction.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Started the transaction successfully.'); + let entries = putBatchString(10, 'batch_test_string_key'); + console.log(`entries: ${entries}`); + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + }); + }); +} catch (e) { + console.error(`Fail to start Transaction.code is ${e.code},message is ${e.message}`); +} +``` + +### startTransaction + +startTransaction(): Promise<void> + +Starts the transaction in this single KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + var count = 0; + kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { + console.log(`startTransaction 0 ${data}`); + count++; + }); + kvStore.startTransaction().then(async (err) => { + console.log('Started the transaction successfully.'); + }).catch((err) => { + console.error(`Fail to start Transaction.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to start Transaction.code is ${e.code},message is ${e.message}`); +} +``` + +### commit + +commit(callback: AsyncCallback<void>): void + +Commits the transaction in this single KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + kvStore.commit(function (err, data) { + if (err == undefined) { + console.log('Committed the transaction successfully.'); + } else { + console.error(`Fail to commit.code is ${err.code},message is ${err.message}`); + } + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### commit + +commit(): Promise<void> + +Commits the transaction in this single KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + kvStore.commit().then(async (err) => { + console.log('Committed the transaction successfully.'); + }).catch((err) => { + console.error(`Fail to commit.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.ode is ${e.code},message is ${e.message}`); +} +``` + +### rollback + +rollback(callback: AsyncCallback<void>): void + +Rolls back the transaction in this single KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + kvStore.rollback(function (err,data) { + if (err == undefined) { + console.log('Rolled back the transaction successfully'); + } else { + console.error(`Fail to rollback.code is ${err.code},message is ${err.message}`); + } + }); +}catch(e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### rollback + +rollback(): Promise<void> + +Rolls back the transaction in this single KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + kvStore.rollback().then(async (err) => { + console.log('Rolled back the transaction successfully'); + }).catch((err) => { + console.error(`Fail to rollback.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### enableSync + +enableSync(enabled: boolean, callback: AsyncCallback<void>): void + +Sets data synchronization, which can be enabled or disabled. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | --------------------------------------------------------- | +| enabled | boolean | Yes | Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +let kvStore; +try { + kvStore.enableSync(true, function (err, data) { + if (err == undefined) { + console.log('Enabled sync successfully.'); + } else { + console.error(`Fail to enable sync.code is ${err.code},message is ${err.message}`); + } + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### enableSync + +enableSync(enabled: boolean): Promise<void> + +Sets data synchronization, which can be enabled or disabled. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| ------- | -------- | ---- | --------------------------------------------------------- | +| enabled | boolean | Yes | Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let kvStore; +try { + kvStore.enableSync(true).then((err) => { + console.log('Enabled sync successfully.'); + }).catch((err) => { + console.error(`Fail to enable sync.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### setSyncRange + +setSyncRange(localLabels: string[], remoteSupportLabels: string[], callback: AsyncCallback<void>): void + +Sets the data synchronization range. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------------- | ------------------------- | ---- | -------------------------------- | +| localLabels | string[] | Yes | Synchronization labels set for the local device. | +| remoteSupportLabels | string[] | Yes | Synchronization labels set for remote devices.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +let kvStore; +try { + const localLabels = ['A', 'B']; + const remoteSupportLabels = ['C', 'D']; + kvStore.setSyncRange(localLabels, remoteSupportLabels, function (err, data) { + if (err != undefined) { + console.error(`Fail to set syncRange.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Set syncRange successfully.'); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### setSyncRange + +setSyncRange(localLabels: string[], remoteSupportLabels: string[]): Promise<void> + +Sets the data synchronization range. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| ------------------- | -------- | ---- | -------------------------------- | +| localLabels | string[] | Yes | Synchronization labels set for the local device. | +| remoteSupportLabels | string[] | Yes | Synchronization labels set for remote devices.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let kvStore; +try { + const localLabels = ['A', 'B']; + const remoteSupportLabels = ['C', 'D']; + kvStore.setSyncRange(localLabels, remoteSupportLabels).then((err) => { + console.log('Set syncRange successfully.'); + }).catch((err) => { + console.error(`Fail to set syncRange.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### setSyncParam + +setSyncParam(defaultAllowedDelayMs: number, callback: AsyncCallback<void>): void + +Sets the default delay allowed for KV store synchronization. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------------- | ------------------------- | ---- | -------------------------------------------- | +| defaultAllowedDelayMs | number | Yes | Default delay allowed for database synchronization, in ms.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +let kvStore; +try { + const defaultAllowedDelayMs = 500; + kvStore.setSyncParam(defaultAllowedDelayMs, function (err, data) { + if (err != undefined) { + console.error(`Fail to set syncParam.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Set syncParam successfully'); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### setSyncParam + +setSyncParam(defaultAllowedDelayMs: number): Promise<void> + +Sets the default delay allowed for KV store synchronization. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------------------- | -------- | ---- | -------------------------------------------- | +| defaultAllowedDelayMs | number | Yes | Default delay allowed for database synchronization, in ms.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let kvStore; +try { + const defaultAllowedDelayMs = 500; + kvStore.setSyncParam(defaultAllowedDelayMs).then((err) => { + console.log('Set syncParam successfully'); + }).catch((err) => { + console.error(`Fail to set syncParam.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### sync + +sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void + +Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview](../../database/database-mdds-overview.md). + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | --------------------- | ---- | ---------------------------------------------- | +| deviceIds | string[] | Yes | List of IDs of the devices in the same networking environment to be synchronized.| +| mode | [SyncMode](#syncmode) | Yes | Synchronization mode. | +| delayMs | number | No | Allowed synchronization delay time, in ms. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | ------------------- | +| 15100003 | Database corrupted. | +| 15100004 | Not found. | + +**Example** + +```js +let kvStore; +const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; +const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; +try { + kvStore.on('syncComplete', function (data) { + console.log('Sync dataChange'); + }); + kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to sync.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Put data successfully.'); + const devices = ['deviceList']; + const mode = distributedKVStore.SyncMode.PULL_ONLY; + kvStore.sync(devices, mode, 1000); + }); +} catch (e) { + console.error(`Fail to sync.code is ${e.code},message is ${e.message}`); +} +``` + +### sync + +sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void + +Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview](../../database/database-mdds-overview.md). + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | --------------------- | ---- | ---------------------------------------------- | +| deviceIds | string[] | Yes | List of IDs of the devices in the same networking environment to be synchronized.| +| mode | [SyncMode](#syncmode) | Yes | Synchronization mode. | +| query | [Query](query) | Yes | **Query** object to match. | +| delayMs | number | No | Allowed synchronization delay time, in ms. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | ------------------- | +| 15100003 | Database corrupted. | +| 15100004 | Not found. | + +**Example** + +```js +let kvStore; +const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; +const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; +try { + kvStore.on('syncComplete', function (data) { + console.log('Sync dataChange'); + }); + kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to sync.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Put data successfully.'); + const devices = ['deviceList']; + const mode = distributedKVStore.SyncMode.PULL_ONLY; + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + query.deviceId('localDeviceId'); + kvStore.sync(devices, query, mode, 1000); + }); +} catch (e) { + console.error(`Fail to sync.code is ${e.code},message is ${e.message}`); +} +``` + +### on('dataChange') + +on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void + +Subscribes to data changes of the specified type. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | ---------------------------------------------------- | +| event | string | Yes | Event to subscribe to. The value is **dataChange**, which indicates a data change event.| +| type | [SubscribeType](#subscribetype) | Yes | Type of data change. | +| listener | Callback<[ChangeNotification](#changenotification)> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100001 | Over max subscribe limits. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { + console.log(`dataChange callback call data: ${data}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### on('syncComplete') + +on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void + +Subscribes to synchronization complete events. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ | +| event | string | Yes | Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.| +| syncCallback | Callback<Array<[string, number]>> | Yes | Callback used to return the synchronization result. | + +**Example** + +```js +let kvStore; +const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; +const VALUE_TEST_FLOAT_ELEMENT = 321.12; +try { + kvStore.on('syncComplete', function (data) { + console.log(`syncComplete ${data}`); + }); + kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => { + console.log('Put data successfully.'); + }).catch((err) => { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to subscribe syncComplete.code is ${e.code},message is ${e.message}`); +} +``` + +### off('dataChange') + +off(event:'dataChange', listener?: Callback<ChangeNotification>): void + +Unsubscribes from data changes. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | -------------------------------------------------------- | +| event | string | Yes | Event to unsubscribe from. The value is **dataChange**, which indicates a data change event.| +| listener | Callback<[ChangeNotification](#changenotification)> | No | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +class KvstoreModel { + call(data) { + console.log(`dataChange : ${data}`); + } + + subscribeDataChange() { + try { + if (kvStore != null) { + kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); + } + } catch (err) { + console.error(`Fail to subscribeDataChange.code is ${err.code},message is ${err.message}`); + } + } + + unsubscribeDataChange() { + try { + if (kvStore != null) { + kvStore.off('dataChange', this.call); + } + } catch (err) { + console.error(`Fail to unsubscribeDataChange.code is ${err.code},message is ${err.message}`); + } + } +} +``` + +### off('syncComplete') + +off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void + +Unsubscribes from synchronization complete events. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- | +| event | string | Yes | Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event.| +| syncCallback | Callback<Array<[string, number]>> | No | Callback used to return the synchronization result. | + +**Example** + +```js +let kvStore; +class KvstoreModel { + call(data) { + console.log(`syncComplete : ${data}`); + } + + subscribeDataChange() { + try { + if (kvStore != null) { + kvStore.on('syncComplete', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); + } + } catch (err) { + console.error(`Fail to subscribeDataChange.code is ${err.code},message is ${err.message}`); + } + } + + unsubscribeDataChange() { + try { + if (kvStore != null) { + kvStore.off('dsyncComplete', this.call); + } + } catch (err) { + console.error(`Fail to unsubscribeDataChange.code is ${err.code},message is ${err.message}`); + } + } +} +``` + +### getSecurityLevel + +getSecurityLevel(callback: AsyncCallback<SecurityLevel>): void + +Obtains the security level of this KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | -------------------------------- | +| callback | AsyncCallback<[SecurityLevel](#securitylevel)> | Yes | Callback invoked to return the security level obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + kvStore.getSecurityLevel(function (err, data) { + if (err != undefined) { + console.error(`Fail to get SecurityLevel.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained securityLevel successfully'); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### getSecurityLevel + +getSecurityLevel(): Promise<SecurityLevel> + +Obtains the security level of this KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ---------------------------------------------- | ----------------------------------- | +| Promise<[SecurityLevel](#securitylevel)> | Promise used to return the security level obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + kvStore.getSecurityLevel().then((data) => { + console.log('Obtained securityLevel successfully'); + }).catch((err) => { + console.error(`Fail to get SecurityLevel.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +## DeviceKVStore + +Provides APIs for querying and synchronizing data in a device KV store. This class inherits from **SingleKVStore**. + +Data is distinguished by device in a device KV store. Each device can only write and modify its own data. Data of other devices is read-only and cannot be modified. + +For example, a device KV store can be used to implement image sharing between devices. The images of other devices can be viewed, but not be modified or deleted. + +Before calling any method in **DeviceKVStore**, you must use [getKVStore](#getkvstore) to obtain a **DeviceKVStore** object. + +### get + +get(key: string, callback: AsyncCallback): void + +Obtains the value of the specified key for this device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).| +| callback | AsyncCallback<boolean \| string \| number \| Uint8Array> | Yes | Callback invoked to return the value obtained. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100004 | Not found. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + return; + } + console.log("Put data successfully."); + kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to get.code is ${err.code},message is ${err.message}`); + return; + } + console.log(`Obtained data successfully. data=${data}`); + }); + }); +} catch (e) { + console.error(`Fail to get.code is ${e.code},message is ${e.message}`); +} +``` + +### get + +get(key: string): Promise<boolean | string| number | Uint8Array> + +Obtains the value of the specified key for this device. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| -------------------------------------------------------- | ------------------------------- | +| Promise<Uint8Array \| string \| boolean \| number> | Promise used to return the value obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100004 | Not found. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { + console.log(`Put data successfully. data=${data}`); + kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { + console.log(`Obtained data successfully. data=${data}`); + }).catch((err) => { + console.error(`Fail to get.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to get.code is ${e.code},message is ${e.message}`); +} +``` + +### get + +get(deviceId: string, key: string, callback: AsyncCallback<boolean|string|number|Uint8Array>): void + +Obtains a string value that matches the specified device ID and key. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| deviceId |string | Yes |ID of the target device. | +| key |string | Yes |Key to match. | +| callback |AsyncCallback<boolean\|string\|number\|Uint8Array> | Yes |Callback invoked to return the value obtained. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100004 | Not found. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; +const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Put data successfully.'); + kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to get.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained data successfully'); + }); + }) +} catch (e) { + console.error(`Fail to get.code is ${e.code},message is ${e.message}`); +} +``` + +### get + +get(deviceId: string, key: string): Promise<boolean|string|number|Uint8Array> + +Obtains a string value that matches the specified device ID and key. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type| Mandatory| Description | +| -------- | -------- | ---- | ------------------------ | +| deviceId | string | Yes | ID of the target device.| +| key | string | Yes | Key to match. | + +**Return value** + +| Type | Description | +| ------ | ------- | +|Promise<boolean\|string\|number\|Uint8Array> |Promise used to return the string value obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100004 | Not found. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; +const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(async (data) => { + console.log('Put data successfully.'); + kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { + console.log('Obtained data successfully'); + }).catch((err) => { + console.error(`Fail to get.code is ${err.code},message is ${err.message}`); + }); + }).catch((error) => { + console.error(`Fail to put.code is ${error.code},message is ${error.message}`); + }); +} catch (e) { + console.error(`Fail to get.code is ${e.code},message is ${e.message}`); +} +``` + +### getEntries + +getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void + +Obtains all KV pairs that match the specified key prefix for this device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | -------------------------------------- | ---- | ---------------------------------------- | +| keyPrefix | string | Yes | Key prefix to match. | +| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + kvStore.getEntries('batch_test_string_key', function (err, entries) { + if (err != undefined) { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the entries successfully.'); + console.log(`entries.length: ${entries.length}`); + console.log(`entries[0]: ${entries[0]}`); + }); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); +} +``` + +### getEntries + +getEntries(keyPrefix: string): Promise<Entry[]> + +Obtains all KV pairs that match the specified key prefix for this device. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | -------------------- | +| keyPrefix | string | Yes | Key prefix to match.| + +**Return value** + +| Type | Description | +| -------------------------------- | ------------------------------------------- | +| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries).then(async (entries) => { + console.log('Batch put data successfully.'); + kvStore.getEntries('batch_test_string_key').then((entries) => { + console.log('Obtained the entries successfully.'); + console.log(`PutBatch ${entries}`); + }).catch((err) => { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); +} +``` + +### getEntries + +getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry[]>): void + +Obtains all KV pairs that match the specified device ID and key prefix. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | -------------------------------------- | ---- | ---------------------------------------------- | +| deviceId | string | Yes | ID of the target device. | +| keyPrefix | string | Yes | Key prefix to match. | +| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + console.log(`entries : ${entries}`); + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err, entries) { + if (err != undefined) { + console.error(`Fail to get entries.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the entries successfully.'); + console.log(`entries.length: ${entries.length}`); + console.log(`entries[0]: ${entries[0]}`); + }); + }); +} catch (e) { + console.error(`Fail to put batch.code is ${e.code},message is ${e.message}`); +} +``` + +### getEntries + +getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]> + +Obtains all KV pairs that match the specified device ID and key prefix. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | ------------------------ | +| deviceId | string | Yes | ID of the target device.| +| keyPrefix | string | Yes | Key prefix to match. | + +**Return value** + +| Type | Description | +| -------------------------------- | ------------------------------------------------- | +| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entries) => { + console.log('Obtained the entries successfully.'); + console.log(`entries.length: ${entries.length}`); + console.log(`entries[0]: ${entries[0]}`); + console.log(`entries[0].value: ${entries[0].value}`); + console.log(`entries[0].value.value: ${entries[0].value.value}`); + }).catch((err) => { + console.error(`Fail to get entries.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to put batch.code is ${e.code},message is ${e.message}`); +} +``` + +### getEntries + +getEntries(query: Query, callback: AsyncCallback<Entry[]>): void + +Obtains all KV pairs that match the specified **Query** object for this device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ----------------------------------------------------- | +| query | [Query](query) | Yes | Key prefix to match. | +| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback used to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + var arr = new Uint8Array([21, 31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.BYTE_ARRAY, + value: arr + } + } + entries.push(entry); + } + console.log(`entries: {entries}`); + kvStore.putBatch(entries, async function (err, data) { + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getEntries(query, function (err, entries) { + if (err != undefined) { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the entries successfully.'); + console.log(`entries.length: ${entries.length}`); + console.log(`entries[0]: ${entries[0]}`); + }); + }); +} catch (e) { + console.error(`Fail to get Entries.code is ${e.code},message is ${e.message}`); +} +``` + +### getEntries + +getEntries(query: Query): Promise<Entry[]> + +Obtains all KV pairs that match the specified **Query** object for this device. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------- | ---- | -------------- | +| query | [Query](query) | Yes | **Query** object to match.| + +**Return value** + +| Type | Description | +| -------------------------------- | -------------------------------------------------------- | +| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + var arr = new Uint8Array([21, 31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.BYTE_ARRAY, + value: arr + } + } + entries.push(entry); + } + console.log(`entries: {entries}`); + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getEntries(query).then((entries) => { + console.log('Obtained the entries successfully.'); + }).catch((err) => { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`) + }); + console.log('Obtained the entries successfully.'); +} catch (e) { + console.error(`Fail to get Entries.code is ${e.code},message is ${e.message}`); +} +``` + +### getEntries + +getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]>): void + +Obtains the KV pairs that match the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------------------------- | +| deviceId | string | Yes | ID of the target device. | +| query | [Query](query) | Yes | **Query** object to match. | +| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + var arr = new Uint8Array([21, 31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.BYTE_ARRAY, + value: arr + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + var query = new distributedKVStore.Query(); + query.deviceId('localDeviceId'); + query.prefixKey("batch_test"); + kvStore.getEntries('localDeviceId', query, function (err, entries) { + if (err != undefined) { + console.error(`Fail to get entries.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the entries successfully.'); + console.log(`entries.length: ${entries.length}`); + console.log(`entries[0]: ${entries[0]}`); + }) + }); + console.log('Obtained the entries successfully.'); +} catch (e) { + console.error(`Fail to get entries.code is ${e.code},message is ${e.message}`); +} +``` + +### getEntries + +getEntries(deviceId: string, query: Query): Promise<Entry[]> + +Obtains the KV pairs that match the specified device ID and **Query** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | -------------------- | +| deviceId | string | Yes | ID of the target device.| +| query | [Query](query) | Yes | **Query** object to match. | + +**Return value** + +| Type | Description | +| -------------------------------- | ---------------------------------------------------------- | +| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + var arr = new Uint8Array([21, 31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.BYTE_ARRAY, + value: arr + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + var query = new distributedKVStore.Query(); + query.deviceId('localDeviceId'); + query.prefixKey("batch_test"); + kvStore.getEntries('localDeviceId', query).then((entries) => { + console.log('Obtained the entries successfully.'); + }).catch((err) => { + console.error(`Fail to get entries.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + console.log('Obtained the entries successfully.'); +} catch (e) { + console.error(`Fail to get entries.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(keyPrefix: string, callback: AsyncCallback<KVStoreResultSet>): void + +Obtains a result set with the specified prefix for this device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ---------------------------------------------------------- | ---- | ------------------------------------ | +| keyPrefix | string | Yes | Key prefix to match. | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the result set obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + kvStore.getResultSet('batch_test_string_key', async function (err, result) { + if (err != undefined) { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set successfully'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err != undefined) { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Closed the result set successfully'); + }) + }); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(keyPrefix: string): Promise<KVStoreResultSet> + +Obtains a result set with the specified prefix for this device. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | -------------------- | +| keyPrefix | string | Yes | Key prefix to match.| + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | --------------------------------------- | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the result set obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('Obtained the result set successfully'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + }); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('Closed the result set successfully'); + }).catch((err) => { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSet + +getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KVStoreResultSet>): void + +Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| deviceId | string | Yes | ID of the target device. | +| keyPrefix | string | Yes | Key prefix to match. | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async function (err, result) { + if (err != undefined) { + console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set successfully.'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err != undefined) { + console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Closed the result set successfully.'); + }) + }); +} catch (e) { + console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(deviceId: string, keyPrefix: string): Promise<KVStoreResultSet> + +Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | ------------------------ | +| deviceId | string | Yes | ID of the target device.| +| keyPrefix | string | Yes | Key prefix to match. | + +**Return value** + +| Type | Description | +| ------------------------------------------------------ | ------------------------------------------------------------ | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('localDeviceId', 'batch_test_string_key').then((result) => { + console.log('Obtained the result set successfully.'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + }); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('Closed the result set successfully.'); + }).catch((err) => { + console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KVStoreResultSet>): void + +Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs. | +| query | [Query](query) | Yes | **Query** object to match. | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSet('localDeviceId', query, async function (err, result) { + if (err != undefined) { + console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set successfully.'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err != undefined) { + console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Closed the result set successfully.'); + }) + }); + }); +} catch (e) { + console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(deviceId: string, query: Query): Promise<KVStoreResultSet> + +Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | ---------------------------------- | +| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs.| +| query | [Query](query) | Yes | **Query** object to match. | + +**Return value** + +| Type | Description | +| ------------------------------------------------------ | ------------------------------------------------------------ | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSet('localDeviceId', query).then((result) => { + console.log('Obtained the result set successfully.'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + }); + query.deviceId('localDeviceId'); + console.log("GetResultSet " + query.getSqlLike()); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('Closed the result set successfully.'); + }).catch((err) => { + console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); + }); + +} catch (e) { + console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(query: Query): Promise<KVStoreResultSet> + +Obtains a **KVStoreResultSet** object that matches the specified **Query** object for this device. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------- | ---- | -------------- | +| query | [Query](query) | Yes | **Query** object to match.| + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------------------------------------------------------------ | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return Obtains a **KVStoreResultSet** object that matches the specified **Query** object for this device.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSet(query).then((result) => { + console.log('Obtained the result set successfully'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSet + +getResultSet(deviceId: string, query: Query): Promise<KVStoreResultSet> + +Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | ---------------------------------- | +| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs.| +| query | [Query](query) | Yes | **Query** object to match. | + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------------------------------------------------------------ | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSet('localDeviceId', query).then((result) => { + console.log('Obtained the result set successfully.'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + }); + query.deviceId('localDeviceId'); + console.log("GetResultSet " + query.getSqlLike()); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('Closed the result set successfully.'); + }).catch((err) => { + console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); + }); + +} catch (e) { + console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KVStoreResultSet>): void + +Obtains a **KVStoreResultSet** object that matches the specified predicate object for this device. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic. | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let kvStore; +try { + let resultSet; + let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.prefixKey("batch_test_string_key"); + kvStore.getResultSet(predicates, async function (err, result) { + if (err != undefined) { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set successfully'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err != undefined) { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Closed the result set successfully'); + }) + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSet + +getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KVStoreResultSet> + +Obtains a **KVStoreResultSet** object that matches the specified predicate object for this device. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic.| + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------------------------- | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let kvStore; +try { + let resultSet; + let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.prefixKey("batch_test_string_key"); + kvStore.getResultSet(predicates).then((result) => { + console.log('Obtained the result set successfully'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + }); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('Closed the result set successfully'); + }).catch((err) => { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSet + +getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KVStoreResultSet>): void + +Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| deviceId | string | Yes | ID of the target device. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic. | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let kvStore; +try { + let resultSet; + let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.prefixKey("batch_test_string_key"); + kvStore.getResultSet('localDeviceId', predicates, async function (err, result) { + if (err != undefined) { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set successfully'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err != undefined) { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Closed the result set successfully'); + }) + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSet + +getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicates): Promise<KVStoreResultSet> + +Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | +| deviceId | string | Yes | ID of the target device. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic.| + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------------------------- | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates'; +let kvStore; +try { + let resultSet; + let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.prefixKey("batch_test_string_key"); + kvStore.getResultSet('localDeviceId', predicates).then((result) => { + console.log('Obtained the result set successfully'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + }); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('Closed the result set successfully'); + }).catch((err) => { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSize + +getResultSize(query: Query, callback: AsyncCallback<number>): void + +Obtains the number of results that match the specified **Query** object for this device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------- | +| query | [Query](query) | Yes | **Query** object to match. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of results that match the specified **Query** object.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries, async function (err, data) { + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSize(query, async function (err, resultSize) { + if (err != undefined) { + console.error(`Fail to get result size.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set size successfully'); + }); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSize + +getResultSize(query: Query): Promise<number> + +Obtains the number of results that match the specified **Query** object for this device. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------- | ---- | -------------- | +| query | [Query](query) | Yes | **Query** object to match.| + +**Return value** + +| Type | Description | +| --------------------- | ---------------------------------------------------- | +| Promise<number> | Promise used to return the number of results that match the specified **Query** object.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSize(query).then((resultSize) => { + console.log('Obtained the result set size successfully'); + }).catch((err) => { + console.error(`Fail to get result size.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSize + +getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number>): void; + +Obtains the number of results that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | --------------------------------------------------- | +| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs. | +| query | [Query](query) | Yes | **Query** object to match. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of results obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) { + if (err != undefined) { + console.error(`Fail to get resultSize.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained resultSize successfully'); + ; + }); + }); +} catch (e) { + console.error(`Fail to get resultSize.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSize + +getResultSize(deviceId: string, query: Query): Promise<number> + +Obtains the number of results that matches the specified device ID and **Query** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | ---------------------------------- | +| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs.| +| query | [Query](query) | Yes | **Query** object to match. | + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------------------------------ | +| Promise<number> | Promise used to return the number of results obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + var query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSize('localDeviceId', query).then((resultSize) => { + console.log('Obtained resultSize successfully'); + ; + }).catch((err) => { + console.error(`Fail to get resultSize.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to get resultSize.code is ${e.code},message is ${e.message}`); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-nfcController.md b/en/application-dev/reference/apis/js-apis-nfcController.md index 105af3cf95ca3a052faddbb6fe632940169fbcd1..bebe6f1fd48fcfa2798924c35d7ad17807a66381 100644 --- a/en/application-dev/reference/apis/js-apis-nfcController.md +++ b/en/application-dev/reference/apis/js-apis-nfcController.md @@ -1,14 +1,13 @@ -# Standard NFC +# @ohos.nfc.controller (Standard NFC) The **nfcController** module provides APIs for opening and closing Near-Field Communication (NFC) and reading the NFC state. > **NOTE**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. - ## **Modules to Import** -``` +```js import controller from '@ohos.nfc.controller'; ``` @@ -18,7 +17,7 @@ Enumerates the NFC states. **System capability**: SystemCapability.Communication.NFC.Core -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | STATE_OFF | 1 | NFC is closed (OFF).| | STATE_TURNING_ON | 2 | NFC is turning on.| @@ -110,12 +109,10 @@ Subscribes to NFC state changes. A callback will be invoked to return the NFC st **Parameter** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to subscribe to. The value is **nfcStateChange**.| - | callback | Callback<[NfcState](#nfcstate)> | Yes| Callback invoked to return the NFC state.| - - +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to subscribe to. The value is **nfcStateChange**.| +| callback | Callback<[NfcState](#nfcstate)> | Yes| Callback invoked to return the NFC state.| ## controller.off('nfcStateChange') @@ -126,41 +123,38 @@ Unsubscribes from the NFC state changes. The subscriber will not receive NFC sta **System capability**: SystemCapability.Communication.NFC.Core **Parameter** - - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to unsubscribe from. The value is **nfcStateChange**.| + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to unsubscribe from. The value is **nfcStateChange**.| | callback | Callback<[NfcState](#nfcstate)> | No| Callback for the NFC state changes. This parameter can be left blank.| **Example** - ```js - import controller from '@ohos.nfc.controller'; - - // Define a callback key. - var NFC_STATE_CALLBACK_KEY = "nfcStateChange"; - - // Register the callback to receive NFC state change notifications. - controller.on(NFC_STATE_CALLBACK_KEY, (err, nfcState)=> { - if (err) { - console.log("controller on callback err: " + err); - } else { - console.log("controller on callback nfcState: " + nfcState); - } - }); - - // Open NFC. Require permission: ohos.permission.MANAGE_SECURE_SETTINGS. - if (!controller.isNfcOpen()) { - var ret = controller.openNfc(); - console.log("controller openNfc ret: " + ret); - } +```js +import controller from '@ohos.nfc.controller'; - // Close NFC. Require permission: ohos.permission.MANAGE_SECURE_SETTINGS. - if (controller.isNfcOpen()) { - var ret = controller.closeNfc(); - console.log("controller closeNfc ret: " + ret); +// Register the callback to receive NFC state change notifications. +controller.on("nfcStateChange", (err, nfcState)=> { + if (err) { + console.log("controller on callback err: " + err); + } else { + console.log("controller on callback nfcState: " + nfcState); } - - // Unregister the callback. - controller.off(NFC_STATE_CALLBACK_KEY); - ``` +}); + +// Open NFC. Require permission: ohos.permission.MANAGE_SECURE_SETTINGS. +if (!controller.isNfcOpen()) { + var ret = controller.openNfc(); + console.log("controller openNfc ret: " + ret); +} + +// Close NFC. Require permission: ohos.permission.MANAGE_SECURE_SETTINGS. +if (controller.isNfcOpen()) { + var ret = controller.closeNfc(); + console.log("controller closeNfc ret: " + ret); +} + +// Unregister the callback. +controller.off("nfcStateChange"); +``` diff --git a/en/application-dev/reference/apis/js-apis-nfcTag.md b/en/application-dev/reference/apis/js-apis-nfcTag.md index 2f3a208fe1f95b2c4f936709d047fa4c9581f8b6..91ef73c07db34721d0cc0f964bb992ce37669ae3 100644 --- a/en/application-dev/reference/apis/js-apis-nfcTag.md +++ b/en/application-dev/reference/apis/js-apis-nfcTag.md @@ -1,8 +1,9 @@ -# NFC Tags +# @ohos.nfc.tag The **nfcTag** module provides APIs for managing Near-Field Communication (NFC) tags. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## **Declaration** @@ -47,12 +48,10 @@ Before developing applications related to tag read and write, you must declare N } ``` > **CAUTION**
-> -> - The **actions** field is mandatory. It must be **ohos.nfc.tag.action.TAG_FOUND** and cannot be changed. -> - The **name** field of **metadata** is mandatory. It must be **tag-tech** and cannot be changed. -> - The **value** field of **metadata** is mandatory. It can be **NfcA**, **NfcB**, **NfcF**, **NfcV**, **IsoDep**, **Ndef**, **MifareClassic**, **MifareUL**, **NdefFormatable** or their combinations. Incorrect setting of this field will cause a parsing failure. -> - The **name** field of **requestPermissions** is mandatory. It must be **ohos.permission.NFC_TAG** and cannot be changed. - +1. The **actions** field is mandatory. It must be **ohos.nfc.tag.action.TAG_FOUND** and cannot be changed. +2. The **name** field under **metadata** is mandatory. It must be **tag-tech** and cannot be changed. +3. The **value** field under **metadata** is mandatory. It can be **NfcA**, **NfcB**, **NfcF**, **NfcV**, **IsoDep**, **Ndef**, **MifareClassic**, **MifareUL**, **NdefFormatable** or any of their combinations. Incorrect settings of this field will cause a parsing failure. +4. The **name** field under **requestPermissions** is mandatory. It must be **ohos.permission.NFC_TAG** and cannot be changed. ## **Modules to Import** @@ -61,34 +60,63 @@ import tag from '@ohos.nfc.tag'; ``` ## **tag.TagInfo** -Before reading or writing data to a card with tags, the application must obtain **TagInfo** to determine the tag technologies supported by the card. Then, the application can invoke the correct API to communicate with the card. + +Before a card with tags is read or written, **TagInfo** must be obtained to determine the tag technologies supported by the card. In this way, the application can invoke the correct API to communicate with the card. ```js import tag from '@ohos.nfc.tag'; onCreate(want, launchParam) { // Add other code here. - // want is initialized by the NFC service and contains taginfo. - var tagInfo = tag.getTagInfo(want); - if (tagInfo == undefined) { + // want is initialized by the NFC service and contains tagInfo. + var tagInfo; + try { + tagInfo = tag.getTagInfo(want); + } catch (error) { + console.log("tag.getTagInfo catched error: " + error); + } + if (tagInfo == null || tagInfo == undefined) { console.log("no TagInfo to be created, ignore it."); return; } + + // get the supported technologies for this found tag. var isNfcATag = false; + var isIsoDepTag = false; for (var i = 0; i < tagInfo.technology.length; i++) { if (tagInfo.technology[i] == tag.NFC_A) { isNfcATag = true; - break; + } + + if (tagInfo.technology[i] == tag.ISO_DEP) { + isIsoDepTag = true; } // Also check for technology tag.NFC_B, NFC_F, NFC_V, ISO_DEP, NDEF, MIFARE_CLASSIC, MIFARE_ULTRALIGHT, and NDEF_FORMATABLE. } + + // use NfcA APIs to access the found tag. if (isNfcATag) { - var nfcA = tag.getNfcATag(taginfo); + var nfcA; + try { + nfcA = tag.getNfcATag(taginfo); + } catch (error) { + console.log("tag.getNfcATag catched error: " + error); + } + // Other code to read or write this tag. + } + + // use getIsoDep APIs to access the found tag. + if (isIsoDepTag) { + var isoDep; + try { + isoDep = tag.getIsoDep(taginfo); + } catch (error) { + console.log("tag.getIsoDep catched error: " + error); + } // Other code to read or write this tag. } - // use the same code to handle "NfcA/NfcB/NfcF/NfcV/IsoDep/Ndef/MifareClassic/MifareUL/NdefFormatable", such as, - // var isoDep = tag.getIsoDepTag(taginfo); + // Use the same code to handle "NfcA/NfcB/NfcF/NfcV/Ndef/MifareClassic/MifareUL/NdefFormatable". } ``` @@ -156,78 +184,122 @@ Obtains an **NfcVTag** object, which allows access to the tags that use the NFC- | -------- | ---------------- | | [NfcVTag](js-apis-nfctech.md#nfcvtag) | **NfcVTag** object obtained.| -## tag.getIsoDepTag9+ +## tag.getIsoDep9+ -getIsoDepTag(tagInfo: [TagInfo](#taginfo)): [IsoDepTag](js-apis-nfctech.md#isoDepTag9 ) +getIsoDep(tagInfo: [TagInfo](#taginfo)): [IsoDepTag](js-apis-nfctech.md#isoDepTag9 ) Obtains an **IsoDepTag** object, which allows access to the tags that use the ISO-DEP technology. -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Core +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. | + **Return value** | **Type**| **Description** | | ---------- | ------------------| | [IsoDepTag](js-apis-nfctech.md#isodeptag9) | **IsoDepTag** object obtained.| -## tag.getNdefTag9+ +**Error codes** -getNdefTag(tagInfo: [TagInfo](#taginfo)): [NdefTag](js-apis-nfctech.md#ndeftag9) +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -Obtains an **NdefTag** object, which allows access to the tags in the NFC Data Exchange Format (NDEF). +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +## tag.getNdef9+ -**Required permissions**: ohos.permission.NFC_TAG +getNdef(tagInfo: [TagInfo](#taginfo)): [NdefTag](js-apis-nfctech.md#ndeftag9) + +Obtains an **NdefTag** object, which allows access to the tags in the NFC Data Exchange Format (NDEF). **System capability**: SystemCapability.Communication.NFC.Core +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. | + **Return value** | **Type**| **Description** | | ---------| -------------- | | [NdefTag](js-apis-nfctech.md#ndeftag9) | **NdefTag** object obtained.| -## tag.getMifareClassicTag9+ +**Error codes** -getMifareClassicTag(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -Obtains a **MifareClassicTag** object, which allows access to the tags that use MIFARE Classic. +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | -**Required permissions**: ohos.permission.NFC_TAG +## tag.getMifareClassic9+ + +getMifareClassic(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) + +Obtains a **MifareClassicTag** object, which allows access to the tags that use MIFARE Classic. **System capability**: SystemCapability.Communication.NFC.Core +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. | + **Return value** | **Type**| **Description** | | ----------------- | ------------------------| | [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) | **MifareClassicTag** object obtained.| -## tag.getMifareUltralightTag9+ +**Error codes** -getMifareUltralightTag(tagInfo: [TagInfo](#taginfo)): [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -Obtains a **MifareUltralightTag** object, which allows access to the tags that use MIFARE Ultralight. +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | -**Required permissions**: ohos.permission.NFC_TAG +## tag.getMifareUltralight9+ + +getMifareUltralight(tagInfo: [TagInfo](#taginfo)): [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) + +Obtains a **MifareUltralightTag** object, which allows access to the tags that use MIFARE Ultralight. **System capability**: SystemCapability.Communication.NFC.Core +**Parameters** +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. | + **Return value** | **Type**| **Description** | | -------------------- | ---------------------------| | [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) | **MifareUltralightTag** object obtained.| -## tag.getNdefFormatableTag9+ +**Error codes** -getNdefFormatableTag(tagInfo: [TagInfo](#taginfo)): [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag9) +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -Obtains an **NdefFormatableTag** object, which allows access to the tags that are NDEF formattable. +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | -**Required permissions**: ohos.permission.NFC_TAG +## tag.getNdefFormatable9+ + +getNdefFormatable(tagInfo: [TagInfo](#taginfo)): [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag9) + +Obtains an **NdefFormatableTag** object, which allows access to the tags that are NDEF formattable. **System capability**: SystemCapability.Communication.NFC.Core @@ -237,89 +309,376 @@ Obtains an **NdefFormatableTag** object, which allows access to the tags that ar | ------------------ | --------------------------| | [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag) | **NdefFormatableTag** object obtained.| +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + ## tag.getTagInfo9+ -getTagInfo(want: Want): [TagInfo](#taginfo) +getTagInfo(want: [Want](js-apis-app-ability-want.md#Want)): [TagInfo](#taginfo) Obtains **TagInfo** from **Want**, which is initialized by the NFC service and contains the attributes required by **TagInfo**. -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Core +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| want | [Want](js-apis-app-ability-want.md#Want) | Yes | Data obtained from the parameters of the **onCreate** entry function when an ability is dispatched. | + **Return value** | **Type**| **Description** | | ------------------ | --------------------------| | [TagInfo](#taginfo) | **TagInfo** object obtained.| -## TagInfo -Defines the **TagInfo** object, which provides information about the tag technologies supported by a card. +## tag.ndef.makeUriRecord9+ -**Required permissions**: ohos.permission.NFC_TAG +makeUriRecord(uri: string): [NdefRecord](#ndefrecord9); + +Creates an NDEF record based on the specified URI. **System capability**: SystemCapability.Communication.NFC.Core -| **Name**| **Type**| **Description**| -| -------- | -------- | -------- | -| uid9+ | number[] | Tag unique identifier (UID). Each number of the UID is a hexadecimal number ranging from **0x00** to **0xFF**.| -| technology9+ | number[] | Supported technologies. Each number is a constant indicating the supported technology.| -| supportedProfiles | number[] | Supported technologies. This parameter is not supported since API version 9 and is replaced by **technology**.| +**Parameters** -## NdefRecord9+ -Defines an NDEF tag record. For details, see *NFCForum-TS-NDEF_1.0*. +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| uri | string | Yes| Data to write to the NDEF record.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +try { + let uri = "https://gitee.com/openharmony"; // change it to be correct. + let ndefRecord = tag.ndef.makeUriRecord(uri); + if (ndefRecord != undefined) { + console.log("ndefMessage makeUriRecord rtdType: " + ndefRecord.rtdType); + console.log("ndefMessage makeUriRecord payload: " + ndefRecord.payload); + } else { + console.log("ndefMessage makeUriRecord ndefRecord: " + ndefRecord); + } +} catch (busiError) { + console.log("ndefMessage makeUriRecord catched busiError: " + busiError); +} +``` + +## tag.ndef.makeTextRecord9+ + +makeTextRecord(text: string, locale: string): [NdefRecord](#ndefrecord9); + +Creates an NDEF record based on the specified text data and encoding type. + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| text | string | Yes | Text to write to the NDEF record.| +| locale | string | Yes | Encoding mode of the text.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +try { + let text = "Hello World"; // change it to be correct. + let locale = "en"; // change it to be correct. + let ndefRecord = tag.ndef.makeTextRecord(text, locale); + if (ndefRecord != undefined) { + console.log("ndefMessage makeTextRecord rtdType: " + ndefRecord.rtdType); + console.log("ndefMessage makeTextRecord payload: " + ndefRecord.payload); + } else { + console.log("ndefMessage makeTextRecord ndefRecord: " + ndefRecord); + } +} catch (busiError) { + console.log("ndefMessage makeTextRecord catched busiError: " + busiError); +} +``` + + +## tag.ndef.makeMimeRecord9+ + +makeMimeRecord(mimeType: string, mimeData: number[]): [NdefRecord](#ndefrecord9); + +Creates an NDEF record based on the specified MIME data and type. + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| mimeType | string | Yes | MIME type that complies with RFC rules, for example, **text/plain** or **image/jpeg**.| +| mimeData | number[] | Yes | MIME data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +try { + let mimeType = "text/plain"; // change it to be correct. + let mimeData = [0x01, 0x02, 0x03, 0x04]; // change it to be correct. + let ndefRecord = tag.ndef.makeMimeRecord(mimeType, mimeData); + if (ndefRecord != undefined) { + console.log("ndefMessage makeMimeRecord rtdType: " + ndefRecord.rtdType); + console.log("ndefMessage makeMimeRecord payload: " + ndefRecord.payload); + } else { + console.log("ndefMessage makeMimeRecord ndefRecord: " + ndefRecord); + } +} catch (busiError) { + console.log("ndefMessage makeMimeRecord catched busiError: " + busiError); +} +``` +## tag.ndef.makeExternalRecord9+ + +makeExternalRecord(domainName: string, type: string, externalData: number[]): [NdefRecord](#ndefrecord9); + +Creates an NDEF record based on application-specific data. + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| domainName | string | Yes | Bundle name of the application or domain name of the organization that releases the applications.| +| type | string | Yes | Type of the application data.| +| externalData | number[] | Yes | Application data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +try { + let domainName = "ohos.nfc.application"; // change it to be correct. + let type = "test"; // change it to be correct. + let externalData = [0x01, 0x02, 0x03, 0x04]; // change it to be correct. + let ndefRecord = tag.ndef.makeExternalRecord(domainName, type, externalData); + if (ndefRecord != undefined) { + console.log("ndefMessage makeExternalRecord rtdType: " + ndefRecord.rtdType); + console.log("ndefMessage makeExternalRecord payload: " + ndefRecord.payload); + } else { + console.log("ndefMessage makeExternalRecord ndefRecord: " + ndefRecord); + } +} catch (busiError) { + console.log("ndefMessage makeExternalRecord catched busiError: " + busiError); +} +``` + +## tag.ndef.messageToBytes9+ + +messageToBytes(ndefMessage: [NdefMessage](js-apis-nfctech.md#ndefmessage9)): number[]; + +Converts an NDEF message to bytes. + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| ndefMessage | [NdefMessage](js-apis-nfctech.md#ndefmessage9) | Yes | NDEF message to convert.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number[] | NDEF message in bytes, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +let rawData = [0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]; // MUST can be parsed as NDEF Record. +let ndefMessage; +try { + ndefMessage = tag.ndef.createNdefMessage(rawData); + console.log("ndef createNdefMessage, ndefMessage: " + ndefMessage); +} catch (busiError) { + console.log("ndef createNdefMessage busiError: " + busiError); +} + +try { + let rawData2 = tag.ndef.messageToBytes(ndefMessage); + console.log("ndefMessage messageToBytes rawData2: " + rawData2); +} catch (busiError) { + console.log("ndefMessage messageToBytes catched busiError: " + busiError); +} +``` +## tag.ndef.createNdefMessage9+ + +createNdefMessage(data: number[]): [NdefMessage](js-apis-nfctech.md#ndefmessage9) + +Creates an NDEF message from raw byte data. The data must comply with the NDEF record format. Otherwise, the NDE record list contained in the **NdefMessage** object will be empty. + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| data | number[] | Yes| Raw byte data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**. The data must comply with the NDEF record format.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefMessage](js-apis-nfctech.md#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Example** +```js +import tag from '@ohos.nfc.tag'; + +let rawData = [0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]; // MUST can be parsed as NDEF Record. +let ndefMessage; +try { + ndefMessage = tag.ndef.createNdefMessage(rawData); + console.log("ndef createNdefMessage, ndefMessage: " + ndefMessage); +} catch (busiError) { + console.log("ndef createNdefMessage busiError: " + busiError); +} +``` + +## tag.ndef.createNdefMessage9+ + +createNdefMessage(ndefRecords: NdefRecord[]): [NdefMessage](js-apis-nfctech.md#ndefmessage9) + +Creates an NDEF message from the NDEF records list. + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| ndefRecords | [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | Yes| NDEF record list used to create the NDEF message. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefMessage](js-apis-nfctech.md#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +let uriRecord = tag.ndef.makeUriRecord("https://gitee.com/openharmony"); +let textRecord = tag.ndef.makeTextRecord("Hello World", "en"); +let ndefRecords = [uriRecord, textRecord]; +let ndefMessage; +try { + ndefMessage = tag.ndef.createNdefMessage(ndefRecords); + console.log("ndef createNdefMessage ndefMessage: " + ndefMessage); +} catch (busiError) { + console.log("ndef createNdefMessage busiError: " + busiError); +} +``` + +## TagInfo + +Defines the **TagInfo** object, which provides information about the tag technologies supported by a card. + +**System capability**: SystemCapability.Communication.NFC.Core **Required permissions**: ohos.permission.NFC_TAG +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| uid9+ | number[] | Yes| No| Tag unique identifier (UID), which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| +| technology9+ | number[] | Yes| No| Supported technologies. Each number is a constant indicating the supported technology.| +| supportedProfiles | number[] | Yes| No| Supported profiles. This parameter is not supported since API version 9. Use [tag.TagInfo#technology](#taginfo) instead.| +| extrasData9+ | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)[] | Yes| No| Extended attribute value of the tag technology.
**System API**: This is a system API.| +| tagRfDiscId9+ | number | Yes| No| ID allocated when the tag is discovered.
**System API**: This is a system API.| +| remoteTagService9+ | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | Yes| No| Remote object of the NFC service process used for interface communication between the client and the service.
**System API**: This is a system API.| +## NdefRecord9+ +Defines an NDEF record. For details, see *NFCForum-TS-NDEF_1.0*. + **System capability**: SystemCapability.Communication.NFC.Core -| **Name**| **Type**| **Description**| -| -------- | -------- | -------- | -| tnf | number | Type name field (TNF) of an NDEF record.| -| rtdType| number[] | Record type definition (RTD) of an NDEF record. Each number is a hexadecimal number ranging from **0x00** to **0xFF**.| -| id | number[] | ID of an NDEF record. Each number is a hexadecimal number ranging from **0x00** to **0xFF**.| -| payload | number[] | Payload of an NDEF record. Each number is a hexadecimal number ranging from **0x00** to **0xFF**.| + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| tnf | number | Yes| No| Type name field (TNF) of the NDEF record.| +| rtdType| number[] | Yes| No| Record type definition (RTD) of the NDEF record. It consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| +| id | number[] | Yes| No| NDEF record ID, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| +| payload | number[] | Yes| No| NDEF payload, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| ## Technology Type Definition Enumerates the tag technology types. -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Core + | **Name**| **Value**| **Description**| | -------- | -------- | -------- | | NFC_A | 1 | NFC-A (ISO 14443-3A).| -| NFC_B | 2 | NFC-A (ISO 14443-3B).| +| NFC_B | 2 | NFC-B (ISO 14443-3B).| | ISO_DEP | 3 | ISO-DEP (ISO 14443-4).| | NFC_F | 4 | NFC-F (JIS 6319-4).| | NFC_V | 5 | NFC-V (ISO 15693).| | NDEF | 6 | NDEF.| +| NDEF_FORMATABLE9+ | 7 | NDEF formattable.| | MIFARE_CLASSIC | 8 | MIFARE Classic.| | MIFARE_ULTRALIGHT | 9 | MIFARE Ultralight.| -| NDEF_FORMATABLE9+ | 10 | NDEF formattable.| ## TnfType9+ Enumerates the TNF types. For details, see *NFCForum-TS-NDEF_1.0*. -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Core + | **Name**| **Value**| **Description**| | -------- | -------- | -------- | | TNF_EMPTY | 0x0 | Empty.| -| TNF_WELL_KNOWN | 0x01 | NFC Forum Well Known Type [NFC RTD].| -| TNF_MEDIA | 0x02 | Media-type as defined in RFC 2046 [RFC 2046].| -| TNF_ABSOLUTE_URI | 0x03 | Absolute URI as defined in RFC 3986 [RFC 3986].| -| TNF_EXT_APP | 0x04 | NFC Forum external type [NFC RTD].| -| TNF_UNKNOWN | 0x05 | Unknown.| -| TNF_UNCHANGED | 0x06 | Unchanged (see section 2.3.3).| +| TNF_WELL_KNOWN | 0x1 | NFC Forum Well Known Type [NFC RTD].| +| TNF_MEDIA | 0x2 | Media-type as defined in RFC 2046 [RFC 2046].| +| TNF_ABSOLUTE_URI | 0x3 | Absolute URI as defined in RFC 3986 [RFC 3986].| +| TNF_EXT_APP | 0x4 | NFC Forum external type [NFC RTD].| +| TNF_UNKNOWN | 0x5 | Unknown.| +| TNF_UNCHANGED | 0x6 | Unchanged (see section 2.3.3 in *NFCForum-TS-NDEF_1.0*).| ## NDEF Record RTD Enumerates the NDEF record types. For details about the RTD, see *NFCForum-TS-NDEF_1.0*. -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Core + | **Name**| **Value**| **Description**| | -------- | -------- | -------- | | RTD_TEXT9+ | [0x54] | NDEF record of the text type.| @@ -328,36 +687,33 @@ Enumerates the NDEF record types. For details about the RTD, see *NFCForum-TS-ND ## NfcForumType9+ Enumerates the NFC Forum tag types. -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Core + | **Name**| **Value**| **Description**| | -------- | -------- | -------- | | NFC_FORUM_TYPE_1 | 1 | NFC Forum tag type 1.| | NFC_FORUM_TYPE_2 | 2 | NFC Forum tag type 2.| | NFC_FORUM_TYPE_3 | 3 | NFC Forum tag type 3.| | NFC_FORUM_TYPE_4 | 4 | NFC Forum tag type 4.| -| MIFARE_CLASSIC | 101 | MIFARE Classic type.| +| MIFARE_CLASSIC | 101 | MIFARE Classic.| ## MifareClassicType9+ Enumerates the MIFARE Classic tag types. -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Core + | **Name**| **Value**| **Description**| | -------- | -------- | -------- | -| TYPE_UNKNOWN | -1 | Unknown type.| -| TYPE_CLASSIC | 0 | MIFARE Classic.| -| TYPE_PLUS | 1 | MIFARE Plus.| -| TYPE_PRO | 2 | MIFARE Pro.| +| TYPE_UNKNOWN | 0 | Unknown type.| +| TYPE_CLASSIC | 1 | MIFARE Classic.| +| TYPE_PLUS | 2 | MIFARE Plus.| +| TYPE_PRO | 3 | MIFARE Pro.| ## MifareClassicSize9+ -Enumerates the storage sizes of MIFARE Classic tags. - -**Required permissions**: ohos.permission.NFC_TAG +Enumerates the sizes of MIFARE Classic tags. **System capability**: SystemCapability.Communication.NFC.Core + | **Name**| **Value**| **Description**| | -------- | -------- | -------- | | MC_SIZE_MINI | 320 | Each tag has 5 sectors, and each sector has 4 blocks.| @@ -365,15 +721,14 @@ Enumerates the storage sizes of MIFARE Classic tags. | MC_SIZE_2K | 2048 | Each tag has 32 sectors, and each sector has 4 blocks.| | MC_SIZE_4K | 4096 | Each tag has 40 sectors, and each sector has 4 blocks.| -### MifareUltralightType9+ +## MifareUltralightType9+ Enumerates the MIFARE Ultralight tag types. -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Core + | **Name**| **Value**| **Description**| | -------- | -------- | -------- | -| TYPE_UNKOWN | -1 | Unknown type.| +| TYPE_UNKNOWN | 0 | Unknown type.| | TYPE_ULTRALIGHT | 1 | MIFARE Ultralight.| | TYPE_ULTRALIGHT_C | 2 | MIFARE Ultralight C.| diff --git a/en/application-dev/reference/apis/js-apis-nfctech.md b/en/application-dev/reference/apis/js-apis-nfctech.md index 9817e5fd5c1f2a7f797f2c20fa7b6eff18dc25a5..e28864fc7bd2002838b7ae982bcb7b5269e2c086 100644 --- a/en/application-dev/reference/apis/js-apis-nfctech.md +++ b/en/application-dev/reference/apis/js-apis-nfctech.md @@ -1,11 +1,12 @@ -# NFC Tag Technologies +# nfctech The **nfctech** module provides APIs for reading and writing tags that use different Near-Field Communication (NFC) technologies. > **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -## **Modules to Import** +## Modules to Import ```js import tag from '@ohos.nfc.tag'; @@ -13,11 +14,11 @@ import tag from '@ohos.nfc.tag'; ## NfcATag -Provides access to NFC-A (ISO 14443-3A) properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access NFC-A (ISO 14443-3A) properties and perform I/O operations on a tag. This class inherits from **[TagSession](js-apis-tagSession.md)**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **NfcATag**. +The following describes the unique APIs of **NfcATag**. ### NfcATag.getSak @@ -40,8 +41,7 @@ Obtains the SAK value of this NFC-A tag. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcA' correctly. - +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcA' correctly. let sak = nfcA.getSak(); console.log("nfcA sak: " + sak); ``` @@ -67,18 +67,18 @@ Obtains the ATQA value of this NFC-A tag. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcA' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcA' correctly. let atqa = nfcA.getAtqa(); console.log("nfcA atqa: " + atqa); ``` ## NfcBTag -Provides access to NFC-B (ISO 14443-3B) properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access NFC-B (ISO 14443-3B) properties and perform I/O operations on a tag. This class inherits from **TagSession**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **NfcBTag**. +The following describes the unique APIs of **NfcBTag**. ### NfcBTag.getRespAppData @@ -94,14 +94,14 @@ Obtains the application data of this NFC-B tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | Application data obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number[] | Application data obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcB' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcB' correctly. let respAppData = nfcB.getRespAppData(); console.log("nfcB respAppData: " + respAppData); ``` @@ -120,25 +120,25 @@ Obtains the protocol information of this NFC-B tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | Protocol information obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number[] | Protocol information obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcB' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcB' correctly. let respProtocol = nfcB.getRespProtocol(); console.log("nfcB respProtocol: " + respProtocol); ``` ## NfcFTag -Provides access to NFC-F (JIS 6319-4) properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access NFC-F (JIS 6319-4) properties and perform I/O operations on a tag. This class inherits from **TagSession**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **NfcFTag**. +The following describes the unique APIs of **NfcFTag**. ### NfcFTag.getSystemCode @@ -154,14 +154,14 @@ Obtains the system code from this NFC-F tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | System code obtained. Each number in the system code is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number[] | System code obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcF' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcF' correctly. let systemCode = nfcF.getSystemCode(); console.log("nfcF systemCode: " + systemCode); ``` @@ -174,31 +174,31 @@ Obtains the PMm (consisting of the IC code and manufacturer parameters) informat **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | PMm information obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number[] | PMm information obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcF' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcF' correctly. let pmm = nfcF.getPmm(); console.log("nfcF pmm: " + pmm); ``` ## NfcVTag -Provides access to NFC-V (ISO 15693) properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access NFC-V (ISO 15693) properties and perform I/O operations on a tag. This class inherits from **TagSession**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **NfcVTag**. +The following describes the unique APIs of **NfcVTag**. ### NfcvTag.getResponseFlags @@ -208,20 +208,20 @@ Obtains the response flags from this NFC-V tag. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| number | Response flags obtained. The value is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number | Response flags obtained, which consist of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcV' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcV' correctly. let responseFlags = nfcV.getResponseFlags(); console.log("nfcV responseFlags: " + responseFlags); ``` @@ -234,54 +234,52 @@ Obtains the data storage format identifier (DSFID) from this NFC-V tag. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| number | DSFID obtained. The value is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number | DSFID obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcV' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcV' correctly. let dsfId = nfcV.getDsfId(); console.log("nfcV dsfId: " + dsfId); ``` ## IsoDepTag9+ -Provides access to ISO-DEP (ISO 14443-4) properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access ISO-DEP (ISO 14443-4) properties and I/O operations on a tag. This class inherits from **TagSession**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **IsoDepTag**. +The following describes the unique APIs of **IsoDepTag**. ### IsoDepTag.getHistoricalBytes9+ getHistoricalBytes(): number[] -Obtains the historical bytes of this tag. - -**Required permissions**: ohos.permission.NFC_TAG +Obtains the historical bytes for the given tag. This API applies only to the IsoDep cards that use the NFC-A technology. -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | Historical bytes obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number[] | Historical bytes obtained, which consist of hexadecimal numbers ranging from **0x00** to **0xFF**. If the IsoDep tag uses the NFC-B technology, **null** will be returned.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'isoDep' correctly. let historicalBytes = isoDep.getHistoricalBytes(); console.log("isoDep historicalBytes: " + historicalBytes); ``` @@ -290,24 +288,22 @@ console.log("isoDep historicalBytes: " + historicalBytes); getHiLayerResponse(): number[] -Obtains the HiLayer response of this tag. - -**Required permissions**: ohos.permission.NFC_TAG +Obtains the higher-layer response bytes for the given tag. This API applies only to the IsoDep cards that use the NFC-B technology. -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | HiLayer response obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number[] | Higher-layer response bytes obtained, which consist of hexadecimal numbers ranging from **0x00** to **0xFF**. If the IsoDep tag uses the NFC-A technology, **null** will be returned.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'isoDep' correctly. let hiLayerResponse = isoDep.getHiLayerResponse(); console.log("isoDep hiLayerResponse: " + hiLayerResponse); ``` @@ -320,7 +316,7 @@ Checks whether an extended application protocol data unit (APDU) is supported. T **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -328,18 +324,39 @@ Checks whether an extended application protocol data unit (APDU) is supported. T | ------------------ | --------------------------| | Promise<boolean> | Promise used to return the result. If the extended APDU is supported, **true** is returned; otherwise, **false** is returned.| +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. -isoDep.isExtendedApduSupported() - .then((data) => { - console.log("isoDep isExtendedApduSupported data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'isoDep' correctly. + +// Connect to the tag if it is not connected. +if (!isoDep.isTagConnected()) { + if (!isoDep.connectTag()) { + console.log("isoDep connectTag failed."); + return; + } +} + +try { + isoDep.isExtendedApduSupported().then((response) => { + console.log("isoDep isExtendedApduSupported Promise response: " + response); }).catch((err)=> { - console.log("isoDep isExtendedApduSupported err: " + err); + console.log("isoDep isExtendedApduSupported Promise err: " + err); }); +} catch (busiError) { + console.log("isoDep isExtendedApduSupported Promise busiError: " + busiError); +} + ``` ### IsoDepTag.isExtendedApduSupported9+ @@ -350,7 +367,7 @@ Checks whether an extended APDU is supported. This API uses an asynchronous call **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** @@ -358,251 +375,159 @@ Checks whether an extended APDU is supported. This API uses an asynchronous call | -------- | ----------------------- | ---- | -------------------------------------- | | callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the extended APDU is supported, **true** is returned; otherwise, **false** is returned.| -```js -import tag from '@ohos.nfc.tag'; - -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. -isoDep.isExtendedApduSupported((err, data)=> { - if (err) { - console.log("isoDep isExtendedApduSupported err: " + err); - } else { - console.log("isoDep isExtendedApduSupported data: " + data); - } -}); -``` - -## NdefTag9+ - -Provides access to the tags in the NFC Data Exchange Format (NDEF). This class inherits from **TagSession**. - -**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). - -The following describes the unique interfaces of **NdefTag**. - -### NdefTag.createNdefMessage9+ - -createNdefMessage(data: number[]): [NdefMessage](#ndefmessage9) +**Error codes** -Creates an NDEF message using raw bytes. +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC - -**Parameters** - -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| data | number[] | Yes| Raw bytes used to create the message. Each number is a hexadecimal number ranging from **0x00** to **0xFF**.| - -**Return value** - -| **Type**| **Description** | -| ------------------ | --------------------------| -| [NdefMessage](#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.| +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let rawData = [0x00, 0xa4, 0x04, ......]; // change the raw data bytes tobe correct. -let ndefMessage = ndef.createNdefMessage(rawData); -console.log("ndef ndefMessage: " + ndefMessage); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'isoDep' correctly. + +// Connect to the tag if it is not connected. +if (!isoDep.isTagConnected()) { + if (!isoDep.connectTag()) { + console.log("isoDep connectTag failed."); + return; + } +} + +try { + isoDep.isExtendedApduSupported((err, response)=> { + if (err) { + console.log("isoDep isExtendedApduSupported AsyncCallback err: " + err); + } else { + console.log("isoDep isExtendedApduSupported AsyncCallback response: " + response); + } + }); +} catch (busiError) { + console.log("isoDep isExtendedApduSupported AsyncCallback busiError: " + busiError); +} ``` ## NdefMessage9+ ### NdefMessage.getNdefRecords9+ -getNdefRecords(): [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[ ] +getNdefRecords(): [tag.NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] Obtains all NDEF records. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[ ] | List of NDEF records obtained. For details, see *NFCForum-TS-NDEF_1.0*.| +| [tag.NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | List of NDEF records obtained. For details, see *NFCForum-TS-NDEF_1.0*.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let ndefRecords = ndef.getNdefRecords(); +// Obtain ndefMessage from tag.ndef.createNdefMessage or ndefTag.getNdefMessage. +// var ndefMessage = tag.ndef.createNdefMessage(...); +// var ndefMessage = ndefTag.getNdefMessage(); + +let ndefRecords = ndefMessage.getNdefRecords(); console.log("ndef ndefRecords number: " + ndefRecords.length); ``` -### NdefTag.createNdefMessage9+ - -createNdefMessage(ndefRecords: NdefRecord[]): [NdefMessage](#ndefmessage9) - -Creates an NDEF message using the NDEF records. - -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC - -**Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| ndefRecords | [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | Yes| NDEF records used to create the NDEF message. For details, see *NFCForum-TS-NDEF_1.0*.| - -**Return value** - -| **Type**| **Description** | -| ------------------ | --------------------------| -| [NdefMessage](#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.| - -**Example** +## NdefTag9+ -```js -import tag from '@ohos.nfc.tag'; +Provides APIs to access the tags in the NFC Data Exchange Format (NDEF). This class inherits from **TagSession**. -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let ndefRecords = [ - // record format: tnf, rtdType, id, payload - // 1st record: - {tnf: 0x01, rtdType: [0x54], id: [0x01, 0x02, ...], payload: [0x00, 0xa4, 0x04, ...]}, +**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). - // 2nd record: - {tnf: 0x02, rtdType: [0x55], id: [0x03, 0x04, ...], payload: [0x00, 0xa4, 0x04, ...]}, - - // other record if has one ... -]; -let ndefMessage = ndef.createNdefMessage(ndefRecords); -console.log("ndef ndefMessage: " + ndefMessage); -``` +The following describes the unique APIs of **NdefTag**. ### NdefTag.getNdefTagType9+ -getNdefTagType(): NfcForumType +getNdefTagType(): [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9) -Obtains the type of this NDEF tag. +Obtains the NDEF tag type. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| [NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | NDEF tag type obtained. It can be NFC FORUM TYPE 1, 2, 3, or 4.| +| [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | NDEF tag type obtained. It can be NFC FORUM TYPE 1, 2, 3, or 4.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let ndefTagType = ndef.getNdefTagType(); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. +let ndefTagType = ndefTag.getNdefTagType(); console.log("ndef ndefTagType: " + ndefTagType); ``` ### NdefTag.getNdefMessage9+ -getNdefMessage(): NdefMessage +getNdefMessage(): [NdefMessage](#ndefmessage9) -Obtains the NDEF message. +Obtains the NDEF message from this NDEF tag. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| [NdefMessage](#ndefmessage9) | NDEF message obtained. For details, see *NFCForum-TS-NDEF_1.0*.| +| [NdefMessage](#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.| **Example** - ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let ndefMessage = ndef.getNdefMessage(); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. +let ndefMessage = ndefTag.getNdefMessage(); console.log("ndef ndefMessage: " + ndefMessage); ``` ### NdefTag.isNdefWritable9+ -isNdefWritable(): Promise<boolean> - -Checks whether the NDEF tag is writable. This API uses a promise to return the result. +isNdefWritable(): boolean; -**Required permissions**: ohos.permission.NFC_TAG +Check whether this NDEF tag is writable. Before calling the data write API, check whether the write operation is supported. -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| Promise<boolean> | Promise used to return the result. If the tag is writable, **true** is returned; otherwise, **false** is returned.| - -**Example** - -```js -import tag from '@ohos.nfc.tag'; - -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -ndef.isNdefWritable() - .then((data) => { - console.log("ndef isNdefWritable data: " + data); - }).catch((err)=> { - console.log("ndef isNdefWritable err: " + err); - }); -``` - -### NdefTag.isNdefWritable9+ - -isNdefWritable(callback: AsyncCallback<boolean>): void; - -Checks whether the NDEF tag is writable. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the tag is writable, **true** is returned; otherwise, **false** is returned.| +| boolean | Promise used to return the result. If the tag is writable, **true** is returned; otherwise, **false** is returned.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -ndef.isNdefWritable((err, data)=> { - if (err) { - console.log("ndef isNdefWritable err: " + err); - } else { - console.log("ndef isNdefWritable data: " + data); - } -}); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. +var isWritable = ndefTag.isNdefWritable(); +console.log("ndef isNdefWritable: " + isWritable); ``` ### NdefTag.readNdef9+ -readNdef(): Promise\ +readNdef(): Promise\<[NdefMessage](#ndefmessage9)> Reads the NDEF message from this tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -610,18 +535,38 @@ Reads the NDEF message from this tag. This API uses a promise to return the resu | ------------------ | --------------------------| | Promise\<[NdefMessage](#ndefmessage9)> | Promise used to return the message read.| +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -ndef.readNdef() - .then((data) => { - console.log("ndef readNdef data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. + +// Connect to the tag if it is not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; + } +} + +try { + ndefTag.readNdef().then((ndefmessage) => { + console.log("ndef readNdef Promise ndefmessage: " + ndefmessage); }).catch((err)=> { - console.log("ndef readNdef err: " + err); + console.log("ndef readNdef Promise err: " + err); }); +} catch (busiError) { + console.log("ndef readNdef Promise catched busiError: " + busiError); +} ``` ### NdefTag.readNdef9+ @@ -632,38 +577,59 @@ Reads the NDEF message from this tag. This API uses an asynchronous callback to **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\<[NdefMessage](#ndefmessage9)> | Yes | Callback invoked to return the result.| +| callback | AsyncCallback\<[NdefMessage](#ndefmessage9)> | Yes | Callback invoked to return the NDEF message read.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -ndef.readNdef((err, data)=> { - if (err) { - console.log("ndef readNdef err: " + err); - } else { - console.log("ndef readNdef data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. + +// Connect to the tag if it is not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; } -}); +} + +try { + ndefTag.readNdef((err, ndefmessage)=> { + if (err) { + console.log("ndef readNdef AsyncCallback err: " + err); + } else { + console.log("ndef readNdef AsyncCallback ndefmessage: " + ndefmessage); + } + }); +} catch (busiError) { + console.log("ndef readNdef AsyncCallback catched busiError: " + busiError); +} ``` ### NdefTag.writeNdef9+ -writeNdef(msg: NdefMessage): Promise\; +writeNdef(msg: NdefMessage): Promise\; Writes an NDEF message to this tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** @@ -671,59 +637,97 @@ Writes an NDEF message to this tag. This API uses a promise to return the result | -------- | ----------------------- | ---- | -------------------------------------- | | msg | NdefMessage | Yes | NDEF message to write.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let ndefMessage = ndef.createNdefMessage([0x01, 0x02, ...]); // change the raw data to be correct. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. +// NDEF message created from raw data, such as: +let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record. +// or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) -ndef.writeNdef(ndefMessage) - .then((data) => { - console.log("ndef writeNdef data: " + data); +// Connect to the tag if it is not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; + } +} + +try { + ndefTag.writeNdef(ndefMessage).then(() => { + console.log("ndef writeNdef Promise success."); }).catch((err)=> { console.log("ndef writeNdef err: " + err); }); +} catch (busiError) { + console.log("ndef writeNdef Promise catch busiError: " + busiError); +} ``` ### NdefTag.writeNdef9+ -writeNdef(msg: NdefMessage, callback: AsyncCallback\): void +writeNdef(msg: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void Writes an NDEF message to this tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| msg | NdefMessage | Yes | NDEF message to write.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| msg | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let ndefMessage = ndef.createNdefMessage([0x01, 0x02, ...]); // change the raw data to be correct. -ndef.writeNdef(ndefMessage, (err, data)=> { - if (err) { - console.log("ndef writeNdef err: " + err); - } else { - console.log("ndef writeNdef data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. +// NDEF message created from raw data, such as: +let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record. +// or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) + +// Connect to the tag if it is not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; } -}); +} + +try { + ndefTag.writeNdef(ndefMessage, (err)=> { + if (err) { + console.log("ndef writeNdef AsyncCallback err: " + err); + } else { + console.log("ndef writeNdef AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("ndef writeNdef AsyncCallback catch busiError: " + busiError); +} ``` ### NdefTag.canSetReadOnly9+ @@ -734,7 +738,7 @@ Checks whether this NDEF tag can be set to read-only. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -742,92 +746,133 @@ Checks whether this NDEF tag can be set to read-only. | ------------------ | --------------------------| | boolean| Returns **true** if the tag can be set to read-only; returns **false** otherwise.| +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -var canSetReadOnly = ndef.canSetReadOnly(); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. +var canSetReadOnly = ndefTag.canSetReadOnly(); console.log("ndef canSetReadOnly: " + canSetReadOnly); ``` ### NdefTag.setReadOnly9+ -setReadOnly(): Promise\ +setReadOnly(): Promise\ Sets this NDEF tag to read-only. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise<number> | Promise used to return the result. If the operation is successful, **0** is returned; otherwise, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -ndef.setReadOnly() - .then((data) => { - console.log("ndef setReadOnly data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. + +// Connect to the tag if it is not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; + } +} + +try { + ndefTag.setReadOnly().then(() => { + console.log("ndef setReadOnly Promise success."); }).catch((err)=> { - console.log("ndef setReadOnly err: " + err); + console.log("ndef setReadOnly Promise err: " + err); }); +} catch (busiError) { + console.log("ndef setReadOnly Promise catch busiError: " + busiError); +} ``` ### NdefTag.setReadOnly9+ -setReadOnly(callback: AsyncCallback\): void +setReadOnly(callback: AsyncCallback\): void Sets this NDEF tag to read-only. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -ndef.setReadOnly((err, data)=> { - if (err) { - console.log("ndef setReadOnly err: " + err); - } else { - console.log("ndef setReadOnly data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. + +// Connect to the tag if it is not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; } -}); +} + +try { + ndefTag.setReadOnly((err)=> { + if (err) { + console.log("ndef setReadOnly AsyncCallback err: " + err); + } else { + console.log("ndef setReadOnly AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("ndef setReadOnly AsyncCallback catch busiError: " + busiError); +} ``` ### NdefTag.getNdefTagTypeString9+ -getNdefTagTypeString(type: [NfcForumType](js-apis-nfcTag.md#nfcforumtype9)): string - -Converts an NFC Forum Type tag to a byte array defined in the NFC Forum. +getNdefTagTypeString(type: [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9)): string -**Required permissions**: ohos.permission.NFC_TAG +Converts an NFC Forum Type tag to a string defined in the NFC Forum. -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| type | [NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | Yes | NDEF tag type. It can be NFC FORUM type 1, 2, 3, or 4.| +| type | [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | Yes | NDEF tag type. It can be NFC FORUM type 1, 2, 3, or 4.| **Return value** @@ -840,110 +885,149 @@ Converts an NFC Forum Type tag to a byte array defined in the NFC Forum. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let ndefTypeString = ndef.getNdefTagTypeString(tag.NFC_FORUM_TYPE_1); -console.log("ndef ndefTypeString: " + ndefTypeString); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. + +try { + let ndefTypeString = ndefTag.getNdefTagTypeString(tag.NFC_FORUM_TYPE_1); + console.log("ndef ndefTypeString: " + ndefTypeString); +} catch (busiError) { + console.log("ndef getNdefTagTypeString catch busiError: " + busiError); +} ``` ## MifareClassicTag9+ -Provides access to MIFARE Classic properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access MIFARE Classic properties and perform I/O operations on a tag. This class inherits from [TagSession](js-apis-tagSession.md). **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **MifareClassicTag**. +The following describes the unique APIs of **MifareClassicTag**. ### MifareClassicTag.authenticateSector9+ -authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean): Promise\ +authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean): Promise\ -Authenticates a sector using the key. The sector can be accessed only after the authentication is successful. This API uses a promise to return the result. +Authenticates a sector using a key. The sector can be accessed only after the authentication is successful. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| sectorIndex | number | Yes | Index of the sector to authenticate.| -| key | number[]| Yes | Key (6 bytes) used for authentication.| +| sectorIndex | number | Yes | Index of the sector to authenticate. The sector indexes start from **0**.| +| key | number[]| Yes | Key (6 bytes) used for sector authentication.| | isKeyA | boolean | Yes | Whether the key is key A. The value **true** indicates key A, and **false** indicates key B.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If the authentication is successful, **true** is returned. Otherwise, **false** is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let sectorIndex = 1; // change it to be correct index. -let key = [0x04, 0x05, ....]; // change it to be correct key. -mifareClassic.authenticateSector(sectorIndex, key, true); - .then((data) => { - console.log("mifareClassic authenticateSector data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; + } +} + +try { + let sectorIndex = 1; // Change it as required. + let key = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06] // The key must be of 6 bytes. + mifareClassic.authenticateSector(sectorIndex, key, true).then(() => { + console.log("mifareClassic authenticateSector Promise success."); }).catch((err)=> { - console.log("mifareClassic authenticateSector err: " + err); + console.log("mifareClassic authenticateSector Promise err: " + err); }); +} catch (busiError) { + console.log("mifareClassic authenticateSector Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.authenticateSector9+ -authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean, callback: AsyncCallback\): void +authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean, callback: AsyncCallback\): void -Authenticates a sector using the key. The sector can be accessed only after the authentication is successful. This API uses an asynchronous callback to return the result. +Authenticates a sector using a key. The sector can be accessed only after the authentication is successful. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| sectorIndex | number | Yes | Index of the sector to authenticate.| -| key | number[]| Yes | Key (6 bytes) used for authentication.| +| sectorIndex | number | Yes | Index of the sector to authenticate. The sector indexes start from **0**.| +| key | number[]| Yes | Key (6 bytes) used for sector authentication.| | isKeyA | boolean | Yes | Whether the key is key A. The value **true** indicates key A, and **false** indicates key B.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| -**Example** +**Error codes** +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + +**Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let sectorIndex = 1; // change it to be correct index. -let key = [0x04, 0x05, ....]; // change it to be correct key. -mifareClassic.authenticateSector(sectorIndex, key, true, (err, data)=> { - if (err) { - console.log("mifareClassic authenticateSector err: " + err); - } else { - console.log("mifareClassic authenticateSector data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let sectorIndex = 1; // Change it as required. + let key = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06] // The key must be of 6 bytes. + mifareClassic.authenticateSector(sectorIndex, key, true, (err)=> { + if (err) { + console.log("mifareClassic authenticateSector AsyncCallback err: " + err); + } else { + console.log("mifareClassic authenticateSector AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic authenticateSector AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.readSingleBlock9+ readSingleBlock(blockIndex: number): Promise\ -Reads a block (16 bytes) on the tag. This API uses a promise to return the result. +Reads a block (16 bytes) on this tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block to read.| +| blockIndex | number | Yes | Index of the block to read. The block indexes start from **0**.| **Return value** @@ -951,421 +1035,632 @@ Reads a block (16 bytes) on the tag. This API uses a promise to return the resul | ------------------ | --------------------------| | Promise\ | Promise used to return the block data read.| +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.readSingleBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic readSingleBlock err: " + err); - } else { - console.log("mifareClassic readSingleBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + mifareClassic.readSingleBlock(blockIndex).then((data) => { + console.log("mifareClassic readSingleBlock Promise data: " + data); + }).catch((err)=> { + console.log("mifareClassic readSingleBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic readSingleBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.readSingleBlock9+ readSingleBlock(blockIndex: number, callback: AsyncCallback\): void -Reads a block (16 bytes) on the tag. This API uses an asynchronous callback to return the result. +Reads a block (16 bytes) on this tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block to read.| +| blockIndex | number | Yes | Index of the block to read. The block indexes start from **0**.| | callback | AsyncCallback\ | Yes | Callback invoked to return the block read.| +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.readSingleBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic readSingleBlock err: " + err); - } else { - console.log("mifareClassic readSingleBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + mifareClassic.readSingleBlock(blockIndex, (err, data)=> { + if (err) { + console.log("mifareClassic readSingleBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic readSingleBlock AsyncCallback data: " + data); + } + }); +} catch (busiError) { + console.log("mifareClassic readSingleBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.writeSingleBlock9+ -writeSingleBlock(blockIndex: number, data: number[]): Promise\ +writeSingleBlock(blockIndex: number, data: number[]): Promise\ -Writes data to a block on the tag. This API uses a promise to return the result. +Writes data to a block on this tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the target block.| -| data | number[] | Yes | Data to write.| +| blockIndex | number | Yes | Index of the target block. The block indexes start from **0**.| +| data | number[] | Yes | 16-byte data to write.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let rawData = [0x0a, 0x14, ...]; // change it to be correct data. -mifareClassic.writeSingleBlock(blockIndex, rawData, (err, data)=> { - if (err) { - console.log("mifareClassic writeSingleBlock err: " + err); - } else { - console.log("mifareClassic writeSingleBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + let rawData = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, + 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10]; // MUST be 16 bytes, change it to be correct data. + mifareClassic.writeSingleBlock(blockIndex, rawData).then(() => { + console.log("mifareClassic writeSingleBlock Promise success."); + }).catch((err)=> { + console.log("mifareClassic writeSingleBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic writeSingleBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.writeSingleBlock9+ -writeSingleBlock(blockIndex: number, data: number[], callback: AsyncCallback\): void +writeSingleBlock(blockIndex: number, data: number[], callback: AsyncCallback\): void -Writes data to a block on the tag. This API uses an asynchronous callback to return the result. +Writes data to a block on this tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the target block.| -| data | number[] | Yes | Data to write.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| blockIndex | number | Yes | Index of the target block. The block indexes start from **0**.| +| data | number[] | Yes | 16-byte data to write.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let rawData = [0x0a, 0x14, ...]; // change it to be correct data. -mifareClassic.writeSingleBlock(blockIndex, rawData, (err, data)=> { - if (err) { - console.log("mifareClassic writeSingleBlock err: " + err); - } else { - console.log("mifareClassic writeSingleBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + let rawData = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, + 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10]; // MUST be 16 bytes, change it to be correct data. + mifareClassic.writeSingleBlock(blockIndex, rawData, (err)=> { + if (err) { + console.log("mifareClassic writeSingleBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic writeSingleBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic writeSingleBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.incrementBlock9+ -incrementBlock(blockIndex: number, value: number): Promise\ +incrementBlock(blockIndex: number, value: number): Promise\ Increments a block with data. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block to increment.| -| value | number | Yes | Block data to increment. The value is a non-negative number.| +| blockIndex | number | Yes | Index of the block to increment. The block indexes start from **0**.| +| value | number | Yes | Block data to increment. The value cannot be a negative number.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let value = 0x20; // change it to be correct data. -mifareClassic.incrementBlock(blockIndex, value, (err, data)=> { - if (err) { - console.log("mifareClassic incrementBlock err: " + err); - } else { - console.log("mifareClassic incrementBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + let value = 0x20; // Change it as required. + mifareClassic.incrementBlock(blockIndex, value).then(() => { + console.log("mifareClassic incrementBlock Promise success."); + }).catch((err)=> { + console.log("mifareClassic incrementBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic incrementBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.incrementBlock9+ -incrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void +incrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void Increments a block with data. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block to increment.| -| value | number | Yes | Block data to increment. The value is a non-negative number.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| blockIndex | number | Yes | Index of the block to increment. The block indexes start from **0**.| +| value | number | Yes | Block data to increment. The value cannot be a negative number.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let value = 0x20; // change it to be correct data. -mifareClassic.incrementBlock(blockIndex, value, (err, data)=> { - if (err) { - console.log("mifareClassic incrementBlock err: " + err); - } else { - console.log("mifareClassic incrementBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + let value = 0x20; // Change it as required. + mifareClassic.incrementBlock(blockIndex, value, (err)=> { + if (err) { + console.log("mifareClassic incrementBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic incrementBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic incrementBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.decrementBlock9+ -decrementBlock(blockIndex: number, value: number): Promise\ +decrementBlock(blockIndex: number, value: number): Promise\ -Decrements a block with data. This API uses a promise to return the result. +Decrements a block. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block to decrement.| -| value | number | Yes | Block data to decrement. The value is a non-negative number.| +| blockIndex | number | Yes | Index of the block to decrement. The block indexes start from **0**.| +| value | number | Yes | Block data to decrement. The value cannot be a negative number.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let value = 0x20; // change it to be correct data. -mifareClassic.decrementBlock(blockIndex, value, (err, data)=> { - if (err) { - console.log("mifareClassic decrementBlock err: " + err); - } else { - console.log("mifareClassic decrementBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + let value = 0x20; // Change it as required. + mifareClassic.decrementBlock(blockIndex, value).then(() => { + console.log("mifareClassic decrementBlock Promise success."); + }).catch((err)=> { + console.log("mifareClassic decrementBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic decrementBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.decrementBlock9+ -decrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void +decrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void -Decrements a block with data. This API uses an asynchronous callback to return the result. +Decrements a block. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block to decrement.| -| value | number | Yes | Block data to decrement. The value is a non-negative number.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| blockIndex | number | Yes | Index of the block to decrement. The block indexes start from **0**.| +| value | number | Yes | Block data to decrement. The value cannot be a negative number.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let value = 0x20; // change it to be correct data. -mifareClassic.decrementBlock(blockIndex, value, (err, data)=> { - if (err) { - console.log("mifareClassic decrementBlock err: " + err); - } else { - console.log("mifareClassic decrementBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + let value = 0x20; // Change it as required. + mifareClassic.decrementBlock(blockIndex, value, (err)=> { + if (err) { + console.log("mifareClassic decrementBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic decrementBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic decrementBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.transferToBlock9+ -transferToBlock(blockIndex: number): Promise\ +transferToBlock(blockIndex: number): Promise\ -Copies data from the register to a block. This API uses a promise to return the result. +Transfers data from the temporary register to a block. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the destination block.| +| blockIndex | number | Yes | Index of the destination block. The value starts form **0**.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js - import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.transferToBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic transferToBlock err: " + err); - } else { - console.log("mifareClassic transferToBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + mifareClassic.transferToBlock(blockIndex).then(() => { + console.log("mifareClassic transferToBlock Promise success."); + }).catch((err)=> { + console.log("mifareClassic transferToBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic transferToBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.transferToBlock9+ -transferToBlock(blockIndex: number, callback: AsyncCallback\): void +transferToBlock(blockIndex: number, callback: AsyncCallback\): void -Copies data from the register to a block. This API uses an asynchronous callback to return the result. +Transfers data from the temporary register to a block. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the destination block.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| blockIndex | number | Yes | Index of the destination block. The value starts form **0**.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.transferToBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic transferToBlock err: " + err); - } else { - console.log("mifareClassic transferToBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + mifareClassic.transferToBlock(blockIndex, (err)=> { + if (err) { + console.log("mifareClassic transferToBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic transferToBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic transferToBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.restoreFromBlock9+ -restoreFromBlock(blockIndex: number): Promise\ +restoreFromBlock(blockIndex: number): Promise\ -Copies data from a block to the register. This API uses a promise to return the result. +Restores data in the temporary register from a block. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the source block.| +| blockIndex | number | Yes | Index of the target block. The value starts form **0**.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js - import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.restoreFromBlock(blockIndex) - .then((data) => { - console.log("mifareClassic restoreFromBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; + } +} + +try { + let blockIndex = 1; // Change it as required. + mifareClassic.restoreFromBlock(blockIndex).then(() => { + console.log("mifareClassic restoreFromBlock Promise success."); }).catch((err)=> { - console.log("mifareClassic isExtendrestoreFromBlockedApduSupported err: " + err); + console.log("mifareClassic restoreFromBlock Promise err: " + err); }); +} catch (busiError) { + console.log("mifareClassic restoreFromBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.restoreFromBlock9+ -restoreFromBlock(blockIndex: number, callback: AsyncCallback\): void +restoreFromBlock(blockIndex: number, callback: AsyncCallback\): void -Copies data from a block to the register. This API uses an asynchronous callback to return the result. +Restores data in the temporary register from a block. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the source block.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| blockIndex | number | Yes | Index of the target block. The value starts form **0**.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.restoreFromBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic restoreFromBlock err: " + err); - } else { - console.log("mifareClassic restoreFromBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + mifareClassic.restoreFromBlock(blockIndex, (err)=> { + if (err) { + console.log("mifareClassic restoreFromBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic restoreFromBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic restoreFromBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.getSectorCount9+ @@ -1374,9 +1669,7 @@ getSectorCount(): number Obtains the number of sectors in this MIFARE Classic tag. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -1389,7 +1682,7 @@ Obtains the number of sectors in this MIFARE Classic tag. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. let sectorCount = mifareClassic.getSectorCount(); console.log("mifareClassic sectorCount: " + sectorCount); ``` @@ -1400,15 +1693,13 @@ getBlockCountInSector(sectorIndex: number): number Obtains the number of blocks in a sector. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| sectorIndex | number | Yes | Index of the sector.| +| sectorIndex | number | Yes | Index of the target sector. The sector indexes start from **0**.| **Return value** @@ -1421,33 +1712,37 @@ Obtains the number of blocks in a sector. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockCountInSector = mifareClassic.getBlockCountInSector(); -console.log("mifareClassic blockCountInSector: " + blockCountInSector); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +try { + let sectorIndex = 1; // Change it as required. + let blockCnt = mifareClassic.getBlockCountInSector(sectorIndex); + console.log("mifareClassic blockCnt: " + blockCnt); +} catch (busiError) { + console.log("mifareClassic getBlockCountInSector catch busiError: " + busiError); +} ``` ### MifareClassicTag.getType9+ -getType(): [MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) +getType(): [tag.MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) Obtains the type of this MIFARE Classic tag. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| [MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) | Type of the MIFARE Classic tag obtained.| +| [tag.MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) | Type of the MIFARE Classic tag obtained.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. let getType = mifareClassic.getType(); console.log("mifareClassic getType: " + getType); ``` @@ -1456,11 +1751,9 @@ console.log("mifareClassic getType: " + getType); getTagSize(): number -Obtains the tag size (in bytes). For details, see [MifareClassicSize](js-apis-nfcTag.md#mifareclassicsize9). - -**Required permissions**: ohos.permission.NFC_TAG +Obtains the size of this tag. For details, see [MifareClassicSize](js-apis-nfcTag.md#mifareclassicsize9). -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -1473,7 +1766,7 @@ Obtains the tag size (in bytes). For details, see [MifareClassicSize](js-apis-nf ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. let tagSize = mifareClassic.getTagSize(); console.log("mifareClassic tagSize: " + tagSize); ``` @@ -1482,11 +1775,9 @@ console.log("mifareClassic tagSize: " + tagSize); isEmulatedTag(): boolean -Checks whether the tag is an emulated tag. +Checks whether it is an emulated tag. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -1499,7 +1790,7 @@ Checks whether the tag is an emulated tag. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. let isEmulatedTag = mifareClassic.isEmulatedTag(); console.log("mifareClassic isEmulatedTag: " + isEmulatedTag); ``` @@ -1508,17 +1799,15 @@ console.log("mifareClassic isEmulatedTag: " + isEmulatedTag); getBlockIndex(sectorIndex: number): number -Obtains the first block of a sector. +Obtains the index of the first block in a sector. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| sectorIndex | number | Yes | Index of the sector.| +| sectorIndex | number | Yes | Index of the target sector. The sector indexes start from **0**.| **Return value** @@ -1531,27 +1820,30 @@ Obtains the first block of a sector. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let sectorIndex = 1; // change it to be correct index. -let blockIndex = mifareClassic.getBlockIndex(sectorIndex); -console.log("mifareClassic blockIndex: " + blockIndex); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +try { + let sectorIndex = 1; // Change it as required. + let blockIndex = mifareClassic.getBlockIndex(sectorIndex); + console.log("mifareClassic blockIndex: " + blockIndex); +} catch (busiError) { + console.log("mifareClassic getBlockIndex catch busiError: " + busiError); +} ``` ### MifareClassicTag.getSectorIndex9+ getSectorIndex(blockIndex: number): number -Obtains the index of a sector that contains the specified block. - -**Required permissions**: ohos.permission.NFC_TAG +Obtains the index of a sector that holds the specified block. -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block contained in the sector.| +| blockIndex | number | Yes| Index of the block. The block indexes start from **0**.| **Return value** @@ -1564,41 +1856,54 @@ Obtains the index of a sector that contains the specified block. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let sectorIndex = mifareClassic.getSectorIndex(blockIndex); -console.log("mifareClassic sectorIndex: " + sectorIndex); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +try { + let blockIndex = 1; // Change it as required. + let sectorIndex = mifareClassic.getSectorIndex(blockIndex); + console.log("mifareClassic sectorIndex: " + sectorIndex); +} catch (busiError) { + console.log("mifareClassic getSectorIndex catch busiError: " + busiError); +} ``` ## MifareUltralightTag9+ -Provides access to MIFARE Ultralight properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access MIFARE Ultralight properties and perform I/O operations on a tag. This class inherits from **TagSession**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **MifareUltralightTag**. +The following describes the unique APIs of **MifareUltralightTag**. ### MifareUltralightTag.readMultiplePages9+ readMultiplePages(pageIndex: number): Promise\ -Reads multiple pages (4 bytes per page). This API uses a promise to return the result. +Reads four pages (4 bytes per page) from this tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------------ | -| pageIndex | number | Yes | Indexes of the pages to read.| +| pageIndex | number | Yes | Index of the first page to read. The page indexes start from **0**.| **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| Promise\ | Promise used to return the data read.| +| Promise\ | Promise used to return the data read, which is 16 bytes in total.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** @@ -1606,207 +1911,286 @@ Reads multiple pages (4 bytes per page). This API uses a promise to return the r import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. -let pageIndex = 1; // change it to be correct index. -mifareUltralight.readMultiplePages(pageIndex) - .then((data) => { - console.log("mifareUltralight readMultiplePages data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly. + +// Connect to the tag if it is not connected. +if (!mifareUltralight.isTagConnected()) { + if (!mifareUltralight.connectTag()) { + console.log("mifareUltralight connectTag failed."); + return; + } +} + +try { + let pageIndex = 1; // Change it as required. + mifareUltralight.readMultiplePages(pageIndex).then((data) => { + console.log("mifareUltralight readMultiplePages Promise data = " + data); }).catch((err)=> { - console.log("mifareUltralight readMultiplePages err: " + err); + console.log("mifareUltralight readMultiplePages Promise err: " + err); }); +} catch (busiError) { + console.log("mifareUltralight readMultiplePages Promise catch busiError: " + busiError); +} ``` ### MifareUltralightTag.readMultiplePages9+ readMultiplePages(pageIndex: number, callback: AsyncCallback\): void -Reads multiple pages (4 bytes per page). This API uses an asynchronous callback to return the result. +Reads four pages (4 bytes per page) from this tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| pageIndex | number | Yes | Indexes of the pages to read.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| pageIndex | number | Yes | Index of the first page to read. The page indexes start from **0**.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the data read, which is 16 bytes in total.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. -let pageIndex = 1; // change it to be correct index. -mifareUltralight.readMultiplePages(pageIndex, (err, data)=> { - if (err) { - console.log("mifareUltralight readMultiplePages err: " + err); - } else { - console.log("mifareUltralight readMultiplePages data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly. + +// Connect to the tag if it is not connected. +if (!mifareUltralight.isTagConnected()) { + if (!mifareUltralight.connectTag()) { + console.log("mifareUltralight connectTag failed."); + return; } -}); +} + +try { + let pageIndex = 1; // Change it as required. + mifareUltralight.readMultiplePages(pageIndex, (err, data)=> { + if (err) { + console.log("mifareUltralight readMultiplePages AsyncCallback err: " + err); + } else { + console.log("mifareUltralight readMultiplePages AsyncCallback data: " + data); + } + }); +} catch (busiError) { + console.log("mifareUltralight readMultiplePages AsyncCallback catch busiError: " + busiError); +} ``` -### MifareUltralightTag.writeSinglePages9+ +### MifareUltralightTag.writeSinglePage9+ -writeSinglePages(pageIndex: number, data: number[]): Promise\ +writeSinglePage(pageIndex: number, data: number[]): Promise\ -Writes a page of data. This API uses a promise to return the result. +Writes one page (4 bytes) of data to this tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| pageIndex | number | Yes | Index of the page.| -| data | number[] | Yes | Data to write.| +| pageIndex | number | Yes | Index of the page to write. The page indexes start from **0**.| +| data | number[] | Yes | 4-byte data to write.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. -let pageIndex = 1; // change it to be correct index. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -mifareUltralight.writeSinglePages(pageIndex, data) - .then((data) => { - console.log("mifareUltralight writeSinglePages data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly. + +// Connect to the tag if it is not connected. +if (!mifareUltralight.isTagConnected()) { + if (!mifareUltralight.connectTag()) { + console.log("mifareUltralight connectTag failed."); + return; + } +} + +try { + let pageIndex = 1; // Change it as required. + let rawData = [0x01, 0x02, 0x03, 0x04]; // MUST be 4 bytes, change it to be correct raw data. + mifareUltralight.writeSinglePage(pageIndex, rawData).then(() => { + console.log("mifareUltralight writeSinglePage Promise success."); }).catch((err)=> { - console.log("mifareUltralight writeSinglePages err: " + err); + console.log("mifareUltralight writeSinglePage Promise err: " + err); }); +} catch (busiError) { + console.log("mifareUltralight writeSinglePage Promise catch busiError: " + busiError); +} ``` -### MifareUltralightTag.writeSinglePages9+ +### MifareUltralightTag.writeSinglePage9+ -writeSinglePages(pageIndex: number, data: number[], callback: AsyncCallback\): void +writeSinglePage(pageIndex: number, data: number[], callback: AsyncCallback\): void -Writes a page of data. This API uses an asynchronous callback to return the result. +Writes one page (4 bytes) of data to this tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------ | -| pageIndex | number | Yes | Index of the page.| -| data | number[] | Yes | Data to write.| -| callback|AsyncCallback\ |Yes| Callback invoked to return the result.| +| pageIndex | number | Yes | Index of the page to write. The page indexes start from **0**.| +| data | number[] | Yes | 4-byte data to write.| +| callback|AsyncCallback\ |Yes| Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. -let pageIndex = 1; // change it to be correct index. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -mifareUltralight.writeSinglePages(pageIndex, data, (err, data)=> { - if (err) { - console.log("mifareUltralight writeSinglePages err: " + err); - } else { - console.log("mifareUltralight writeSinglePages data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly. + +// Connect to the tag if it is not connected. +if (!mifareUltralight.isTagConnected()) { + if (!mifareUltralight.connectTag()) { + console.log("mifareUltralight connectTag failed."); + return; } -}); +} + +try { + let pageIndex = 1; // Change it as required. + let rawData = [0x01, 0x02, 0x03, 0x04]; // MUST be 4 bytes, change it to be correct raw data. + mifareUltralight.writeSinglePage(pageIndex, rawData, (err)=> { + if (err) { + console.log("mifareUltralight writeSinglePage AsyncCallback err: " + err); + } else { + console.log("mifareUltralight writeSinglePage AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareUltralight writeSinglePage AsyncCallback catch busiError: " + busiError); +} ``` ### MifareUltralightTag.getType9+ -getType(): MifareUltralightType +getType(): [tag.MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9) -Obtains the MIFARE Ultralight tag type, in bytes. For details, see [MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9). - -**Required permissions**: ohos.permission.NFC_TAG +Obtains the type of this MIFARE Ultralight tag. -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| MifareUltralightType | MIFARE Ultralight tag type obtained. For details, see [MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9).| +| [tag.MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9) | Type of the MIFARE Ultralight tag obtained.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly. let getType = mifareClassic.getType(); console.log("mifareUltralight getType: " + getType); ``` ## NdefFormatableTag9+ -Provides APIs for operating NDEF formattable tags. This class inherits from **TagSession**. +Provides APIs for formatting NDEF formattable tags. This class inherits from **TagSession**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **NdefFormatableTag**. +The following describes the unique APIs of **NdefFormatableTag**. ### NdefFormatableTag.format9+ -format(message: [NdefMessage](#ndefmessage9)): Promise\ +format(message: [NdefMessage](#ndefmessage9)): Promise\ -Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API uses a promise to return the result. +Formats this tag as an NDEF tag, and writes an NDEF message to it. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only (no data will be written).| +| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write. If this parameter is **null**, the tag is formatted only (no data will be written).| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -let ndefmessage = ndef.createNdefMessage(data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefFormatable' correctly. -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndefFormatable' correctly. -ndefFormatable.format(ndefmessage, (err, data)=> { - if (err) { - console.log("ndefFormatable format err: " + err); - } else { - console.log("ndefFormatable format data: " + data); +// Connect to the tag if it is not connected. +if (!ndefFormatable.isTagConnected()) { + if (!ndefFormatable.connectTag()) { + console.log("ndefFormatable connectTag failed."); + return; } -}); +} + +try { + // NDEF message created from raw data, such as: + let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record. + // or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) + + ndefFormatable.format(ndefMessage).then(() => { + console.log("ndefFormatable format Promise success."); + }).catch((err)=> { + console.log("ndefFormatable format Promise err: " + err); + }); +} catch (busiError) { + console.log("ndefFormatable format Promise catch busiError: " + busiError); +} ``` ### NdefFormatableTag.format9+ -format(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void +format(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void -Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API uses an asynchronous callback to return the result. +Formats this tag as an NDEF tag, and writes an NDEF message to it. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** @@ -1818,7 +2202,7 @@ Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API | **Type**| **Description** | | ------------------ | --------------------------| -| callback: AsyncCallback\ | Callback invoked to return the result.| +| callback: AsyncCallback\ | Callback invoked to return the result.| **Example** @@ -1826,82 +2210,108 @@ Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -let ndefmessage = ndef.createNdefMessage(data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefFormatable' correctly. -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndefFormatable' correctly. -ndefFormatable.format(ndefmessage, (err, data)=> { - if (err) { - console.log("ndefFormatable format err: " + err); - } else { - console.log("ndefFormatable format data: " + data); +// Connect to the tag if it is not connected. +if (!ndefFormatable.isTagConnected()) { + if (!ndefFormatable.connectTag()) { + console.log("ndefFormatable connectTag failed."); + return; } -}); +} + +try { + // NDEF message created from raw data, such as: + let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record. + // or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) + + ndefFormatable.format(ndefMessage, (err)=> { + if (err) { + console.log("ndefFormatable format AsyncCallback err: " + err); + } else { + console.log("ndefFormatable format AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("ndefFormatable format AsyncCallback catch busiError: " + busiError); +} ``` ### NdefFormatableTag.formatReadOnly9+ -formatReadOnly(message: [NdefMessage](#ndefmessage9)): Promise\ +formatReadOnly(message: [NdefMessage](#ndefmessage9)): Promise\ -Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and then sets the tag to read-only. This API uses a promise to return the result. +Formats this tag as an NDEF tag, writes an NDEF message to it, and then sets the tag to read-only. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only (no data will be written).| +| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write. If this parameter is **null**, the tag is formatted only (no data will be written).| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -let ndefmessage = ndef.createNdefMessage(data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefFormatable' correctly. -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndefFormatable' correctly. -ndefFormatable.formatReadOnly(ndefmessage, (err, data)=> { - if (err) { - console.log("ndefFormatable formatReadOnly err: " + err); - } else { - console.log("ndefFormatable formatReadOnly data: " + data); +// Connect to the tag if it is not connected. +if (!ndefFormatable.isTagConnected()) { + if (!ndefFormatable.connectTag()) { + console.log("ndefFormatable connectTag failed."); + return; } -}); +} + +try { + // NDEF message created from raw data, such as: + let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record. + // or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) + + ndefFormatable.formatReadOnly(ndefMessage).then(() => { + console.log("ndefFormatable formatReadOnly Promise success."); + }).catch((err)=> { + console.log("ndefFormatable formatReadOnly Promise err: " + err); + }); +} catch (busiError) { + console.log("ndefFormatable formatReadOnly Promise catch busiError: " + busiError); +} ``` ### NdefFormatableTag.formatReadOnly9+ -formatReadOnly(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void +formatReadOnly(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and then sets the tag to read-only. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only (no data will be written).| +| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write. If this parameter is **null**, the tag is formatted only (no data will be written).| **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| callback: AsyncCallback\ | Callback invoked to return the result.| +| callback: AsyncCallback\ | Callback invoked to return the result.| **Example** @@ -1909,16 +2319,29 @@ Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and the ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -let ndefmessage = ndef.createNdefMessage(data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefFormatable' correctly. -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndefFormatable' correctly. -ndefFormatable.formatReadOnly(ndefmessage, (err, data)=> { - if (err) { - console.log("ndefFormatable formatReadOnly err: " + err); - } else { - console.log("ndefFormatable formatReadOnly data: " + data); +// Connect to the tag if it is not connected. +if (!ndefFormatable.isTagConnected()) { + if (!ndefFormatable.connectTag()) { + console.log("ndefFormatable connectTag failed."); + return; } -}); +} + +try { + // NDEF message created from raw data, such as: + let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record. + // or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) + + ndefFormatable.formatReadOnly(ndefMessage, (err)=> { + if (err) { + console.log("ndefFormatable formatReadOnly AsyncCallback err: " + err); + } else { + console.log("ndefFormatable formatReadOnly AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("ndefFormatable formatReadOnly AsyncCallback catch busiError: " + busiError); +} ``` diff --git a/en/application-dev/reference/apis/js-apis-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md index 36e075f0e24f3a01dfc7feddc29173c364e0b885..f903401701e9f68ae6277a687215310f59afc34c 100644 --- a/en/application-dev/reference/apis/js-apis-osAccount.md +++ b/en/application-dev/reference/apis/js-apis-osAccount.md @@ -1,8 +1,9 @@ -# OS Account Management +# @ohos.account.osAccount The **osAccount** module provides basic capabilities for managing OS accounts, including adding, deleting, querying, setting, subscribing to, and enabling an OS account. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -37,7 +38,7 @@ Enumerates the OS account types. **System capability**: SystemCapability.Account.OsAccount -| Name | Default Value| Description | +| Name | Value| Description | | ------ | ------ | ----------- | | ADMIN | 0 | Administrator account| | NORMAL | 1 | Normal account | @@ -154,7 +155,7 @@ Checks whether multiple OS accounts are supported. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ------------------------------------------------------ | -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, multiple OS accounts are supported. If **false** is returned, multiple OS accounts are not supported.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means multiple OS accounts are supported; the value false means the opposite.| **Error codes** @@ -191,7 +192,7 @@ Checks whether multiple OS accounts are supported. This API uses a promise to re | Type | Description | | :--------------------- | :--------------------------------------------------------- | -| Promise<boolean> | Promise used to return the result. If **true** is returned, multiple OS accounts are supported. If **false** is returned, multiple OS accounts are not supported.| +| Promise<boolean> | Promise used to return the result. The value **true** means multiple OS accounts are supported; the value false means the opposite.| **Error codes** @@ -220,7 +221,7 @@ checkOsAccountActivated(localId: number, callback: AsyncCallback<boolean>) Checks whether an OS account is activated. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS **System capability**: SystemCapability.Account.OsAccount @@ -229,7 +230,7 @@ Checks whether an OS account is activated. This API uses an asynchronous callbac | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ------------------------------------------------------ | | localId | number | Yes | ID of the target OS account. | -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, the account is activated. If **false** is returned, the account is not activated.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means the account is activated; the value **false** means the opposite.| **Error codes** @@ -277,7 +278,7 @@ Checks whether an OS account is activated. This API uses a promise to return the | Type | Description | | ---------------------- | ---------------------------------------------------------- | -| Promise<boolean> | Promise used to return the result. If **true** is returned, the account is activated. If **false** is returned, the account is not activated.| +| Promise<boolean> | Promise used to return the result. The value **true** means the account is activated; the value **false** means the opposite.| **Error codes** @@ -309,7 +310,7 @@ checkConstraintEnabled(localId: number, constraint: string, callback: AsyncCallb Checks whether the specified constraint is enabled for an OS account. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS **System capability**: SystemCapability.Account.OsAccount @@ -319,7 +320,7 @@ Checks whether the specified constraint is enabled for an OS account. This API u | ---------- | ---------------------------- | ---- | ----------------------------------------------------------------- | | localId | number | Yes | ID of the target OS account. | | constraint | string | Yes | [Constraint](#constraints) to check. | -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, the constraint is enabled. If **false** is returned, the constraint is not enabled.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means the specified constraint is enabled; the value **false** means the opposite.| **Error codes** @@ -369,7 +370,7 @@ Checks whether the specified constraint is enabled for an OS account. This API u | Type | Description | | --------------------- | --------------------------------------------------------------------- | -| Promise<boolean> | Promise used to return the result. If **true** is returned, the constraint is enabled. If **false** is returned, the constraint is not enabled.| +| Promise<boolean> | Promise used to return the result. The value **true** means the specified constraint is enabled; the value **false** means the opposite.| **Error codes** @@ -408,7 +409,7 @@ Checks whether this OS account is a test account. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | --------------------------------------------------------------------- | -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, the account is a test account. If **false** is returned, the account is not a test account.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means the account is a test account; the value **false** means the opposite.| **Error codes** @@ -445,7 +446,7 @@ Checks whether this OS account is a test account. This API uses a promise to ret | Type | Description | | ---------------------- | ------------------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the result. If **true** is returned, the account is a test account. If **false** is returned, the account is not a test account.| +| Promise<boolean> | Promise used to return the result. The value **true** means the account is a test account; the value **false** means the opposite.| **Error codes** @@ -482,7 +483,7 @@ Checks whether this OS account has been verified. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ------------------------------------------------------------- | -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, the account has been verified. If **false** is returned, the account has not been verified.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If true is returned, the current account has been verified. If false is returned, the current account has not been verified.| **Error codes** @@ -523,8 +524,8 @@ Checks whether an OS account has been verified. This API uses an asynchronous ca | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ------------------------------------------------------------- | -| localId | number | No | ID of the target OS account. | -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, the account has been verified. If **false** is returned, the account has not been verified.| +| localId | number | Yes | ID of the target OS account. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means the OS account has been verified; the value **false** means the opposite.| **Error codes** @@ -572,7 +573,7 @@ Checks whether an OS account has been verified. This API uses a promise to retur | Type | Description | | ---------------------- | ----------------------------------------------------------------- | -| Promise<boolean> | Promise used to return the result. If **true** is returned, the account has been verified. If **false** is returned, the account has not been verified.| +| Promise<boolean> | Promise used to return the result. The value **true** means the OS account has been verified; the value **false** means the opposite.| **Error codes** @@ -814,7 +815,7 @@ Sets a name for an OS account. This API uses an asynchronous callback to return | Name | Type | Mandatory| Description | | :-------- | ------------------------- | ---- | ----------------------------------------------- | | localId | number | Yes | ID of the target OS account. | -| localName | string | Yes | Account name to set. The value cannot exceed 1024 characters. | +| localName | string | Yes | Account name. The value cannot exceed 1024 characters. | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| **Error codes** @@ -1918,7 +1919,7 @@ Obtains the type of the account to which the current process belongs. This API u getOsAccountType(): Promise<OsAccountType> -Obtains the type of the OS account to which the current process belongs. This API uses a promise to return the result. +Obtains the type of the account to which the current process belongs. This API uses a promise to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -2130,7 +2131,7 @@ Sets a profile photo for an OS account. This API uses an asynchronous callback t | -------- | ------------------------- | ---- | ------------ | | localId | number | Yes | ID of the target OS account.| | photo | string | Yes | Profile photo information. | -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object. | **Error codes** @@ -2381,7 +2382,7 @@ Obtains the SN of an OS account based on the account ID. This API uses a promise on(type: 'activate' | 'activating', name: string, callback: Callback<number>): void -Subscribes to OS account changes. This API uses a callback to return the result. +Subscribes to the OS account activation states, including the states of the account being activated and the account with activation completed. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -2393,9 +2394,9 @@ Subscribes to OS account changes. This API uses a callback to return the result. | Name | Type | Mandatory| Description | | -------- | -------------------------- | ---- | ------------------------------------------------------------ | -| type | 'activate' \| 'activating' | Yes | Type of the event to subscribe to. The value **activate** means an event indicating that an OS account is activated, and **activating** means an event indicating that an OS account is being activated.| +| type | 'activate' \| 'activating' | Yes | Type of the event to subscribe to. The value **activate** indicates an event reported when the OS account activation is complete, and **activating** indicates an event reported when OS account is being activated.| | name | string | Yes | Subscription name, which can be customized. The value cannot be empty or exceed 1024 bytes. | -| callback | Callback<number> | Yes | Callback invoked to return the OS account ID and status changes. | +| callback | Callback<number> | Yes | Callback invoked to return the ID of the OS account being activated or activated. | **Error codes** @@ -2423,7 +2424,7 @@ Subscribes to OS account changes. This API uses a callback to return the result. off(type: 'activate' | 'activating', name: string, callback?: Callback<number>): void -Unsubscribes from OS account changes. This API uses a callback to return the result. +Unsubscribes from the OS account activation states, including the states of the account being activated and the account with activation completed. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -2437,7 +2438,7 @@ Unsubscribes from OS account changes. This API uses a callback to return the res | -------- | -------------------------- | ---- | ------------------------------------------------------------ | | type | 'activate' \| 'activating' | Yes | Type of the event to unsubscribe from. The value **activate** means an event indicating that an OS account is activated, and **activating** means an event indicating that an OS account is being activated.| | name | string | Yes | Subscription name, which can be customized. The value cannot be empty or exceed 1024 bytes, and must be the same as the value passed by **on()**.| -| callback | Callback<number> | No | Callback for OS account changes. By default, **0** is returned. | +| callback | Callback<number> | No | Callback to unregister. By default, **0** is returned. | **Error codes** @@ -2708,7 +2709,6 @@ Obtains the constraint source information of an OS account. This API uses a prom console.info('queryOsAccountConstraintSourceType exception:' + JSON.stringify(e)); } ``` - ### isMultiOsAccountEnable(deprecated) isMultiOsAccountEnable(callback: AsyncCallback<boolean>): void @@ -2725,7 +2725,7 @@ Checks whether multiple OS accounts are supported. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ------------------------------------------------------ | -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, multiple OS accounts are supported. If **false** is returned, multiple OS accounts are not supported.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means multiple OS accounts are supported; the value false means the opposite.| **Example** @@ -2756,7 +2756,7 @@ Checks whether multiple OS accounts are supported. This API uses a promise to re | Type | Description | | :--------------------- | :--------------------------------------------------------- | -| Promise<boolean> | Promise used to return the result. If **true** is returned, multiple OS accounts are supported. If **false** is returned, multiple OS accounts are not supported.| +| Promise<boolean> | Promise used to return the result. The value **true** means multiple OS accounts are supported; the value false means the opposite.| **Example** @@ -2789,7 +2789,7 @@ Checks whether an OS account is activated. This API uses an asynchronous callbac | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ------------------------------------------------------ | | localId | number | Yes | ID of the target OS account. | -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, the account is activated. If **false** is returned, the account is not activated.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means the account is activated; the value **false** means the opposite.| **Example**: Check whether OS account 100 is activated. @@ -2829,7 +2829,7 @@ Checks whether an OS account is activated. This API uses a promise to return the | Type | Description | | --------------------- | ----------------------------------------------------------- | -| Promise<boolean> | Promise used to return the result. If **true** is returned, the account is activated. If **false** is returned, the account is not activated.| +| Promise<boolean> | Promise used to return the result. The value **true** means the account is activated; the value **false** means the opposite.| **Example**: Check whether OS account 100 is activated. @@ -2863,7 +2863,7 @@ Checks whether the specified constraint is enabled for an OS account. This API u | ---------- | ---------------------------- | ---- | ----------------------------------------------------------------- | | localId | number | Yes | ID of the target OS account. | | constraint | string | Yes | [Constraint](#constraints) to check. | -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, the constraint is enabled. If **false** is returned, the constraint is not enabled.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means the specified constraint is enabled; the value **false** means the opposite.| **Example**: Check whether OS account 100 is forbidden to use Wi-Fi. @@ -2905,7 +2905,7 @@ Checks whether the specified constraint is enabled for an OS account. This API u | Type | Description | | ---------------------- | --------------------------------------------------------------------- | -| Promise<boolean> | Promise used to return the result. If **true** is returned, the constraint is enabled. If **false** is returned, the constraint is not enabled.| +| Promise<boolean> | Promise used to return the result. The value **true** means the specified constraint is enabled; the value **false** means the opposite.| **Example**: Check whether OS account 100 is forbidden to use Wi-Fi. @@ -2936,7 +2936,7 @@ Checks whether this OS account is a test account. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | --------------------------------------------------------------------- | -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, the account is a test account. If **false** is returned, the account is not a test account.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means the account is a test account; the value **false** means the opposite.| **Example** @@ -2967,7 +2967,7 @@ Checks whether this OS account is a test account. This API uses a promise to ret | Type | Description | | ---------------------- | ------------------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the result. If **true** is returned, the account is a test account. If **false** is returned, the account is not a test account.| +| Promise<boolean> | Promise used to return the result. The value **true** means the account is a test account; the value **false** means the opposite.| **Example** @@ -2998,7 +2998,7 @@ Checks whether this OS account has been verified. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ------------------------------------------------------------- | -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, the account has been verified. If **false** is returned, the account has not been verified.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means the OS account has been verified; the value **false** means the opposite.| **Example** @@ -3031,8 +3031,8 @@ Checks whether an OS account has been verified. This API uses an asynchronous ca | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ------------------------------------------------------------- | -| localId | number | No | ID of the target OS account. | -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, the account has been verified. If **false** is returned, the account has not been verified.| +| localId | number | Yes | ID of the target OS account. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means the OS account has been verified; the value **false** means the opposite.| **Example** @@ -3072,7 +3072,7 @@ Checks whether an OS account has been verified. This API uses a promise to retur | Type | Description | | ---------------------- | ----------------------------------------------------------------- | -| Promise<boolean> | Promise used to return the result. If **true** is returned, the account has been verified. If **false** is returned, the account has not been verified.| +| Promise<boolean> | Promise used to return the result. The value **true** means the OS account has been verified; the value **false** means the opposite.| **Example** @@ -3337,7 +3337,7 @@ Obtains the OS account ID based on the domain account information. This API uses | Type | Description | | :-------------------- | :------------------------------------- | -| Promise<number> | Promise used to return the OS account ID obtained.| +| Promise<number> | Promise used to return the ID of the OS account associated with the domain account.| **Example** @@ -3985,7 +3985,7 @@ Obtains the executor property based on the request. This API uses a promise to r ### setProperty8+ -setProperty(request: SetPropertyRequest, callback: AsyncCallback<number>): void; +setProperty(request: SetPropertyRequest, callback: AsyncCallback<void>): void; Sets the property for the initialization algorithm. This API uses an asynchronous callback to return the result. @@ -4000,7 +4000,7 @@ Sets the property for the initialization algorithm. This API uses an asynchronou | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------- | ---- | ---------------------------------------------------------------------- | | request | [SetPropertyRequest](#setpropertyrequest8)| Yes | Request information, including the authentication credential type and the key value to set. | -| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is a [result code](#resultcode8). Otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| **Error codes** @@ -4018,9 +4018,12 @@ Sets the property for the initialization algorithm. This API uses an asynchronou setInfo: new Uint8Array([0]) }; try { - userAuth.setProperty(request, (err, result) => { - console.log('setProperty error = ' + JSON.stringify(err)); - console.log('setProperty result = ' + JSON.stringify(result)); + userAuth.setProperty(request, (err) => { + if (err) { + console.log('setProperty failed, error = ' + JSON.stringify(err)); + } else { + console.log('setProperty successfully'); + } }); } catch (e) { console.log('setProperty exception = ' + JSON.stringify(e)); @@ -4029,7 +4032,7 @@ Sets the property for the initialization algorithm. This API uses an asynchronou ### setProperty8+ -setProperty(request: SetPropertyRequest): Promise<number>; +setProperty(request: SetPropertyRequest): Promise<void>; Sets the property for the initialization algorithm. This API uses a promise to return the result. @@ -4049,7 +4052,7 @@ Sets the property for the initialization algorithm. This API uses a promise to r | Type | Description | | :-------------------- | :------------------------------------------------------------ | -| Promise<number> | Promise used to return the [result code](#resultcode8).| +| Promise<void> | Promise that returns no value.| **Error codes** @@ -4067,10 +4070,10 @@ Sets the property for the initialization algorithm. This API uses a promise to r setInfo: new Uint8Array([0]) }; try { - userAuth.setProperty(request).then((result) => { - console.log('setProperty result = ' + JSON.stringify(result)); + userAuth.setProperty(request).then(() => { + console.log('setProperty successfully'); }).catch((err) => { - console.log('setProperty error = ' + JSON.stringify(err)); + console.log('setProperty failed, error = ' + JSON.stringify(err)); }); } catch (e) { console.log('setProperty exception = ' + JSON.stringify(e)); @@ -4081,7 +4084,7 @@ Sets the property for the initialization algorithm. This API uses a promise to r auth(challenge: Uint8Array, authType: AuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array; -Performs authentication for the current user. This API uses a callback to return the result. +Performs authentication of the current user. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -4139,7 +4142,7 @@ Performs authentication for the current user. This API uses a callback to return authUser(userId: number, challenge: Uint8Array, authType: AuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array; -Performs authentication for a user. This API uses an asynchronous callback to return the result. +Performs authentication of the specified user. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -4277,17 +4280,12 @@ Register a PIN inputer. | ----------| ----------------------- | --- | -------------------------- | | inputer | [IInputer](#iinputer8) | Yes | PIN inputer, which is used to obtain the PIN.| -**Return value** - -| Type | Description | -| :------ | :-------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - **Error codes** | ID| Error Message | | -------- | --------------------------- | | 12300001 | System service exception. | +| 12300102 | Invalid inputer. | | 12300103 | Inputer already registered. | **Example** @@ -4296,8 +4294,8 @@ Register a PIN inputer. let password = new Uint8Array([0, 0, 0, 0, 0]); try { let result = pinAuth.registerInputer({ - onGetData: (pinSubType, callback) => { - callback.onSetData(pinSubType, password); + onGetData: (authSubType, callback) => { + callback.onSetData(authSubType, password); } }); console.log('registerInputer result = ' + result); @@ -4324,6 +4322,91 @@ Unregisters this PIN inputer. pinAuth.unregisterInputer(); ``` +### InputerManager 10+ + +Provides APIs for managing credential inputers. + +### registerInputer10+ + +registerInputer(authType: AuthType, inputer: IInputer): void; + +Register a credential inputer. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL or ohos.permission.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------| ----------------------- | --- | -------------------------- | +| authType | [AuthType](#authtype8) | Yes | Authentication credential type.| +| inputer | [IInputer](#iinputer8) | Yes | Credential inputer to register.| + +**Error codes** + +| ID| Error Message | +| -------- | --------------------------- | +| 12300001 | System service exception. | +| 12300102 | Invalid authType or inputer. | +| 12300103 | The credential inputer has been registered. | +| 12300106 | Unsupported authType. | + +**Example** + ```js + let inputerMgr = new account_osAccount.InputerManager(); + let authType = account_osAccount.AuthType.DOMAIN; + let password = new Uint8Array([0, 0, 0, 0, 0]); + try { + InputerMgr.registerInputer(authType, { + onGetData: (authSubType, callback) => { + callback.onSetData(authSubType, password); + } + }); + console.log('registerInputer success.'); + } catch (e) { + console.log('registerInputer exception = ' + JSON.stringify(e)); + } + ``` + +### unregisterInputer10+ + +unregisterInputer(authType: AuthType): void; + +Unregisters this credential inputer. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL or ohos.permission.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------| ----------------------- | --- | -------------------------- | +| authType | [AuthType](#authtype8) | Yes | Authentication credential type.| + +**Error codes** + +| ID| Error Message | +| -------- | --------------------------- | +| 12300002 | Invalid authType. | + +**Example** + ```js + let inputerMgr = new account_osAccount.InputerManager(); + let authType = account_osAccount.AuthType.DOMAIN; + try { + inputerMgr.unregisterInputer(authType); + console.log('unregisterInputer success.'); + } catch(err) { + console.log("unregisterInputer err:" + JSON.stringify(err)); + } + ``` + ## UserIdentityManager8+ Provides APIs for user identity management (IDM). @@ -4453,8 +4536,8 @@ Adds credential information, including the credential type, subtype, and token ( let password = new Uint8Array([0, 0, 0, 0, 0, 0]); let pinAuth = new account_osAccount.PINAuth(); pinAuth.registerInputer({ - onGetData: (pinSubType, callback) => { - callback.onSetData(pinSubType, password); + onGetData: (authSubType, callback) => { + callback.onSetData(authSubType, password); } }); let credentialInfo = { @@ -4467,12 +4550,12 @@ Adds credential information, including the credential type, subtype, and token ( try { userIDM.addCredential(credentialInfo, { onResult: (result, extraInfo) => { - console.log('updateCredential result = ' + result); - console.log('updateCredential extraInfo = ' + extraInfo); + console.log('addCredential result = ' + result); + console.log('addCredential extraInfo = ' + extraInfo); } }); } catch (e) { - console.log('updateCredential exception = ' + JSON.stringify(e)); + console.log('addCredential exception = ' + JSON.stringify(e)); } }); ``` @@ -4493,7 +4576,7 @@ Updates credential information. This API uses a callback to return the result. | Name | Type | Mandatory| Description | | --------------- | ------------------------------------- | --- | ------------------------- | -| credentialInfo | [CredentialInfo](#credentialinfo8) | Yes | New credential information. | +| credentialInfo | [CredentialInfo](#credentialinfo8) | Yes | New credential information. | | callback | [IIdmCallback](#iidmcallback8) | Yes | Callback invoked to return the new credential information.| **Error codes** @@ -4517,8 +4600,8 @@ Updates credential information. This API uses a callback to return the result. token: null }; pinAuth.registerInputer({ - onGetData: (pinSubType, callback) => { - callback.onSetData(pinSubType, password); + onGetData: (authSubType, callback) => { + callback.onSetData(authSubType, password); } }); userIDM.openSession((err, challenge) => { @@ -4701,7 +4784,7 @@ Obtains authentication information. This API uses an asynchronous callback to re | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------------------ | ---- | --------------------------------------------- | -| callback | AsyncCallback<Array<[EnrolledCredInfo](#enrolledcredinfo8)>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the credential information obtained. Otherwise, **err** is an error object.| +| callback | AsyncCallback<Array<[EnrolledCredInfo](#enrolledcredinfo8)>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is information about all registered credentials of the user. Otherwise, **err** is an error object.| **Error codes** @@ -4817,7 +4900,7 @@ Provides callbacks for PIN operations. ### onSetData8+ -onSetData: (pinSubType: AuthSubType, data: Uint8Array) => void; +onSetData: (authSubType: AuthSubType, data: Uint8Array) => void; **System API**: This is a system API. @@ -4829,7 +4912,7 @@ Called to set data in a PIN operation. | Name | Type | Mandatory| Description | | ---------- | ---------------------------------------- | ---- | ----------------------------------------------- | -| pinSubType | [AuthSubType](#authsubtype8) | Yes | Credential subtype. | +| authSubType | [AuthSubType](#authsubtype8) | Yes | Credential subtype. | | data | Uint8Array | Yes | Data (credential) to set. The data is used for authentication and operations for adding and modifying credentials.| **Example** @@ -4837,11 +4920,11 @@ Called to set data in a PIN operation. let password = new Uint8Array([0, 0, 0, 0, 0, 0]); let passwordNumber = new Uint8Array([1, 2, 3, 4]); let inputer = { - onGetData: (pinSubType, callback) => { - if (pinSubType == account_osAccount.AuthSubType.PIN_NUMBER) { - callback.onSetData(pinSubType, passwordNumber); + onGetData: (authSubType, callback) => { + if (authSubType == account_osAccount.AuthSubType.PIN_NUMBER) { + callback.onSetData(authSubType, passwordNumber); } else { - callback.onSetData(pinSubType, password); + callback.onSetData(authSubType, password); } } }; @@ -4849,13 +4932,13 @@ Called to set data in a PIN operation. ## IInputer8+ -Provides callbacks for the PIN input box. +Provides callbacks for credential inputers. **System API**: This is a system API. ### onGetData8+ -onGetData: (pinSubType: AuthSubType, callback: IInputData) => void; +onGetData: (authSubType: AuthSubType, callback: IInputData) => void; Called to obtain data. @@ -4874,11 +4957,11 @@ Called to obtain data. let password = new Uint8Array([0, 0, 0, 0, 0, 0]); let passwordNumber = new Uint8Array([1, 2, 3, 4]); let inputer = { - onGetData: (pinSubType, callback) => { - if (pinSubType == account_osAccount.AuthSubType.PIN_NUMBER) { - callback.onSetData(pinSubType, passwordNumber); + onGetData: (authSubType, callback) => { + if (authSubType == account_osAccount.AuthSubType.PIN_NUMBER) { + callback.onSetData(authSubType, passwordNumber); } else { - callback.onSetData(pinSubType, password); + callback.onSetData(authSubType, password); } } }; @@ -4974,7 +5057,7 @@ Called to return the result code and request result information. | Name | Type | Mandatory| Description | | --------- | --------------------------------------- | ---- | ----------------------- | | result | number | Yes | Authentication result code. | -| extraInfo | [AuthResult](#authresult8) | Yes | Specific information to be transferred.| +| extraInfo | [RequestResult](#requestresult8) | Yes | Specific information to be transferred.| **Example** ```js @@ -5124,7 +5207,7 @@ Enumerates the types of properties to obtain. **System capability**: SystemCapability.Account.OsAccount -| Name | Default Value| Description | +| Name | Value| Description | | ------------- | ------ | --------- | | AUTH_SUB_TYPE | 1 | Authentication credential subtype.| | REMAIN_TIMES | 2 | Remaining time. | @@ -5138,7 +5221,7 @@ Enumerates the types of properties to set. **System capability**: SystemCapability.Account.OsAccount -| Name | Default Value| Description | +| Name | Value| Description | | -------------- | ----- | ----------- | | INIT_ALGORITHM | 1 | Initialization algorithm.| @@ -5150,10 +5233,12 @@ Enumerates the authentication credential types. **System capability**: SystemCapability.Account.OsAccount -| Name | Default Value| Description | +| Name | Value| Description | | ----- | ----- | ---------------- | | PIN | 1 | PIN authentication.| | FACE | 2 | Facial authentication.| +| FINGERPRINT10+ | 4 | Fingerprint authentication.| +| DOMAIN10+ | 1024 | Domain authentication.| ## AuthSubType8+ @@ -5163,13 +5248,14 @@ Enumerates the authentication credential subtypes. **System capability**: SystemCapability.Account.OsAccount -| Name | Default Value| Description | +| Name | Value| Description | | ---------- | ----- | ------------------ | | PIN_SIX | 10000 | Six-digit PIN. | | PIN_NUMBER | 10001 | Custom PIN.| -| PIN_MIXED | 10002 | Custom mixed credential.| +| PIN_MIXED | 10002 | Custom mixed credentials.| | FACE_2D | 20000 | 2D face credential. | | FACE_3D | 20001 | 3D face credential. | +| DOMAIN_MIXED10+ | 10240001 | Mixed domain authentication credentials. | ## AuthTrustLevel8+ @@ -5179,7 +5265,7 @@ Enumerates the trust levels of the authentication result. **System capability**: SystemCapability.Account.OsAccount -| Name | Default Value| Description | +| Name | Value| Description | | ---- | ------ | ----------- | | ATL1 | 10000 | Trust level 1.| | ATL2 | 20000 | Trust level 2.| @@ -5194,7 +5280,7 @@ Enumerates the modules from which information is obtained. **System capability**: SystemCapability.Account.OsAccount -| Name | Default Value| Description | +| Name | Value| Description | | --------- | ------ | ------------------------ | | FACE_AUTH | 1 | Facial authentication module.| @@ -5206,7 +5292,7 @@ Enumerates the authentication result codes. **System capability**: SystemCapability.Account.OsAccount -| Name | Default Value| Description | +| Name | Value| Description | | ----------------------- | ----- | ---------------------------------------- | | SUCCESS | 0 | The authentication is successful or the authentication feature is supported. | | FAIL | 1 | The authentication executor failed to identify the user. | @@ -5228,7 +5314,7 @@ Enumerates the tip codes for facial authentication. **System capability**: SystemCapability.Account.OsAccount -| Name | Default Value| Description | +| Name | Value| Description | | ----------------------------- | ----- | ---------------------------------------- | | FACE_AUTH_TIP_TOO_BRIGHT | 1 | The obtained face image is too bright. | | FACE_AUTH_TIP_TOO_DARK | 2 | The obtained face image is too dark. | @@ -5250,7 +5336,7 @@ Enumerates the tip codes for fingerprint authentication. **System capability**: SystemCapability.Account.OsAccount -| Name | Default Value| Description | +| Name | Value| Description | | ----------------------------- | ----- | ----------------------------------------------- | | FINGERPRINT_TIP_GOOD | 0 | The captured image is clear. | | FINGERPRINT_TIP_IMAGER_DIRTY | 1 | The fingerprint image has big noise due to dirt on the sensor.| @@ -5381,10 +5467,9 @@ Enumerates the constraint sources. **System capability**: SystemCapability.Account.OsAccount -| Name | Default Value| Description | +| Name | Value| Description | | ------ | ------ | ------------ | | CONSTRAINT_NOT_EXIST | 0 | The constraint does not exist.| | CONSTRAINT_TYPE_BASE | 1 | Constraint from system settings. | | CONSTRAINT_TYPE_DEVICE_OWNER | 2 | Constraint from the device owners' settings. | | CONSTRAINT_TYPE_PROFILE_OWNER | 3 | Constraint from the profile owners' settings. | - diff --git a/en/application-dev/reference/apis/js-apis-rpc.md b/en/application-dev/reference/apis/js-apis-rpc.md index d1b4506837068ac88f3821befed6a673726fd327..94757432a9c16fa471fb98629b63387594542e65 100644 --- a/en/application-dev/reference/apis/js-apis-rpc.md +++ b/en/application-dev/reference/apis/js-apis-rpc.md @@ -1,326 +1,361 @@ -# RPC +# @ohos.rpc -The **RPC** module implements communication between processes, including inter-process communication (IPC) on a single device and Remote Procedure Call (RPC) between processes on difference devices. IPC is implemented based on the Binder driver, and RPC is based on the DSoftBus driver. +The **RPC** module implements communication between processes, including inter-process communication (IPC) on a single device and remote procedure call (RPC) between processes on difference devices. IPC is implemented based on the Binder driver, and RPC is based on the DSoftBus driver. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> This module supports return of error codes since API version 9. ## Modules to Import - ``` import rpc from '@ohos.rpc'; ``` -## MessageParcel +## ErrorCode9+ + +The APIs of this module return exceptions since API version 9. The following table lists the error codes. + +**System capability**: SystemCapability.Communication.IPC.Core + + | Name | Value | Description | + | ------------------------------------- | ------- | --------------------------------------------- | + | CHECK_PARAM_ERROR | 401 | Parameter check failed. | + | OS_MMAP_ERROR | 1900001 | Failed to call mmap. | + | OS_IOCTL_ERROR | 1900002 | Failed to call **ioctl** with the shared memory file descriptor.| + | WRITE_TO_ASHMEM_ERROR | 1900003 | Failed to write data to the shared memory. | + | READ_FROM_ASHMEM_ERROR | 1900004 | Failed to read data from the shared memory. | + | ONLY_PROXY_OBJECT_PERMITTED_ERROR | 1900005 | This operation is allowed only on the proxy object. | + | ONLY_REMOTE_OBJECT_PERMITTED_ERROR | 1900006 | This operation is allowed only on the remote object. | + | COMMUNICATION_ERROR | 1900007 | Failed to communicate with the remote object over IPC. | + | PROXY_OR_REMOTE_OBJECT_INVALID_ERROR | 1900008 | Invalid proxy or remote object. | + | WRITE_DATA_TO_MESSAGE_SEQUENCE_ERROR | 1900009 | Failed to write data to MessageSequence. | + | READ_DATA_FROM_MESSAGE_SEQUENCE_ERROR | 1900010 | Failed to read data from MessageSequence. | + | PARCEL_MEMORY_ALLOC_ERROR | 1900011 | Failed to allocate memory during serialization. | + | CALL_JS_METHOD_ERROR | 1900012 | Failed to invoke the JS callback. | + | OS_DUP_ERROR | 1900013 | Failed to call dup. | + -Provides APIs for reading and writing data in specific format. During RPC, the sender can use the **write()** method provided **MessageParcel** to write data to a **MessageParcel** object in specific format. The receiver can use the **read()** method provided by **MessageParcel** to read data in specific format from a **MessageParcel** object. The data formats include basic data types and arrays, IPC objects, interface tokens, and custom sequenceable objects. +## MessageSequence9+ + Provides APIs for reading and writing data in specific format. During RPC, the sender can use the **write()** method provided by **MessageSequence** to write data in specific format to a **MessageSequence** object. The receiver can use the **read()** method provided by **MessageSequence** to read data in specific format from a **MessageSequence** object. The data formats include basic data types and arrays, IPC objects, interface tokens, and custom sequenceable objects. ### create -create(): MessageParcel + create(): MessageSequence -Creates a **MessageParcel** object. This method is a static method. + Creates a **MessageSequence** object. This API is a static method. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | MessageParcel | **MessageParcel** object created.| + | Type | Description | + | --------------- | ------------------------------- | + | MessageSequence | **MessageSequence** object created.| **Example** ``` - let data = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); console.log("RpcClient: data is " + data); ``` - ### reclaim reclaim(): void -Reclaims the **MessageParcel** object that is no longer used. +Reclaims the **MessageSequence** object that is no longer used. **System capability**: SystemCapability.Communication.IPC.Core **Example** ``` - let reply = rpc.MessageParcel.create(); + let reply = rpc.MessageSequence.create(); reply.reclaim(); ``` - ### writeRemoteObject -writeRemoteObject(object: [IRemoteObject](#iremoteobject)): boolean +writeRemoteObject(object: [IRemoteObject](#iremoteobject)): void - Serializes a remote object and writes it to this **MessageParcel** object. +Serializes a remote object and writes it to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | object | [IRemoteObject](#iremoteobject) | Yes| Remote object to serialize and write to the **MessageParcel** object.| + | Name| Type | Mandatory| Description | + | ------ | ------------------------------- | ---- | ----------------------------------------- | + | object | [IRemoteObject](#iremoteobject) | Yes | Remote object to serialize and write to the **MessageSequence** object.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | -------- | ------- | + | 1900008 | proxy or remote object is invalid | + | 1900009 | write data to message sequence failed | **Example** ``` - class MyDeathRecipient { - onRemoteDied() { - console.log("server died"); - } - } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - isObjectDead(): boolean { - return false; - } } - let data = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); let testRemoteObject = new TestRemoteObject("testObject"); - data.writeRemoteObject(testRemoteObject); + try { + data.writeRemoteObject(testRemoteObject); + } catch(error) { + console.info("Rpc write remote object fail, errorCode " + error.code); + console.info("Rpc write remote object fail, errorMessage " + error.message); + } ``` - ### readRemoteObject readRemoteObject(): IRemoteObject -Reads the remote object from this **MessageParcel** object. You can use this method to deserialize the **MessageParcel** object to generate an **IRemoteObject**. The remote objects are read in the order in which they are written to this **MessageParcel** object. +Reads the remote object from **MessageSequence**. You can use this API to deserialize the **MessageSequence** object to generate an **IRemoteObject**. The remote object is read in the order in which it is written to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------------------- | ------------------ | | [IRemoteObject](#iremoteobject) | Remote object obtained.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900008 | proxy or remote object is invalid | + | 1900010 | read data from message sequence failed | + **Example** ``` - class MyDeathRecipient { - onRemoteDied() { - console.log("server died"); - } - } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - isObjectDead(): boolean { - return false; - } } - let data = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); let testRemoteObject = new TestRemoteObject("testObject"); - data.writeRemoteObject(testRemoteObject); - let proxy = data.readRemoteObject(); + try { + data.writeRemoteObject(testRemoteObject); + let proxy = data.readRemoteObject(); + } catch(error) { + console.info("Rpc write remote object fail, errorCode " + error.code); + console.info("Rpc write remote object fail, errorMessage " + error.message); + } ``` - ### writeInterfaceToken -writeInterfaceToken(token: string): boolean +writeInterfaceToken(token: string): void -Writes an interface token to this **MessageParcel** object. The remote object can use this interface token to verify the communication. +Writes an interface token to this **MessageSequence** object. The remote object can use this interface token to verify the communication. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | token | string | Yes| Interface token to write.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------ | + | token | string | Yes | Interface token to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeInterfaceToken("aaa"); - console.log("RpcServer: writeInterfaceToken is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeInterfaceToken("aaa"); + } catch(error) { + console.info("rpc write interface fail, errorCode " + error.code); + console.info("rpc write interface fail, errorMessage " + error.message); + } ``` - ### readInterfaceToken readInterfaceToken(): string -Reads the interface token from this **MessageParcel** object. The interface token is read in the sequence in which it is written to the **MessageParcel** object. The local object can use it to verify the communication. +Reads the interface token from this **MessageSequence** object. The interface token is read in the sequence in which it is written to the **MessageSequence** object. The local object can use it to verify the communication. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ------------------------ | | string | Interface token obtained.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ----- | + | 1900010 | read data from message sequence failed | + + **Example** ``` class Stub extends rpc.RemoteObject { onRemoteRequest(code, data, reply, option) { - let interfaceToken = data.readInterfaceToken(); - console.log("RpcServer: interfaceToken is " + interfaceToken); + try { + let interfaceToken = data.readInterfaceToken(); + console.log("RpcServer: interfaceToken is " + interfaceToken); + } catch(error) { + console.info("RpcServer: read interfaceToken failed, errorCode " + error.code); + console.info("RpcServer: read interfaceToken failed, errorMessage " + error.message); + } return true; } } ``` - ### getSize getSize(): number -Obtains the data size of this **MessageParcel** object. +Obtains the data size of this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | number | Size of the **MessageParcel** object obtained, in bytes.| + | Type | Description | + | ------ | ----------------------------------------------- | + | number | Size of the **MessageSequence** object obtained, in bytes.| **Example** ``` - let data = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); let size = data.getSize(); console.log("RpcClient: size is " + size); ``` - ### getCapacity getCapacity(): number -Obtains the capacity of this **MessageParcel** object. +Obtains the capacity of this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | number | **MessageParcel** capacity obtained, in bytes.| + | Type | Description| + | ------ | ----- | + | number | **MessageSequence** capacity obtained, in bytes.| **Example** ``` - let data = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); let result = data.getCapacity(); console.log("RpcClient: capacity is " + result); ``` - ### setSize -setSize(size: number): boolean +setSize(size: number): void -Sets the size of data contained in this **MessageParcel** object. +Sets the size of data contained in this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | + | Name| Type | Mandatory| Description| + | ------ | ------ | ---- | ------ | | size | number | Yes| Data size to set, in bytes.| -**Return value** - - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - **Example** ``` - let data = rpc.MessageParcel.create(); - let setSize = data.setSize(16); - console.log("RpcClient: setSize is " + setSize); + let data = rpc.MessageSequence.create(); + try { + data.setSize(16); + console.log("RpcClient: setSize is " + data.getSize()); + } catch(error) { + console.info("rpc set size of MessageSequence fail, errorCode " + error.code); + console.info("rpc set size of MessageSequence fail, errorMessage " + error.message); + } ``` - ### setCapacity -setCapacity(size: number): boolean +setCapacity(size: number): void -Sets the storage capacity of this **MessageParcel** object. +Sets the storage capacity of this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | size | number | Yes| Storage capacity to set, in bytes.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | --------------------------------------------- | + | size | number | Yes | Storage capacity of the **MessageSequence** object to set, in bytes.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | -------- | ------ | + | 1900011 | parcel memory alloc failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.setCapacity(100); - console.log("RpcClient: setCapacity is " + result); + let data = rpc.MessageSequence.create(); + try { + data.setCapacity(100); + console.log("RpcClient: setCapacity is " + data.getCapacity()); + } catch(error) { + console.info("rpc memory alloc fail, errorCode " + error.code); + console.info("rpc memory alloc fail, errorMessage " + error.message); + } ``` - ### getWritableBytes getWritableBytes(): number -Obtains the writable capacity of this **MessageParcel** object. +Obtains the writable capacity of this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** | Type| Description| - | -------- | -------- | - | number | **MessageParcel** writable capacity obtained, in bytes.| + | ------ | ------ | + | number | **MessageSequence** writable capacity obtained, in bytes.| **Example** @@ -334,20 +369,19 @@ Obtains the writable capacity of this **MessageParcel** object. } ``` - ### getReadableBytes getReadableBytes(): number -Obtains the readable capacity of this **MessageParcel** object. +Obtains the readable capacity of this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** | Type| Description| - | -------- | -------- | - | number | **MessageParcel** object readable capacity, in bytes.| + | ------ | ------- | + | number | **MessageSequence** readable capacity obtained, in bytes.| **Example** @@ -361,57 +395,54 @@ Obtains the readable capacity of this **MessageParcel** object. } ``` - ### getReadPosition getReadPosition(): number -Obtains the read position of this **MessageParcel** object. +Obtains the read position of this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** | Type| Description| - | -------- | -------- | - | number | Current read position of the **MessageParcel** object.| + | ------ | ------ | + | number | Read position obtained.| **Example** ``` - let data = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); let readPos = data.getReadPosition(); console.log("RpcClient: readPos is " + readPos); ``` - ### getWritePosition getWritePosition(): number -Obtains the write position of this **MessageParcel** object. +Obtains the write position of this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** | Type| Description| - | -------- | -------- | - | number | Current write position of the **MessageParcel** object.| + | ------ | ----- | + | number | Write position obtained.| **Example** ``` - let data = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); data.writeInt(10); let bwPos = data.getWritePosition(); console.log("RpcClient: bwPos is " + bwPos); ``` - ### rewindRead -rewindRead(pos: number): boolean +rewindRead(pos: number): void Moves the read pointer to the specified position. @@ -420,32 +451,30 @@ Moves the read pointer to the specified position. **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | pos | number | Yes| Position from which data is to read.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the read position changes; returns **false** otherwise.| + | ------ | ------ | ---- | ------- | + | pos | number | Yes | Position from which data is to read.| **Example** ``` - let data = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); data.writeInt(12); - data.writeString("parcel"); + data.writeString("sequence"); let number = data.readInt(); console.log("RpcClient: number is " + number); - data.rewindRead(0); + try { + data.rewindRead(0); + } catch(error) { + console.info("rpc rewind read data fail, errorCode " + error.code); + console.info("rpc rewind read data fail, errorMessage " + error.message); + } let number2 = data.readInt(); console.log("RpcClient: rewindRead is " + number2); ``` - ### rewindWrite -rewindWrite(pos: number): boolean +rewindWrite(pos: number): void Moves the write pointer to the specified position. @@ -454,532 +483,721 @@ Moves the write pointer to the specified position. **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | pos | number | Yes| Position from which data is to write.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the write position changes; returns **false** otherwise.| + | ------ | ------ | ---- | ----- | + | pos | number | Yes | Position from which data is to write.| **Example** ``` - let data = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); data.writeInt(4); - data.rewindWrite(0); + try { + data.rewindWrite(0); + } catch(error) { + console.info("rpc rewind read data fail, errorCode " + error.code); + console.info("rpc rewind read data fail, errorMessage " + error.message); + } data.writeInt(5); let number = data.readInt(); console.log("RpcClient: rewindWrite is: " + number); ``` - ### writeByte -writeByte(val: number): boolean +writeByte(val: number): void -Writes a Byte value to this **MessageParcel** object. +Writes a byte value to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | + | Name| Type | Mandatory| Description| + | ----- | ------ | ---- | ----- | | val | number | Yes| Byte value to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | -------- | ------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeByte(2); - console.log("RpcClient: writeByte is: " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeByte(2); + } catch(error) { + console.info("rpc write byte fail, errorCode " + error.code); + console.info("rpc write byte fail, errorMessage" + error.message); + } ``` - ### readByte readByte(): number -Reads the Byte value from this **MessageParcel** object. +Reads the byte value from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description| + | ------ | ----- | | number | Byte value read.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | + **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeByte(2); - console.log("RpcClient: writeByte is: " + result); - let ret = data.readByte(); - console.log("RpcClient: readByte is: " + ret); + let data = rpc.MessageSequence.create(); + try { + data.writeByte(2); + } catch(error) { + console.info("rpc write byte fail, errorCode " + error.code); + console.info("rpc write byte fail, errorMessage" + error.message); + } + try { + let ret = data.readByte(); + console.log("RpcClient: readByte is: " + ret); + } catch(error) { + console.info("rpc write byte fail, errorCode " + error.code); + console.info("rpc write byte fail, errorMessage" + error.message); + } ``` - ### writeShort -writeShort(val: number): boolean +writeShort(val: number): void -Writes a Short int value to this **MessageParcel** object. +Writes a short integer to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | val | number | Yes| Short int value to write.| + | Name| Type | Mandatory| Description| + | ------ | ------ | --- | --- | + | val | number | Yes| Short integer to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ------ | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeShort(8); - console.log("RpcClient: writeShort is: " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeShort(8); + } catch(error) { + console.info("rpc write short fail, errorCode " + error.code); + console.info("rpc write short fail, errorMessage" + error.message); + } ``` - ### readShort readShort(): number -Reads the Short int value from this **MessageParcel** object. +Reads the short integer from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | number | Short int value read.| + | Type | Description | + | ------ | -------------- | + | number | Short integer read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeShort(8); - console.log("RpcClient: writeShort is: " + result); - let ret = data.readShort(); - console.log("RpcClient: readShort is: " + ret); + let data = rpc.MessageSequence.create(); + try { + data.writeShort(8); + } catch(error) { + console.info("rpc write short fail, errorCode " + error.code); + console.info("rpc write short fail, errorMessage" + error.message); + } + try { + let ret = data.readShort(8); + } catch(error) { + console.info("rpc read short fail, errorCode " + error.code); + console.info("rpc read short fail, errorMessage" + error.message); + } + console.log("RpcClient: readByte is: " + ret); ``` - ### writeInt -writeInt(val: number): boolean +writeInt(val: number): void -Writes an Int value to this **MessageParcel** object. +Writes an integer to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | val | number | Yes| Int value to write.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ---------------- | + | val | number | Yes | Integer to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | -------- | ------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeInt(10); - console.log("RpcClient: writeInt is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeInt(10); + } catch(error) { + console.info("rpc write int fail, errorCode " + error.code); + console.info("rpc write int fail, errorMessage" + error.message); + } ``` - ### readInt readInt(): number -Reads the Int value from this **MessageParcel** object. +Reads the integer from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | number | Int value read.| + | Type | Description | + | ------ | ------------ | + | number | Integer read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeInt(10); - console.log("RpcClient: writeInt is " + result); - let ret = data.readInt(); - console.log("RpcClient: readInt is " + ret); + let data = rpc.MessageSequence.create(); + try { + data.writeInt(10); + } catch(error) { + console.info("rpc write int fail, errorCode " + error.code); + console.info("rpc write int fail, errorMessage" + error.message); + } + try { + let ret = data.readInt(); + console.log("RpcClient: readInt is " + ret); + } catch(error) { + console.info("rpc read int fail, errorCode " + error.code); + console.info("rpc read int fail, errorMessage" + error.message); + } ``` - ### writeLong -writeLong(val: number): boolean +writeLong(val: number): void -Writes a Long int value to this **MessageParcel** object. +Writes a long integer to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | val | number | Yes| Long int value to write.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ---------------- | + | val | number | Yes | Long integer to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeLong(10000); - console.log("RpcClient: writeLong is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeLong(10000); + } catch(error) { + console.info("rpc write long fail, errorCode " + error.code); + console.info("rpc write long fail, errorMessage" + error.message); + } ``` - ### readLong readLong(): number -Reads the Long int value from this **MessageParcel** object. +Reads the long integer from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | number | Long int value read.| + | Type | Description | + | ------ | -------------- | + | number | Long integer read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeLong(10000); - console.log("RpcClient: writeLong is " + result); - let ret = data.readLong(); - console.log("RpcClient: readLong is " + ret); + let data = rpc.MessageSequence.create(); + try { + data.writeLong(10000); + } catch(error) { + console.info("rpc write long fail, errorCode " + error.code); + console.info("rpc write long fail, errorMessage" + error.message); + } + try { + let ret = data.readLong(); + console.log("RpcClient: readLong is " + ret); + } catch(error) { + console.info("rpc read long fail, errorCode " + error.code); + console.info("rpc read long fail, errorMessage" + error.message); + } ``` - ### writeFloat -writeFloat(val: number): boolean +writeFloat(val: number): void -Writes a Float value to this **MessageParcel** object. +Writes a floating-point number to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | val | number | Yes| Float value to write.| + | ----- | ---- | ---- | ----- | + | val | number | Yes| Floating-point number to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeFloat(1.2); - console.log("RpcClient: writeFloat is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeFloat(1.2); + } catch(error) { + console.info("rpc write float fail, errorCode " + error.code); + console.info("rpc write float fail, errorMessage" + error.message); + } ``` - ### readFloat readFloat(): number -Reads the Float value from this **MessageParcel** object. +Reads the floating-pointer number from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | number | Float value read.| + | Type | Description | + | ------ | ------------ | + | number | Floating-point number read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeFloat(1.2); - console.log("RpcClient: writeFloat is " + result); - let ret = data.readFloat(); - console.log("RpcClient: readFloat is " + ret); + let data = rpc.MessageSequence.create(); + try { + data.writeFloat(1.2); + } catch(error) { + console.info("rpc write float fail, errorCode " + error.code); + console.info("rpc write float fail, errorMessage" + error.message); + } + try { + let ret = data.readFloat(); + console.log("RpcClient: readFloat is " + ret); + } catch(error) { + console.info("rpc read float fail, errorCode " + error.code); + console.info("rpc read float fail, errorMessage" + error.message); + } ``` - ### writeDouble -writeDouble(val: number): boolean +writeDouble(val: number): void -Writes a Double value to this **MessageParcel** object. +Writes a double-precision floating-point number to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | val | number | Yes| Double value to write.| + | ------ | ------ | ---- | ------ | + | val number | Yes| Double-precision floating-point number to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeDouble(10.2); - console.log("RpcClient: writeDouble is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeDouble(10.2); + } catch(error) { + console.info("rpc read float fail, errorCode " + error.code); + console.info("rpc read float fail, errorMessage" + error.message); + } ``` - ### readDouble readDouble(): number -Reads the Double value from this **MessageParcel** object. +Reads the double-precision floating-point number from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | number | Double value read.| + | Type | Description | + | ------ | ------------------ | + | number | Double-precision floating-point number read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeDouble(10.2); - console.log("RpcClient: writeDouble is " + result); - let ret = data.readDouble(); - console.log("RpcClient: readDouble is " + ret); + let data = rpc.MessageSequence.create(); + try { + data.writeDouble(10.2); + } catch(error) { + console.info("rpc write double fail, errorCode " + error.code); + console.info("rpc write double fail, errorMessage" + error.message); + } + try { + let ret = data.readDouble(); + console.log("RpcClient: readDouble is " + ret); + } catch(error) { + console.info("rpc read double fail, errorCode " + error.code); + console.info("rpc read double fail, errorMessage" + error.message); + } ``` - ### writeBoolean -writeBoolean(val: boolean): boolean +writeBoolean(val: boolean): void -Writes a Boolean value to this **MessageParcel** object. +Writes a Boolean value to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | val | boolean | Yes| Boolean value to write.| + | Name| Type | Mandatory| Description | + | ------ | ------- | ---- | ---------------- | + | val | boolean | Yes | Boolean value to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeBoolean(false); - console.log("RpcClient: writeBoolean is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeBoolean(false); + } catch(error) { + console.info("rpc write boolean fail, errorCode " + error.code); + console.info("rpc write boolean fail, errorMessage" + error.message); + } ``` - ### readBoolean readBoolean(): boolean -Reads the Boolean value from this **MessageParcel** object. +Reads the Boolean value from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | -------------------- | | boolean | Boolean value read.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | -------- | ------- | + | 1900010 | read data from message sequence failed | + **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeBoolean(false); - console.log("RpcClient: writeBoolean is " + result); - let ret = data.readBoolean(); - console.log("RpcClient: readBoolean is " + ret); + let data = rpc.MessageSequence.create(); + try { + data.writeBoolean(false); + } catch(error) { + console.info("rpc write boolean fail, errorCode " + error.code); + console.info("rpc write boolean fail, errorMessage" + error.message); + } + try { + let ret = data.readBoolean(); + console.log("RpcClient: readBoolean is " + ret); + } catch(error) { + console.info("rpc read boolean fail, errorCode " + error.code); + console.info("rpc read boolean fail, errorMessage" + error.message); + } ``` - ### writeChar -writeChar(val: number): boolean +writeChar(val: number): void -Writes a Char value to this **MessageParcel** object. +Writes a character to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | val | number | Yes| Char value to write.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | -------------------- | + | val | number | Yes | Single character to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeChar(97); - console.log("RpcClient: writeChar is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeChar(97); + } catch(error) { + console.info("rpc write char fail, errorCode " + error.code); + console.info("rpc write char fail, errorMessage" + error.message); + } ``` - ### readChar readChar(): number -Reads the Char value from this **MessageParcel** object. +Reads the character from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | number | Char value read.| + | Type | Description| + | ------ | ---- | + | number | Character read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------ | --------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeChar(97); - console.log("RpcClient: writeChar is " + result); - let ret = data.readChar(); - console.log("RpcClient: readChar is " + ret); + let data = rpc.MessageSequence.create(); + try { + data.writeChar(97); + } catch(error) { + console.info("rpc write char fail, errorCode " + error.code); + console.info("rpc write char fail, errorMessage" + error.message); + } + try { + let ret = data.readChar(); + console.log("RpcClient: readChar is " + ret); + } catch(error) { + console.info("rpc read char fail, errorCode " + error.code); + console.info("rpc read char fail, errorMessage" + error.message); + } ``` - ### writeString -writeString(val: string): boolean +writeString(val: string): void -Writes a string to this **MessageParcel** object. +Writes a string to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | val | string | Yes| String to write. The length of the string must be less than 40960 bytes.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ----------------------------------------- | + | val | string | Yes | String to write. The length of the string must be less than 40960 bytes.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeString('abc'); - console.log("RpcClient: writeString is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeString('abc'); + } catch(error) { + console.info("rpc write string fail, errorCode " + error.code); + console.info("rpc write string fail, errorMessage" + error.message); + } ``` - ### readString readString(): string -Reads a string from this **MessageParcel** object. +Reads the string from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | -------------- | | string | String read.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | + **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeString('abc'); - console.log("RpcClient: writeString is " + result); - let ret = data.readString(); - console.log("RpcClient: readString is " + ret); + let data = rpc.MessageSequence.create(); + try { + data.writeString('abc'); + } catch(error) { + console.info("rpc write string fail, errorCode " + error.code); + console.info("rpc write string fail, errorMessage" + error.message); + } + try { + let ret = data.readString(); + console.log("RpcClient: readString is " + ret); + } catch(error) { + console.info("rpc read string fail, errorCode " + error.code); + console.info("rpc read string fail, errorMessage" + error.message); + } ``` +### writeParcelable -### writeSequenceable - -writeSequenceable(val: Sequenceable): boolean +writeParcelable(val: Parcelable): void -Writes a sequenceable object to this **MessageParcel** object. +Writes a **Parcelable** object to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | val | [Sequenceable](#sequenceable) | Yes| Sequenceable object to write.| + | ------ | --------- | ---- | ------ | + | val | Parcelable | Yes | **Parcelable** object to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900009 | write data to message sequence failed | **Example** @@ -991,43 +1209,49 @@ Writes a sequenceable object to this **MessageParcel** object. this.num = num; this.str = str; } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); return true; } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); return true; } } - let sequenceable = new MySequenceable(1, "aaa"); - let data = rpc.MessageParcel.create(); - let result = data.writeSequenceable(sequenceable); - console.log("RpcClient: writeSequenceable is " + result); + let parcelable = new MySequenceable(1, "aaa"); + let data = rpc.MessageSequence.create(); + try { + data.writeParcelable(parcelable); + } catch(error) { + console.info("rpc write parcelable fail, errorCode " + error.code); + console.info("rpc write parcelable fail, errorMessage" + error.message); + } ``` +### readParcelable -### readSequenceable - -readSequenceable(dataIn: Sequenceable) : boolean +readParcelable(dataIn: Parcelable): void -Reads member variables from this **MessageParcel** object. +Reads a **Parcelable** object from this **MessageSequence** object to the specified object (**dataIn**). **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataIn | [Sequenceable](#sequenceable) | Yes| Object that reads member variables from the **MessageParcel** object.| + | Name| Type | Mandatory| Description | + | ------ | ------------------------- | ---- | ----------------------------------------- | + | dataIn | Parcelable | Yes | **Parcelable** object to read.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | -------- | ------- | + | 1900010 | read data from message sequence failed | + | 1900012 | call js callback function failed | **Example** @@ -1039,774 +1263,1110 @@ Reads member variables from this **MessageParcel** object. this.num = num; this.str = str; } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); return true; } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); return true; } } - let sequenceable = new MySequenceable(1, "aaa"); - let data = rpc.MessageParcel.create(); - let result = data.writeSequenceable(sequenceable); - console.log("RpcClient: writeSequenceable is " + result); + let parcelable = new MySequenceable(1, "aaa"); + let data = rpc.MessageSequence.create(); + data.writeParcelable(parcelable); let ret = new MySequenceable(0, ""); - let result2 = data.readSequenceable(ret); - console.log("RpcClient: writeSequenceable is " + result2); + try { + data.readParcelable(ret); + }catch(error) { + console.info("rpc read parcelable fail, errorCode " + error.code); + console.info("rpc read parcelable fail, errorMessage" + error.message); + } ``` - ### writeByteArray -writeByteArray(byteArray: number[]): boolean +writeByteArray(byteArray: number[]): void -Writes a byte array to this **MessageParcel** object. +Writes a byte array to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | byteArray | number[] | Yes| Byte array to write.| + | Name | Type | Mandatory| Description | + | --------- | -------- | ---- | ------------------ | + | byteArray | number[] | Yes | Byte array to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); let ByteArrayVar = [1, 2, 3, 4, 5]; - let result = data.writeByteArray(ByteArrayVar); - console.log("RpcClient: writeByteArray is " + result); + try { + data.writeByteArray(ByteArrayVar); + } catch(error) { + console.info("rpc write byteArray fail, errorCode " + error.code); + console.info("rpc write byteArray fail, errorMessage" + error.message); + } ``` - ### readByteArray -readByteArray(dataIn: number[]) : void +readByteArray(dataIn: number[]): void -Reads a byte array from this **MessageParcel** object. +Reads a byte array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataIn | number[] | Yes| Byte array to read.| + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | ------------------ | + | dataIn | number[] | Yes | Byte array to read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); let ByteArrayVar = [1, 2, 3, 4, 5]; - let result = data.writeByteArray(ByteArrayVar); - console.log("RpcClient: writeByteArray is " + result); - let array = new Array(5); - data.readByteArray(array); + try { + data.writeByteArray(ByteArrayVar); + } catch(error) { + console.info("rpc write byteArray fail, errorCode " + error.code); + console.info("rpc write byteArray fail, errorMessage" + error.message); + } + try { + let array = new Array(5); + data.readByteArray(array); + } catch(error) { + console.info("rpc write byteArray fail, errorCode " + error.code); + console.info("rpc write byteArray fail, errorMessage" + error.message); + } ``` - ### readByteArray readByteArray(): number[] -Reads the byte array from this **MessageParcel** object. +Reads the byte array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | -------- | -------------- | | number[] | Byte array read.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | -------- | ------- | + | 1900010 | read data from message sequence failed | + **Example** ``` - let data = rpc.MessageParcel.create(); - let ByteArrayVar = [1, 2, 3, 4, 5]; - let result = data.writeByteArray(ByteArrayVar); - console.log("RpcClient: writeByteArray is " + result); - let array = data.readByteArray(); - console.log("RpcClient: readByteArray is " + array); + let data = rpc.MessageSequence.create(); + let byteArrayVar = [1, 2, 3, 4, 5]; + try { + data.writeByteArray(byteArrayVar); + } catch(error) { + console.info("rpc write byteArray fail, errorCode " + error.code); + console.info("rpc write byteArray fail, errorMessage" + error.message); + } + try { + let array = data.readByteArray(); + console.log("RpcClient: readByteArray is " + array); + } catch(error) { + console.info("rpc read byteArray fail, errorCode " + error.code); + console.info("rpc read byteArray fail, errorMessage" + error.message); + } ``` - ### writeShortArray -writeShortArray(shortArray: number[]): boolean +writeShortArray(shortArray: number[]): void -Writes a short array to this **MessageParcel** object. +Writes a short array to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | shortArray | number[] | Yes| Short array to write.| + | Name | Type | Mandatory| Description | + | ---------- | -------- | ---- | -------------------- | + | shortArray | number[] | Yes | Short array to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ----- | ----- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeShortArray([11, 12, 13]); - console.log("RpcClient: writeShortArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeShortArray([11, 12, 13]); + } catch(error) { + console.info("rpc read byteArray fail, errorCode " + error.code); + console.info("rpc read byteArray fail, errorMessage" + error.message); + } ``` - ### readShortArray -readShortArray(dataIn: number[]) : void +readShortArray(dataIn: number[]): void -Reads a short array from this **MessageParcel** object. +Reads a short array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataIn | number[] | Yes| Short array to read.| + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | -------------------- | + | dataIn | number[] | Yes | Short array to read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------ | ------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeShortArray([11, 12, 13]); - console.log("RpcClient: writeShortArray is " + result); - let array = new Array(3); - data.readShortArray(array); + let data = rpc.MessageSequence.create(); + try { + data.writeShortArray([11, 12, 13]); + } catch(error) { + console.info("rpc write shortArray fail, errorCode " + error.code); + console.info("rpc write shortArray fail, errorMessage" + error.message); + } + try { + let array = new Array(3); + data.readShortArray(array); + } catch(error) { + console.info("rpc read shortArray fail, errorCode " + error.code); + console.info("rpc read shortArray fail, errorMessage" + error.message); + } ``` - ### readShortArray readShortArray(): number[] -Reads the short array from this **MessageParcel** object. +Reads the short array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | -------- | ---------------- | | number[] | Short array read.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | -------- | ------- | + | 1900010 | read data from message sequence failed | + **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeShortArray([11, 12, 13]); - console.log("RpcClient: writeShortArray is " + result); - let array = data.readShortArray(); - console.log("RpcClient: readShortArray is " + array); + let data = rpc.MessageSequence.create(); + try { + data.writeShortArray([11, 12, 13]); + } catch(error) { + console.info("rpc write shortArray fail, errorCode " + error.code); + console.info("rpc write shortArray fail, errorMessage" + error.message); + } + try { + let array = data.readShortArray(); + console.log("RpcClient: readShortArray is " + array); + } catch(error) { + console.info("rpc read shortArray fail, errorCode " + error.code); + console.info("rpc read shortArray fail, errorMessage" + error.message); + } ``` - ### writeIntArray -writeIntArray(intArray: number[]): boolean +writeIntArray(intArray: number[]): void -Writes an integer array to this **MessageParcel** object. +Writes an integer array to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | intArray | number[] | Yes| Integer array to write.| + | Name | Type | Mandatory| Description | + | -------- | -------- | ---- | ------------------ | + | intArray | number[] | Yes | Integer array to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ----- | --------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeIntArray([100, 111, 112]); - console.log("RpcClient: writeIntArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeIntArray([100, 111, 112]); + } catch(error) { + console.info("rpc write intArray fail, errorCode " + error.code); + console.info("rpc write intArray fail, errorMessage" + error.message); + } ``` - ### readIntArray -readIntArray(dataIn: number[]) : void +readIntArray(dataIn: number[]): void -Reads an integer array from this **MessageParcel** object. +Reads an integer array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataIn | number[] | Yes| Integer array to read.| + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | ------------------ | + | dataIn | number[] | Yes | Integer array to read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeIntArray([100, 111, 112]); - console.log("RpcClient: writeIntArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeIntArray([100, 111, 112]); + } catch(error) { + console.info("rpc write intArray fail, errorCode " + error.code); + console.info("rpc write intArray fail, errorMessage" + error.message); + } let array = new Array(3); - data.readIntArray(array); + try { + data.readIntArray(array); + } catch(error) { + console.info("rpc read intArray fail, errorCode " + error.code); + console.info("rpc read intArray fail, errorMessage" + error.message); + } ``` - ### readIntArray readIntArray(): number[] -Reads the integer array from this **MessageParcel** object. +Reads the integer array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | -------- | -------------- | | number[] | Integer array read.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ----- | ------- | + | 1900010 | read data from message sequence failed | + **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeIntArray([100, 111, 112]); - console.log("RpcClient: writeIntArray is " + result); - let array = data.readIntArray(); - console.log("RpcClient: readIntArray is " + array); + let data = rpc.MessageSequence.create(); + try { + data.writeIntArray([100, 111, 112]); + } catch(error) { + console.info("rpc write intArray fail, errorCode " + error.code); + console.info("rpc write intArray fail, errorMessage" + error.message); + } + try { + let array = data.readIntArray(); + console.log("RpcClient: readIntArray is " + array); + } catch(error) { + console.info("rpc read intArray fail, errorCode " + error.code); + console.info("rpc read intArray fail, errorMessage" + error.message); + } ``` - ### writeLongArray -writeLongArray(longArray: number[]): boolean +writeLongArray(longArray: number[]): void -Writes a long array to this **MessageParcel** object. +Writes a long array to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | longArray | number[] | Yes| Long array to write.| + | Name | Type | Mandatory| Description | + | --------- | -------- | ---- | -------------------- | + | longArray | number[] | Yes | Long array to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ----- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeLongArray([1111, 1112, 1113]); - console.log("RpcClient: writeLongArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeLongArray([1111, 1112, 1113]); + }catch(error){ + console.info("rpc write longArray fail, errorCode " + error.code); + console.info("rpc write longArray fail, errorMessage" + error.message); + } ``` - ### readLongArray -readLongArray(dataIn: number[]) : void +readLongArray(dataIn: number[]): void -Reads a long array from this **MessageParcel** object. +Reads a long array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataIn | number[] | Yes| Long array to read.| + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | -------------------- | + | dataIn | number[] | Yes | Long array to read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ------ | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeLongArray([1111, 1112, 1113]); - console.log("RpcClient: writeLongArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeLongArray([1111, 1112, 1113]); + } catch(error) { + console.info("rpc write longArray fail, errorCode " + error.code); + console.info("rpc write longArray fail, errorMessage" + error.message); + } let array = new Array(3); - data.readLongArray(array); + try { + data.readLongArray(array); + } catch(error) { + console.info("rpc read longArray fail, errorCode " + error.code); + console.info("rpc read longArray fail, errorMessage" + error.message); + } ``` - ### readLongArray readLongArray(): number[] -Reads the long array from this **MessageParcel** object. +Reads the long array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | -------- | ---------------- | | number[] | Long array read.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | + **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeLongArray([1111, 1112, 1113]); - console.log("RpcClient: writeLongArray is " + result); - let array = data.readLongArray(); - console.log("RpcClient: readLongArray is " + array); + let data = rpc.MessageSequence.create(); + try { + data.writeLongArray([1111, 1112, 1113]); + } catch(error) { + console.info("rpc write longArray fail, errorCode " + error.code); + console.info("rpc write longArray fail, errorMessage" + error.message); + } + try { + let array = data.readLongArray(); + console.log("RpcClient: readLongArray is " + array); + } catch(error) { + console.info("rpc read longArray fail, errorCode " + error.code); + console.info("rpc read longArray fail, errorMessage" + error.message); + } ``` - ### writeFloatArray -writeFloatArray(floatArray: number[]): boolean +writeFloatArray(floatArray: number[]): void -Writes a FloatArray to this **MessageParcel** object. +Writes a floating-point array to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | floatArray | number[] | Yes| FloatArray to write. The system processes Float data as that of the Double type. Therefore, the total number of bytes occupied by a FloatArray must be calculated as the Double type.| + | Name | Type | Mandatory| Description | + | ---------- | -------- | ---- | ----------------------------------------------------------------------------------------------------------------------- | + | floatArray | number[] | Yes | Floating-point array to write. The system processes Float data as that of the Double type. Therefore, the total number of bytes occupied by a FloatArray must be calculated as the Double type.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeFloatArray([1.2, 1.3, 1.4]); - console.log("RpcClient: writeFloatArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeFloatArray([1.2, 1.3, 1.4]); + } catch(error) { + console.info("rpc write floatArray fail, errorCode " + error.code); + console.info("rpc write floatArray fail, errorMessage" + error.message); + } ``` - ### readFloatArray -readFloatArray(dataIn: number[]) : void +readFloatArray(dataIn: number[]): void -Reads a FloatArray from this **MessageParcel** object. +Reads a floating-point array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataIn | number[] | Yes| FloatArray to read. The system processes Float data as that of the Double type. Therefore, the total number of bytes occupied by a FloatArray must be calculated as the Double type.| + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | ----------------------------------------------------------------------------------------------------------------------- | + | dataIn | number[] | Yes | Floating-point array to read. The system processes Float data as that of the Double type. Therefore, the total number of bytes occupied by a FloatArray must be calculated as the Double type.| + +**Error codes** +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeFloatArray([1.2, 1.3, 1.4]); - console.log("RpcClient: writeFloatArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeFloatArray([1.2, 1.3, 1.4]); + }catch(error){ + console.info("rpc write floatArray fail, errorCode " + error.code); + console.info("rpc write floatArray fail, errorMessage" + error.message); + } let array = new Array(3); - data.readFloatArray(array); + try { + data.readFloatArray(array); + } catch(error) { + console.info("rpc read floatArray fail, errorCode " + error.code); + console.info("rpc read floatArray fail, errorMessage" + error.message); + } ``` - ### readFloatArray readFloatArray(): number[] -Reads the FloatArray from this **MessageParcel** object. +Reads the floating-point array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | number[] | FloatArray read.| + | Type | Description | + | -------- | -------------- | + | number[] | Floating-point array read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeFloatArray([1.2, 1.3, 1.4]); - console.log("RpcClient: writeFloatArray is " + result); - let array = data.readFloatArray(); - console.log("RpcClient: readFloatArray is " + array); + let data = rpc.MessageSequence.create(); + try { + data.writeFloatArray([1.2, 1.3, 1.4]); + } catch(error) { + console.info("rpc write floatArray fail, errorCode " + error.code); + console.info("rpc write floatArray fail, errorMessage" + error.message); + } + try { + let array = data.readFloatArray(); + console.log("RpcClient: readFloatArray is " + array); + } catch(error) { + console.info("rpc read floatArray fail, errorCode " + error.code); + console.info("rpc read floatArray fail, errorMessage" + error.message); + } ``` - ### writeDoubleArray -writeDoubleArray(doubleArray: number[]): boolean +writeDoubleArray(doubleArray: number[]): void -Writes a DoubleArray to this **MessageParcel** object. +Writes a double-precision floating-point array to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | doubleArray | number[] | Yes| DoubleArray to write.| + | Name | Type | Mandatory| Description | + | ----------- | -------- | ---- | ------------------------ | + | doubleArray | number[] | Yes | Double-precision floating-point array to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeDoubleArray([11.1, 12.2, 13.3]); - console.log("RpcClient: writeDoubleArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeDoubleArray([11.1, 12.2, 13.3]); + } catch(error) { + console.info("rpc write doubleArray fail, errorCode " + error.code); + console.info("rpc write doubleArray fail, errorMessage" + error.message); + } ``` - ### readDoubleArray -readDoubleArray(dataIn: number[]) : void +readDoubleArray(dataIn: number[]): void -Reads a DoubleArray from this **MessageParcel** object. +Reads a double-precision floating-point array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataIn | number[] | Yes| DoubleArray to read.| + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | ------------------------ | + | dataIn | number[] | Yes | Double-precision floating-point array to read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeDoubleArray([11.1, 12.2, 13.3]); - console.log("RpcClient: writeDoubleArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeDoubleArray([11.1, 12.2, 13.3]); + } catch(error) { + console.info("rpc write doubleArray fail, errorCode " + error.code); + console.info("rpc write doubleArray fail, errorMessage" + error.message); + } let array = new Array(3); - data.readDoubleArray(array); + try { + data.readDoubleArray(array); + } catch(error) { + console.info("rpc read doubleArray fail, errorCode " + error.code); + console.info("rpc read doubleArray fail, errorMessage" + error.message); + } ``` - ### readDoubleArray readDoubleArray(): number[] -Reads the DoubleArray from this **MessageParcel** object. +Reads the double-precision floating-point array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | number[] | DoubleArray read.| + | Type | Description | + | -------- | -------------------- | + | number[] | Double-precision floating-point array read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeDoubleArray([11.1, 12.2, 13.3]); - console.log("RpcClient: writeDoubleArray is " + result); - let array = data.readDoubleArray(); - console.log("RpcClient: readDoubleArray is " + array); + let data = rpc.MessageSequence.create(); + try { + data.writeDoubleArray([11.1, 12.2, 13.3]); + } catch(error) { + console.info("rpc write doubleArray fail, errorCode " + error.code); + console.info("rpc write doubleArray fail, errorMessage" + error.message); + } + try { + let array = data.readDoubleArray(); + console.log("RpcClient: readDoubleArray is " + array); + } catch(error) { + console.info("rpc read doubleArray fail, errorCode " + error.code); + console.info("rpc read doubleArray fail, errorMessage" + error.message); + } ``` - ### writeBooleanArray -writeBooleanArray(booleanArray: boolean[]): boolean +writeBooleanArray(booleanArray: boolean[]): void -Writes a Boolean array to this **MessageParcel** object. +Writes a Boolean array to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | booleanArray | boolean[] | Yes| Boolean array to write.| + | Name | Type | Mandatory| Description | + | ------------ | --------- | ---- | ------------------ | + | booleanArray | boolean[] | Yes | Boolean array to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeBooleanArray([false, true, false]); - console.log("RpcClient: writeBooleanArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeBooleanArray([false, true, false]); + } catch(error) { + console.info("rpc write booleanArray fail, errorCode " + error.code); + console.info("rpc write booleanArray fail, errorMessage" + error.message); + } ``` - ### readBooleanArray -readBooleanArray(dataIn: boolean[]) : void +readBooleanArray(dataIn: boolean[]): void -Reads a Boolean array from this **MessageParcel** object. +Reads a Boolean array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataIn | boolean[] | Yes| Boolean array to read.| + | Name| Type | Mandatory| Description | + | ------ | --------- | ---- | ------------------ | + | dataIn | boolean[] | Yes | Boolean array to read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeBooleanArray([false, true, false]); - console.log("RpcClient: writeBooleanArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeBooleanArray([false, true, false]); + } catch(error) { + console.info("rpc write booleanArray fail, errorCode " + error.code); + console.info("rpc write booleanArray fail, errorMessage" + error.message); + } let array = new Array(3); - data.readBooleanArray(array); + try { + data.readBooleanArray(array); + } catch(error) { + console.info("rpc read booleanArray fail, errorCode " + error.code); + console.info("rpc read booleanArray fail, errorMessage" + error.message); + } ``` - ### readBooleanArray readBooleanArray(): boolean[] -Reads the Boolean array from this **MessageParcel** object. +Reads the Boolean array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | --------- | -------------- | | boolean[] | Boolean array read.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | + +**Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeBooleanArray([false, true, false]); - console.log("RpcClient: writeBooleanArray is " + result); - let array = data.readBooleanArray(); - console.log("RpcClient: readBooleanArray is " + array); + let data = rpc.MessageSequence.create(); + try { + data.writeBooleanArray([false, true, false]); + } catch(error) { + console.info("rpc write booleanArray fail, errorCode " + error.code); + console.info("rpc write booleanArray fail, errorMessage" + error.message); + } + try { + let array = data.readBooleanArray(); + console.log("RpcClient: readBooleanArray is " + array); + } catch(error) { + console.info("rpc read booleanArray fail, errorCode " + error.code); + console.info("rpc read booleanArray fail, errorMessage" + error.message); + } ``` - ### writeCharArray -writeCharArray(charArray: number[]): boolean +writeCharArray(charArray: number[]): void -Writes a character array to this **MessageParcel** object. +Writes a character array to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | charArray | number[] | Yes| Character array to write.| + | Name | Type | Mandatory| Description | + | --------- | -------- | ---- | ---------------------- | + | charArray | number[] | Yes | Character array to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | -------- | ------ | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeCharArray([97, 98, 88]); - console.log("RpcClient: writeCharArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeCharArray([97, 98, 88]); + } catch(error) { + console.info("rpc write charArray fail, errorCode " + error.code); + console.info("rpc write charArray fail, errorMessage" + error.message); + } ``` - ### readCharArray -readCharArray(dataIn: number[]) : void +readCharArray(dataIn: number[]): void -Reads a character array from this **MessageParcel** object. +Reads a character array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataIn | number[] | Yes| Character array to read.| + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | ---------------------- | + | dataIn | number[] | Yes | Character array to read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeCharArray([97, 98, 99]); - console.log("RpcClient: writeCharArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeCharArray([97, 98, 88]); + } catch(error) { + console.info("rpc write charArray fail, errorCode " + error.code); + console.info("rpc write charArray fail, errorMessage" + error.message); + } let array = new Array(3); - data.readCharArray(array); + try { + data.readCharArray(array); + } catch(error) { + console.info("rpc read charArray fail, errorCode " + error.code); + console.info("rpc read charArray fail, errorMessage" + error.message); + } ``` - ### readCharArray readCharArray(): number[] -Reads the character array from this **MessageParcel** object. +Reads the character array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | -------- | ------------------ | | number[] | Character array read.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | + **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeCharArray([97, 98, 99]); - console.log("RpcClient: writeCharArray is " + result); - let array = data.readCharArray(); - console.log("RpcClient: readCharArray is " + array); + let data = rpc.MessageSequence.create(); + try { + data.writeCharArray([97, 98, 88]); + } catch(error) { + console.info("rpc write charArray fail, errorCode " + error.code); + console.info("rpc write charArray fail, errorMessage" + error.message); + } + let array = new Array(3); + try { + let array = data.readCharArray(); + console.log("RpcClient: readCharArray is " + array); + } catch(error) { + console.info("rpc read charArray fail, errorCode " + error.code); + console.info("rpc read charArray fail, errorMessage" + error.message); + } ``` - ### writeStringArray -writeStringArray(stringArray: string[]): boolean +writeStringArray(stringArray: string[]): void -Writes a string array to this **MessageParcel** object. +Writes a string array to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | stringArray | string[] | Yes| String array to write. The length of a single element in the array must be less than 40960 bytes.| + | Name | Type | Mandatory| Description | + | ----------- | -------- | ---- | ------------------------------------------------------- | + | stringArray | string[] | Yes | String array to write. The length of a single element in the array must be less than 40960 bytes.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeStringArray(["abc", "def"]); - console.log("RpcClient: writeStringArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeStringArray(["abc", "def"]); + } catch(error) { + console.info("rpc write stringArray fail, errorCode " + error.code); + console.info("rpc write stringArray fail, errorMessage" + error.message); + } ``` - ### readStringArray -readStringArray(dataIn: string[]) : void +readStringArray(dataIn: string[]): void -Reads a string array from this **MessageParcel** object. +Reads a string array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataIn | string[] | Yes| String array to read.| + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | -------------------- | + | dataIn | string[] | Yes | String array to read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeStringArray(["abc", "def"]); - console.log("RpcClient: writeStringArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeStringArray(["abc", "def"]); + } catch(error) { + console.info("rpc write stringArray fail, errorCode " + error.code); + console.info("rpc write stringArray fail, errorMessage" + error.message); + } let array = new Array(2); - data.readStringArray(array); + try { + data.readStringArray(array); + } catch(error) { + console.info("rpc read stringArray fail, errorCode " + error.code); + console.info("rpc read stringArray fail, errorMessage" + error.message); + } ``` - ### readStringArray readStringArray(): string[] -Reads the string array from this **MessageParcel** object. +Reads the string array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | -------- | ---------------- | | string[] | String array read.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | + **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeStringArray(["abc", "def"]); - console.log("RpcClient: writeStringArray is " + result); - let array = data.readStringArray(); - console.log("RpcClient: readStringArray is " + array); + let data = rpc.MessageSequence.create(); + try { + data.writeStringArray(["abc", "def"]); + } catch(error) { + console.info("rpc write stringArray fail, errorCode " + error.code); + console.info("rpc write stringArray fail, errorMessage" + error.message); + } + try { + let array = data.readStringArray(); + console.log("RpcClient: readStringArray is " + array); + } catch(error) { + console.info("rpc read stringArray fail, errorCode " + error.code); + console.info("rpc read stringArray fail, errorMessage" + error.message); + } ``` - -### writeNoException8+ +### writeNoException writeNoException(): void -Writes information to this **MessageParcel** object indicating that no exception occurred. +Writes information to this **MessageSequence** object indicating that no exception occurred. **System capability**: SystemCapability.Communication.IPC.Core +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900009 | write data to message sequence failed | + **Example** ``` - class MyDeathRecipient { - onRemoteDied() { - console.log("server died"); - } - } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - isObjectDead(): boolean { - return false; - } + onRemoteRequest(code, data, reply, option) { if (code === 1) { console.log("RpcServer: onRemoteRequest called"); - reply.writeNoException(); + try { + reply.writeNoException(); + } catch(error) { + console.info("rpc write no exception fail, errorCode " + error.code); + console.info("rpc write no exception fail, errorMessage" + error.message); + } return true; } else { console.log("RpcServer: unknown code: " + code); @@ -1816,15 +2376,22 @@ Writes information to this **MessageParcel** object indicating that no exception } ``` - -### readException8+ +### readException readException(): void -Reads the exception information from this **MessageParcel** object. +Reads the exception information from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | + **Example** ``` @@ -1848,194 +2415,219 @@ Reads the exception information from this **MessageParcel** object. }; FA.connectAbility(want, connect); let option = new rpc.MessageOption(); - let data = rpc.MessageParcel.create(); - let reply = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); + let reply = rpc.MessageSequence.create(); data.writeInt(1); data.writeString("hello"); - proxy.sendRequestAsync(1, data, reply, option) + proxy.sendMessageRequest(1, data, reply, option) .then(function(errCode) { if (errCode === 0) { - console.log("sendRequestAsync got result"); - reply.readException(); + console.log("sendMessageRequest got result"); + try { + reply.readException(); + } catch(error) { + console.info("rpc read exception fail, errorCode " + error.code); + console.info("rpc read no exception fail, errorMessage" + error.message); + } let msg = reply.readString(); console.log("RPCTest: reply msg: " + msg); } else { - console.log("RPCTest: sendRequestAsync failed, errCode: " + errCode); + console.log("RPCTest: sendMessageRequest failed, errCode: " + errCode); } }).catch(function(e) { - console.log("RPCTest: sendRequestAsync got exception: " + e.message); + console.log("RPCTest: sendMessageRequest got exception: " + e.message); }).finally (() => { - console.log("RPCTest: sendRequestAsync ends, reclaim parcel"); + console.log("RPCTest: sendMessageRequest ends, reclaim parcel"); data.reclaim(); reply.reclaim(); }); ``` +### writeParcelableArray -### writeSequenceableArray - -writeSequenceableArray(sequenceableArray: Sequenceable[]): boolean +writeParcelableArray(parcelableArray: Parcelable[]): void -Writes a sequenceable array to this **MessageParcel** object. +Writes a **Parcelable** array to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | sequenceableArray | Sequenceable[] | Yes| Sequenceable array to write.| + | Name | Type | Mandatory| Description | + | --------------- | ------------ | ---- | -------------------------- | + | parcelableArray | Parcelable[] | Yes | **Parcelable** array to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900009 | write data to message sequence failed | **Example** ``` - class MySequenceable { + class MyParcelable { num: number; str: string; constructor(num, str) { this.num = num; this.str = str; } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); return true; } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); return true; } } - let sequenceable = new MySequenceable(1, "aaa"); - let sequenceable2 = new MySequenceable(2, "bbb"); - let sequenceable3 = new MySequenceable(3, "ccc"); - let a = [sequenceable, sequenceable2, sequenceable3]; - let data = rpc.MessageParcel.create(); - let result = data.writeSequenceableArray(a); - console.log("RpcClient: writeSequenceableArray is " + result); + let parcelable = new MyParcelable(1, "aaa"); + let parcelable2 = new MyParcelable(2, "bbb"); + let parcelable3 = new MyParcelable(3, "ccc"); + let a = [parcelable, parcelable2, parcelable3]; + let data = rpc.MessageSequence.create(); + try { + data.writeParcelableArray(a); + } catch(error) { + console.info("rpc write parcelable array fail, errorCode " + error.code); + console.info("rpc write parcelable array fail, errorMessage" + error.message); + } ``` +### readParcelableArray -### readSequenceableArray8+ - -readSequenceableArray(sequenceableArray: Sequenceable[]): void +readParcelableArray(parcelableArray: Parcelable[]): void -Reads a sequenceable array from this **MessageParcel** object. +Reads a **Parcelable** array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | sequenceableArray | Sequenceable[] | Yes| Sequenceable array to read.| + | Name | Type | Mandatory| Description | + | --------------- | ------------ | ---- | -------------------------- | + | parcelableArray | Parcelable[] | Yes | **Parcelable** array to read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | + | 1900012 | call js callback function failed | **Example** ``` - class MySequenceable { + class MyParcelable { num: number; str: string; constructor(num, str) { this.num = num; this.str = str; } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); return true; } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); return true; } } - let sequenceable = new MySequenceable(1, "aaa"); - let sequenceable2 = new MySequenceable(2, "bbb"); - let sequenceable3 = new MySequenceable(3, "ccc"); - let a = [sequenceable, sequenceable2, sequenceable3]; - let data = rpc.MessageParcel.create(); - let result = data.writeSequenceableArray(a); - console.log("RpcClient: writeSequenceableArray is " + result); - let b = [new MySequenceable(0, ""), new MySequenceable(0, ""), new MySequenceable(0, "")]; - data.readSequenceableArray(b); + let parcelable = new MyParcelable(1, "aaa"); + let parcelable2 = new MyParcelable(2, "bbb"); + let parcelable3 = new MyParcelable(3, "ccc"); + let a = [parcelable, parcelable2, parcelable3]; + let data = rpc.MessageSequence.create(); + let result = data.writeParcelableArray(a); + console.log("RpcClient: writeParcelableArray is " + result); + let b = [new MyParcelable(0, ""), new MyParcelable(0, ""), new MyParcelable(0, "")]; + try { + data.readParcelableArray(b); + } catch(error) { + console.info("rpc read parcelable array fail, errorCode " + error.code); + console.info("rpc read parcelable array fail, errorMessage" + error.message); + } + data.readParcelableArray(b); ``` +### writeRemoteObjectArray -### writeRemoteObjectArray8+ - -writeRemoteObjectArray(objectArray: IRemoteObject[]): boolean +writeRemoteObjectArray(objectArray: IRemoteObject[]): void -Writes an array of **IRemoteObject** objects to this **MessageParcel** object. +Writes an array of **IRemoteObject** objects to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | objectArray | IRemoteObject[] | Yes| Array of **IRemoteObject** objects to write.| + | Name | Type | Mandatory| Description | + | ----------- | --------------- | ---- | ---------------------------------------------- | + | objectArray | IRemoteObject[] | Yes | Array of **IRemoteObject** objects to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** if the operation fails or if the **IRemoteObject** array is null.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ------- | + | 1900009 | write data to message sequence failed | **Example** ``` - class MyDeathRecipient { - onRemoteDied() { - console.log("server died"); - } - } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); - this.attachLocalInterface(this, descriptor); - } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - isObjectDead(): boolean { - return false; + this.modifyLocalInterface(this, descriptor); } + asObject(): rpc.IRemoteObject { return this; } } let a = [new TestRemoteObject("testObject1"), new TestRemoteObject("testObject2"), new TestRemoteObject("testObject3")]; - let data = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); let result = data.writeRemoteObjectArray(a); + try { + data.writeRemoteObjectArray(a); + } catch(error) { + console.info("rpc write remote object array fail, errorCode " + error.code); + console.info("rpc write remote object array fail, errorMessage" + error.message); + } console.log("RpcClient: writeRemoteObjectArray is " + result); ``` - -### readRemoteObjectArray8+ +### readRemoteObjectArray readRemoteObjectArray(objects: IRemoteObject[]): void -Reads an **IRemoteObject** array from this **MessageParcel** object. +Reads an array of **IRemoteObject** objects from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | objects | IRemoteObject[] | Yes| **IRemoteObject** array to read.| + | Name | Type | Mandatory| Description | + | ------- | --------------- | ---- | ---------------------------------------------- | + | objects | IRemoteObject[] | Yes | **IRemoteObject** array to read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** @@ -2048,79 +2640,75 @@ Reads an **IRemoteObject** array from this **MessageParcel** object. class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); - this.attachLocalInterface(this, descriptor); - } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - isObjectDead(): boolean { - return false; + this.modifyLocalInterface(this, descriptor); } + asObject(): rpc.IRemoteObject { return this; } } let a = [new TestRemoteObject("testObject1"), new TestRemoteObject("testObject2"), new TestRemoteObject("testObject3")]; - let data = rpc.MessageParcel.create(); - let result = data.writeRemoteObjectArray(a); + let data = rpc.MessageSequence.create(); + data.writeRemoteObjectArray(a); let b = new Array(3); + try { + data.readRemoteObjectArray(b); + } catch(error) { + console.info("rpc read remote object array fail, errorCode " + error.code); + console.info("rpc read remote object array fail, errorMessage" + error.message); + } data.readRemoteObjectArray(b); ``` - -### readRemoteObjectArray8+ +### readRemoteObjectArray readRemoteObjectArray(): IRemoteObject[] -Reads the **IRemoteObject** array from this **MessageParcel** object. +Reads the **IRemoteObject** object array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | IRemoteObject[] | **IRemoteObject** object array obtained.| + | Type | Description | + | --------------- | --------------------------- | + | IRemoteObject[] | **IRemoteObject** object array read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - class MyDeathRecipient { - onRemoteDied() { - console.log("server died"); - } - } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); - this.attachLocalInterface(this, descriptor); - } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - isObjectDead(): boolean { - return false; + this.modifyLocalInterface(this, descriptor); } + asObject(): rpc.IRemoteObject { return this; } } let a = [new TestRemoteObject("testObject1"), new TestRemoteObject("testObject2"), new TestRemoteObject("testObject3")]; - let data = rpc.MessageParcel.create(); - let result = data.writeRemoteObjectArray(a); - console.log("RpcClient: readRemoteObjectArray is " + result); - let b = data.readRemoteObjectArray(); - console.log("RpcClient: readRemoteObjectArray is " + b); + let data = rpc.MessageSequence.create(); + data.writeRemoteObjectArray(a); + try { + let b = data.readRemoteObjectArray(); + console.log("RpcClient: readRemoteObjectArray is " + b); + } catch(error) { + console.info("rpc read remote object array fail, errorCode " + error.code); + console.info("rpc read remote object array fail, errorMessage" + error.message); + } ``` -### closeFileDescriptor8+ +### closeFileDescriptor9+ static closeFileDescriptor(fd: number): void @@ -2130,9 +2718,9 @@ Closes a file descriptor. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor to close.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | -------------------- | + | fd | number | Yes | File descriptor to close.| **Example** @@ -2140,11 +2728,15 @@ Closes a file descriptor. import fileio from '@ohos.fileio'; let filePath = "path/to/file"; let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); - rpc.MessageParcel.closeFileDescriptor(fd); + try { + rpc.MessageSequence.closeFileDescriptor(fd); + } catch(error) { + console.info("rpc close file descriptor fail, errorCode " + error.code); + console.info("rpc close file descriptor fail, errorMessage" + error.message); + } ``` - -### dupFileDescriptor8+ +### dupFileDescriptor static dupFileDescriptor(fd: number) :number @@ -2154,104 +2746,2589 @@ Duplicates a file descriptor. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor to duplicate.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------------ | + | fd | number | Yes | File descriptor to duplicate.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | -------------------- | | number | New file descriptor.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ------- | + | 1900013 | call os dup function failed | + **Example** ``` import fileio from '@ohos.fileio'; let filePath = "path/to/file"; let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); - let newFd = rpc.MessageParcel.dupFileDescriptor(fd); + try { + let newFd = rpc.MessageSequence.dupFileDescriptor(fd); + } catch(error) { + console.info("rpc dup file descriptor fail, errorCode " + error.code); + console.info("rpc dup file descriptor fail, errorMessage" + error.message); + } ``` - -### containFileDescriptors8+ +### containFileDescriptors containFileDescriptors(): boolean -Checks whether this **MessageParcel** object contains a file descriptor. +Checks whether this **MessageSequence** object contains file descriptors. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the **MessageParcel** object contains a file descriptor; returns **false** otherwise.| + | Type | Description | + | ------- | -------------------------------------------------------------------- | + | boolean | Returns **true** if the **MessageSequence** object contains file descriptors; returns **false** otherwise.| **Example** + ``` import fileio from '@ohos.fileio'; - let parcel = new rpc.MessageParcel(); + let sequence = new rpc.MessageSequence(); let filePath = "path/to/file"; - let r1 = parcel.containFileDescriptors(); + let r1 = sequence.containFileDescriptors(); let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); - let writeResult = parcel.writeFileDescriptor(fd); - console.log("RpcTest: parcel writeFd result is : " + writeResult); - let containFD = parcel.containFileDescriptors(); - console.log("RpcTest: parcel after write fd containFd result is : " + containFD); + try { + sequence.writeFileDescriptor(fd); + } catch(error) { + console.info("rpc write file descriptor fail, errorCode " + error.code); + console.info("rpc write file descriptor fail, errorMessage" + error.message); + } + try { + let containFD = sequence.containFileDescriptors(); + console.log("RpcTest: sequence after write fd containFd result is : " + containFD); + } catch(error) { + console.info("rpc contain file descriptor fail, errorCode " + error.code); + console.info("rpc contain file descriptor fail, errorMessage" + error.message); + } ``` +### writeFileDescriptor -### writeFileDescriptor8+ - -writeFileDescriptor(fd: number): boolean +writeFileDescriptor(fd: number): void -Writes a file descriptor to this **MessageParcel** object. +Writes a file descriptor to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor to write.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | -------- | ------ | + | 1900009 | write data to message sequence failed | **Example** ``` import fileio from '@ohos.fileio'; - let parcel = new rpc.MessageParcel(); + let sequence = new rpc.MessageSequence(); let filePath = "path/to/file"; let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); - let writeResult = parcel.writeFileDescriptor(fd); - console.log("RpcTest: parcel writeFd result is : " + writeResult); + try { + sequence.writeFileDescriptor(fd); + } catch(error) { + console.info("rpc write file descriptor fail, errorCode " + error.code); + console.info("rpc write file descriptor fail, errorMessage" + error.message); + } ``` -### readFileDescriptor8+ +### readFileDescriptor readFileDescriptor(): number -Reads the file descriptor from this **MessageParcel** object. +Reads the file descriptor from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ---------------- | | number | File descriptor read.| -**Example** +**Error codes** - ``` +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | + +**Example** + + ``` + import fileio from '@ohos.fileio'; + let sequence = new rpc.MessageSequence(); + let filePath = "path/to/file"; + let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); + try { + sequence.writeFileDescriptor(fd); + } catch(error) { + console.info("rpc write file descriptor fail, errorCode " + error.code); + console.info("rpc write file descriptor fail, errorMessage" + error.message); + } + try { + let readFD = sequence.readFileDescriptor(); + } catch(error) { + console.info("rpc read file descriptor fail, errorCode " + error.code); + console.info("rpc read file descriptor fail, errorMessage" + error.message); + } + ``` + + +### writeAshmem + +writeAshmem(ashmem: Ashmem): void + +Writes an anonymous shared object to this **MessageSequence** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------------------------- | + | ashmem | Ashmem | Yes | Anonymous shared object to write.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ------- | + | 1900003 | write to ashmem failed | + +**Example** + + ``` + let sequence = new rpc.MessageSequence(); + let ashmem; + try { + ashmem = rpc.Ashmem.create("ashmem", 1024); + } catch(error) { + console.info("rpc create ashmem fail, errorCode " + error.code); + console.info("rpc creat ashmem fail, errorMessage" + error.message); + } + try { + sequence.writeAshmem(ashmem); + } catch(error) { + console.info("rpc write ashmem fail, errorCode " + error.code); + console.info("rpc write ashmem fail, errorMessage" + error.message); + } + ``` + + +### readAshmem + +readAshmem(): Ashmem + +Reads the anonymous shared object from this **MessageSequence** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | ------------------ | + | Ashmem | Anonymous share object read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900004 | read from ashmem failed | + +**Example** + + ``` + let sequence = new rpc.MessageSequence(); + let ashmem; + try { + ashmem = rpc.Ashmem.create("ashmem", 1024); + } catch(error) { + console.info("rpc create ashmem fail, errorCode " + error.code); + console.info("rpc creat ashmem fail, errorMessage" + error.message); + } + try { + sequence.writeAshmem(ashmem); + } catch(error) { + console.info("rpc write ashmem fail, errorCode " + error.code); + console.info("rpc write ashmem fail, errorMessage" + error.message); + } + try { + let readAshmem = sequence.readAshmem(); + console.log("RpcTest: read ashmem to result is : " + readAshmem); + } catch(error) { + console.info("rpc read ashmem fail, errorCode " + error.code); + console.info("rpc read ashmem fail, errorMessage" + error.message); + } + ``` + + +### getRawDataCapacity + +getRawDataCapacity(): number + +Obtains the maximum amount of raw data that can be held by this **MessageSequence** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | ------------------------------------------------------------ | + | number | 128 MB, which is the maximum amount of raw data that can be held by this **MessageSequence** object.| + +**Example** + + ``` + let sequence = new rpc.MessageSequence(); + let result = sequence.getRawDataCapacity(); + console.log("RpcTest: sequence get RawDataCapacity result is : " + result); + ``` + + +### writeRawData + +writeRawData(rawData: number[], size: number): void + +Writes raw data to this **MessageSequence** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ------- | -------- | ---- | ---------------------------------- | + | rawData | number[] | Yes | Raw data to write. | + | size | number | Yes | Size of the raw data, in bytes.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ------ | + | 1900009 | write data to message sequence failed | + +**Example** + + ``` + let sequence = new rpc.MessageSequence(); + let arr = [1, 2, 3, 4, 5]; + try { + sequence.writeRawData(arr, arr.length); + } catch(error) { + console.info("rpc write rawdata fail, errorCode " + error.code); + console.info("rpc write rawdata fail, errorMessage" + error.message); + } + ``` + + +### readRawData + +readRawData(size: number): number[] + +Reads raw data from this **MessageSequence** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------------ | + | size | number | Yes | Size of the raw data to read.| + +**Return value** + + | Type | Description | + | -------- | ------------------------------ | + | number[] | Raw data read, in bytes.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | + +**Example** + + ``` + let sequence = new rpc.MessageSequence(); + let arr = [1, 2, 3, 4, 5]; + try { + sequence.writeRawData(arr, arr.length); + } catch(error) { + console.info("rpc write rawdata fail, errorCode " + error.code); + console.info("rpc write rawdata fail, errorMessage" + error.message); + } + try { + let result = sequence.readRawData(5); + console.log("RpcTest: sequence read raw data result is : " + result); + } catch(error) { + console.info("rpc read rawdata fail, errorCode " + error.code); + console.info("rpc read rawdata fail, errorMessage" + error.message); + } + ``` + +## MessageParcel(deprecated) + +>This class is no longer maintained since API version 9. You are advised to use [MessageSequence](#messagesequence9). + +Provides APIs for reading and writing data in specific format. During RPC, the sender can use the **write()** method provided by **MessageParcel** to write data in specific format to a **MessageParcel** object. The receiver can use the **read()** method provided by **MessageParcel** to read data in specific format from a **MessageParcel** object. The data formats include basic data types and arrays, IPC objects, interface tokens, and custom sequenceable objects. + +### create + +create(): MessageParcel + +Creates a **MessageParcel** object. This method is a static method. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------------- | ----------------------------- | + | MessageParcel | **MessageParcel** object created.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + console.log("RpcClient: data is " + data); + ``` + +### reclaim + +reclaim(): void + +Reclaims the **MessageParcel** object that is no longer used. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Example** + + ``` + let reply = rpc.MessageParcel.create(); + reply.reclaim(); + ``` + +### writeRemoteObject + +writeRemoteObject(object: [IRemoteObject](#iremoteobject)): boolean + +Serializes a remote object and writes it to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------------------------------- | ---- | --------------------------------------- | + | object | [IRemoteObject](#iremoteobject) | Yes | Remote object to serialize and write to the **MessageParcel** object.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } + class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } + } + let data = rpc.MessageParcel.create(); + let testRemoteObject = new TestRemoteObject("testObject"); + data.writeRemoteObject(testRemoteObject); + ``` + +### readRemoteObject + +readRemoteObject(): IRemoteObject + +Reads the remote object from this **MessageParcel** object. You can use this method to deserialize the **MessageParcel** object to generate an **IRemoteObject**. The remote objects are read in the order in which they are written to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------------------------------- | ------------------ | + | [IRemoteObject](#iremoteobject) | Remote object obtained.| + +**Example** + + ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } + class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } + } + let data = rpc.MessageParcel.create(); + let testRemoteObject = new TestRemoteObject("testObject"); + data.writeRemoteObject(testRemoteObject); + let proxy = data.readRemoteObject(); + ``` + +### writeInterfaceToken + +writeInterfaceToken(token: string): boolean + +Writes an interface token to this **MessageParcel** object. The remote object can use this interface token to verify the communication. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------ | + | token | string | Yes | Interface token to write.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeInterfaceToken("aaa"); + console.log("RpcServer: writeInterfaceToken is " + result); + ``` + + +### readInterfaceToken + +readInterfaceToken(): string + +Reads the interface token from this **MessageParcel** object. The interface token is read in the sequence in which it is written to the **MessageParcel** object. The local object can use it to verify the communication. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | ------------------------ | + | string | Interface token obtained.| + +**Example** + + ``` + class Stub extends rpc.RemoteObject { + onRemoteMessageRequest(code, data, reply, option) { + let interfaceToken = data.readInterfaceToken(); + console.log("RpcServer: interfaceToken is " + interfaceToken); + return true; + } + } + ``` + + +### getSize + +getSize(): number + +Obtains the data size of this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | --------------------------------------------- | + | number | Size of the **MessageParcel** object obtained, in bytes.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let size = data.getSize(); + console.log("RpcClient: size is " + size); + ``` + + +### getCapacity + +getCapacity(): number + +Obtains the capacity of this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | --------------------------------------------- | + | number | **MessageParcel** capacity obtained, in bytes.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.getCapacity(); + console.log("RpcClient: capacity is " + result); + ``` + + +### setSize + +setSize(size: number): boolean + +Sets the size of data contained in this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------------------------------- | + | size | number | Yes | Data size to set, in bytes.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let setSize = data.setSize(16); + console.log("RpcClient: setSize is " + setSize); + ``` + + +### setCapacity + +setCapacity(size: number): boolean + +Sets the storage capacity of this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------------------------------- | + | size | number | Yes | Storage capacity to set, in bytes.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.setCapacity(100); + console.log("RpcClient: setCapacity is " + result); + ``` + + +### getWritableBytes + +getWritableBytes(): number + +Obtains the writable capacity of this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | --------------------------------------------------- | + | number | **MessageParcel** writable capacity obtained, in bytes.| + +**Example** + + ``` + class Stub extends rpc.RemoteObject { + onRemoteMessageRequest(code, data, reply, option) { + let getWritableBytes = data.getWritableBytes(); + console.log("RpcServer: getWritableBytes is " + getWritableBytes); + return true; + } + } + ``` + + +### getReadableBytes + +getReadableBytes(): number + +Obtains the readable capacity of this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | --------------------------------------------------- | + | number | **MessageParcel** object readable capacity, in bytes.| + +**Example** + + ``` + class Stub extends rpc.RemoteObject { + onRemoteRequest(code, data, reply, option) { + let result = data.getReadableBytes(); + console.log("RpcServer: getReadableBytes is " + result); + return true; + } + } + ``` + + +### getReadPosition + +getReadPosition(): number + +Obtains the read position of this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | --------------------------------------- | + | number | Current read position of the **MessageParcel** object.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let readPos = data.getReadPosition(); + console.log("RpcClient: readPos is " + readPos); + ``` + + +### getWritePosition + +getWritePosition(): number + +Obtains the write position of this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | --------------------------------------- | + | number | Current write position of the **MessageParcel** object.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + data.writeInt(10); + let bwPos = data.getWritePosition(); + console.log("RpcClient: bwPos is " + bwPos); + ``` + + +### rewindRead + +rewindRead(pos: number): boolean + +Moves the read pointer to the specified position. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------------ | + | pos | number | Yes | Position from which data is to read.| + +**Return value** + + | Type | Description | + | ------- | ------------------------------------------------- | + | boolean | Returns **true** if the read position changes; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + data.writeInt(12); + data.writeString("parcel"); + let number = data.readInt(); + console.log("RpcClient: number is " + number); + data.rewindRead(0); + let number2 = data.readInt(); + console.log("RpcClient: rewindRead is " + number2); + ``` + + +### rewindWrite + +rewindWrite(pos: number): boolean + +Moves the write pointer to the specified position. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------------ | + | pos | number | Yes | Position from which data is to write.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------------------- | + | boolean | Returns **true** if the write position changes; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + data.writeInt(4); + data.rewindWrite(0); + data.writeInt(5); + let number = data.readInt(); + console.log("RpcClient: rewindWrite is: " + number); + ``` + + +### writeByte + +writeByte(val: number): boolean + +Writes a Byte value to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ---------------- | + | val | number | Yes | Byte value to write.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeByte(2); + console.log("RpcClient: writeByte is: " + result); + ``` + + +### readByte + +readByte(): number + +Reads the Byte value from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | ------------ | + | number | Byte value read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeByte(2); + console.log("RpcClient: writeByte is: " + result); + let ret = data.readByte(); + console.log("RpcClient: readByte is: " + ret); + ``` + + +### writeShort + +writeShort(val: number): boolean + +Writes a Short int value to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------ | + | val | number | Yes | Short int value to write.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeShort(8); + console.log("RpcClient: writeShort is: " + result); + ``` + + +### readShort + +readShort(): number + +Reads the Short int value from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | -------------- | + | number | Short int value read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeShort(8); + console.log("RpcClient: writeShort is: " + result); + let ret = data.readShort(); + console.log("RpcClient: readShort is: " + ret); + ``` + + +### writeInt + +writeInt(val: number): boolean + +Writes an Int value to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ---------------- | + | val | number | Yes | Int value to write.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeInt(10); + console.log("RpcClient: writeInt is " + result); + ``` + + +### readInt + +readInt(): number + +Reads the Int value from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | ------------ | + | number | Int value read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeInt(10); + console.log("RpcClient: writeInt is " + result); + let ret = data.readInt(); + console.log("RpcClient: readInt is " + ret); + ``` + + +### writeLong + +writeLong(val: number): boolean + +Writes a Long int value to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ---------------- | + | val | number | Yes | Long int value to write.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeLong(10000); + console.log("RpcClient: writeLong is " + result); + ``` + + +### readLong + +readLong(): number + +Reads the Long int value from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | -------------- | + | number | Long int value read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeLong(10000); + console.log("RpcClient: writeLong is " + result); + let ret = data.readLong(); + console.log("RpcClient: readLong is " + ret); + ``` + + +### writeFloat + +writeFloat(val: number): boolean + +Writes a Float value to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ---------------- | + | val | number | Yes | Float value to write.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeFloat(1.2); + console.log("RpcClient: writeFloat is " + result); + ``` + + +### readFloat + +readFloat(): number + +Reads the Float value from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | ------------ | + | number | Float value read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeFloat(1.2); + console.log("RpcClient: writeFloat is " + result); + let ret = data.readFloat(); + console.log("RpcClient: readFloat is " + ret); + ``` + + +### writeDouble + +writeDouble(val: number): boolean + +Writes a Double value to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ---------------------- | + | val | number | Yes | Double value to write.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeDouble(10.2); + console.log("RpcClient: writeDouble is " + result); + ``` + + +### readDouble + +readDouble(): number + +Reads the Double value from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | ------------------ | + | number | Double value read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeDouble(10.2); + console.log("RpcClient: writeDouble is " + result); + let ret = data.readDouble(); + console.log("RpcClient: readDouble is " + ret); + ``` + +### writeBoolean + +writeBoolean(val: boolean): boolean + +Writes a Boolean value to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------- | ---- | ---------------- | + | val | boolean | Yes | Boolean value to write.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeBoolean(false); + console.log("RpcClient: writeBoolean is " + result); + ``` + + +### readBoolean + +readBoolean(): boolean + +Reads the Boolean value from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------- | -------------------- | + | boolean | Boolean value read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeBoolean(false); + console.log("RpcClient: writeBoolean is " + result); + let ret = data.readBoolean(); + console.log("RpcClient: readBoolean is " + ret); + ``` + + +### writeChar + +writeChar(val: number): boolean + +Writes a Char value to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | -------------------- | + | val | number | Yes | Char value to write.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeChar(97); + console.log("RpcClient: writeChar is " + result); + ``` + + +### readChar + +readChar(): number + +Reads the Char value from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | ---------------- | + | number | Char value read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeChar(97); + console.log("RpcClient: writeChar is " + result); + let ret = data.readChar(); + console.log("RpcClient: readChar is " + ret); + ``` + + +### writeString + +writeString(val: string): boolean + +Writes a string to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ----------------------------------------- | + | val | string | Yes | String to write. The length of the string must be less than 40960 bytes.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeString('abc'); + console.log("RpcClient: writeString is " + result); + ``` + + +### readString + +readString(): string + +Reads the string from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | -------------- | + | string | String read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeString('abc'); + console.log("RpcClient: writeString is " + result); + let ret = data.readString(); + console.log("RpcClient: readString is " + ret); + ``` + + +### writeSequenceable + +writeSequenceable(val: Sequenceable): boolean + +Writes a sequenceable object to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ----------------------------- | ---- | -------------------- | + | val | [Sequenceable](#sequenceable) | Yes | Sequenceable object to write.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + class MySequenceable { + num: number; + str: string; + constructor(num, str) { + this.num = num; + this.str = str; + } + marshalling(messageParcel) { + messageParcel.writeInt(this.num); + messageParcel.writeString(this.str); + return true; + } + unmarshalling(messageParcel) { + this.num = messageParcel.readInt(); + this.str = messageParcel.readString(); + return true; + } + } + let sequenceable = new MySequenceable(1, "aaa"); + let data = rpc.MessageParcel.create(); + let result = data.writeSequenceable(sequenceable); + console.log("RpcClient: writeSequenceable is " + result); + ``` + + +### readSequenceable + +readSequenceable(dataIn: Sequenceable): boolean + +Reads member variables from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ----------------------------- | ---- | --------------------------------------- | + | dataIn | [Sequenceable](#sequenceabledeprecated) | Yes | Object that reads member variables from the **MessageParcel** object.| + +**Return value** + + | Type | Description | + | ------- | ------------------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + class MySequenceable { + num: number; + str: string; + constructor(num, str) { + this.num = num; + this.str = str; + } + marshalling(messageParcel) { + messageParcel.writeInt(this.num); + messageParcel.writeString(this.str); + return true; + } + unmarshalling(messageParcel) { + this.num = messageParcel.readInt(); + this.str = messageParcel.readString(); + return true; + } + } + let sequenceable = new MySequenceable(1, "aaa"); + let data = rpc.MessageParcel.create(); + let result = data.writeSequenceable(sequenceable); + console.log("RpcClient: writeSequenceable is " + result); + let ret = new MySequenceable(0, ""); + let result2 = data.readSequenceable(ret); + console.log("RpcClient: writeSequenceable is " + result2); + ``` + + +### writeByteArray + +writeByteArray(byteArray: number[]): boolean + +Writes a byte array to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | --------- | -------- | ---- | ------------------ | + | byteArray | number[] | Yes | Byte array to write.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let ByteArrayVar = [1, 2, 3, 4, 5]; + let result = data.writeByteArray(ByteArrayVar); + console.log("RpcClient: writeByteArray is " + result); + ``` + + +### readByteArray + +readByteArray(dataIn: number[]): void + +Reads a byte array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | ------------------ | + | dataIn | number[] | Yes | Byte array to read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let ByteArrayVar = [1, 2, 3, 4, 5]; + let result = data.writeByteArray(ByteArrayVar); + console.log("RpcClient: writeByteArray is " + result); + let array = new Array(5); + data.readByteArray(array); + ``` + + +### readByteArray + +readByteArray(): number[] + +Reads the byte array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | -------- | -------------- | + | number[] | Byte array read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let ByteArrayVar = [1, 2, 3, 4, 5]; + let result = data.writeByteArray(ByteArrayVar); + console.log("RpcClient: writeByteArray is " + result); + let array = data.readByteArray(); + console.log("RpcClient: readByteArray is " + array); + ``` + + +### writeShortArray + +writeShortArray(shortArray: number[]): boolean + +Writes a short array to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ---------- | -------- | ---- | -------------------- | + | shortArray | number[] | Yes | Short array to write.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeShortArray([11, 12, 13]); + console.log("RpcClient: writeShortArray is " + result); + ``` + + +### readShortArray + +readShortArray(dataIn: number[]): void + +Reads a short array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | -------------------- | + | dataIn | number[] | Yes | Short array to read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeShortArray([11, 12, 13]); + console.log("RpcClient: writeShortArray is " + result); + let array = new Array(3); + data.readShortArray(array); + ``` + + +### readShortArray + +readShortArray(): number[] + +Reads the short array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | -------- | ---------------- | + | number[] | Short array read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeShortArray([11, 12, 13]); + console.log("RpcClient: writeShortArray is " + result); + let array = data.readShortArray(); + console.log("RpcClient: readShortArray is " + array); + ``` + + +### writeIntArray + +writeIntArray(intArray: number[]): boolean + +Writes an integer array to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------- | -------- | ---- | ------------------ | + | intArray | number[] | Yes | Integer array to write.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeIntArray([100, 111, 112]); + console.log("RpcClient: writeIntArray is " + result); + ``` + + +### readIntArray + +readIntArray(dataIn: number[]): void + +Reads an integer array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | ------------------ | + | dataIn | number[] | Yes | Integer array to read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeIntArray([100, 111, 112]); + console.log("RpcClient: writeIntArray is " + result); + let array = new Array(3); + data.readIntArray(array); + ``` + + +### readIntArray + +readIntArray(): number[] + +Reads the integer array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | -------- | -------------- | + | number[] | Integer array read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeIntArray([100, 111, 112]); + console.log("RpcClient: writeIntArray is " + result); + let array = data.readIntArray(); + console.log("RpcClient: readIntArray is " + array); + ``` + + +### writeLongArray + +writeLongArray(longArray: number[]): boolean + +Writes a long array to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | --------- | -------- | ---- | -------------------- | + | longArray | number[] | Yes | Long array to write.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeLongArray([1111, 1112, 1113]); + console.log("RpcClient: writeLongArray is " + result); + ``` + + +### readLongArray + +readLongArray(dataIn: number[]): void + +Reads a long array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | -------------------- | + | dataIn | number[] | Yes | Long array to read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeLongArray([1111, 1112, 1113]); + console.log("RpcClient: writeLongArray is " + result); + let array = new Array(3); + data.readLongArray(array); + ``` + + +### readLongArray + +readLongArray(): number[] + +Reads the long array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | -------- | ---------------- | + | number[] | Long array read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeLongArray([1111, 1112, 1113]); + console.log("RpcClient: writeLongArray is " + result); + let array = data.readLongArray(); + console.log("RpcClient: readLongArray is " + array); + ``` + + +### writeFloatArray + +writeFloatArray(floatArray: number[]): boolean + +Writes a FloatArray to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | ---------- | -------- | ---- | --- | + | floatArray | number[] | Yes | Floating-point array to write. The system processes Float data as that of the Double type. Therefore, the total number of bytes occupied by a FloatArray must be calculated as the Double type.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeFloatArray([1.2, 1.3, 1.4]); + console.log("RpcClient: writeFloatArray is " + result); + ``` + + +### readFloatArray + +readFloatArray(dataIn: number[]): void + +Reads a FloatArray from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | ------ | -------- | ---- | ------ | + | dataIn | number[] | Yes | Floating-point array to read. The system processes Float data as that of the Double type. Therefore, the total number of bytes occupied by a FloatArray must be calculated as the Double type.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeFloatArray([1.2, 1.3, 1.4]); + console.log("RpcClient: writeFloatArray is " + result); + let array = new Array(3); + data.readFloatArray(array); + ``` + + +### readFloatArray + +readFloatArray(): number[] + +Reads the FloatArray from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | -------- | -------------- | + | number[] | FloatArray read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeFloatArray([1.2, 1.3, 1.4]); + console.log("RpcClient: writeFloatArray is " + result); + let array = data.readFloatArray(); + console.log("RpcClient: readFloatArray is " + array); + ``` + + +### writeDoubleArray + +writeDoubleArray(doubleArray: number[]): boolean + +Writes a DoubleArray to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ----------- | -------- | ---- | ------------------------ | + | doubleArray | number[] | Yes | DoubleArray to write.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeDoubleArray([11.1, 12.2, 13.3]); + console.log("RpcClient: writeDoubleArray is " + result); + ``` + + +### readDoubleArray + +readDoubleArray(dataIn: number[]): void + +Reads a DoubleArray from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | ------------------------ | + | dataIn | number[] | Yes | DoubleArray to read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeDoubleArray([11.1, 12.2, 13.3]); + console.log("RpcClient: writeDoubleArray is " + result); + let array = new Array(3); + data.readDoubleArray(array); + ``` + + +### readDoubleArray + +readDoubleArray(): number[] + +Reads the DoubleArray from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | -------- | -------------------- | + | number[] | DoubleArray read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeDoubleArray([11.1, 12.2, 13.3]); + console.log("RpcClient: writeDoubleArray is " + result); + let array = data.readDoubleArray(); + console.log("RpcClient: readDoubleArray is " + array); + ``` + + +### writeBooleanArray + +writeBooleanArray(booleanArray: boolean[]): boolean + +Writes a Boolean array to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ------------ | --------- | ---- | ------------------ | + | booleanArray | boolean[] | Yes | Boolean array to write.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeBooleanArray([false, true, false]); + console.log("RpcClient: writeBooleanArray is " + result); + ``` + + +### readBooleanArray + +readBooleanArray(dataIn: boolean[]): void + +Reads a Boolean array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | --------- | ---- | ------------------ | + | dataIn | boolean[] | Yes | Boolean array to read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeBooleanArray([false, true, false]); + console.log("RpcClient: writeBooleanArray is " + result); + let array = new Array(3); + data.readBooleanArray(array); + ``` + + +### readBooleanArray + +readBooleanArray(): boolean[] + +Reads the Boolean array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | --------- | -------------- | + | boolean[] | Boolean array read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeBooleanArray([false, true, false]); + console.log("RpcClient: writeBooleanArray is " + result); + let array = data.readBooleanArray(); + console.log("RpcClient: readBooleanArray is " + array); + ``` + + +### writeCharArray + +writeCharArray(charArray: number[]): boolean + +Writes a character array to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | --------- | -------- | ---- | ---------------------- | + | charArray | number[] | Yes | Character array to write.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeCharArray([97, 98, 88]); + console.log("RpcClient: writeCharArray is " + result); + ``` + + +### readCharArray + +readCharArray(dataIn: number[]): void + +Reads a character array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | ---------------------- | + | dataIn | number[] | Yes | Character array to read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeCharArray([97, 98, 99]); + console.log("RpcClient: writeCharArray is " + result); + let array = new Array(3); + data.readCharArray(array); + ``` + + +### readCharArray + +readCharArray(): number[] + +Reads the character array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | -------- | ------------------ | + | number[] | Character array read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeCharArray([97, 98, 99]); + console.log("RpcClient: writeCharArray is " + result); + let array = data.readCharArray(); + console.log("RpcClient: readCharArray is " + array); + ``` + + +### writeStringArray + +writeStringArray(stringArray: string[]): boolean + +Writes a string array to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description| + | ----------- | -------- | ---- | ---------------- | + | stringArray | string[] | Yes | String array to write. The length of a single element in the array must be less than 40960 bytes.| + +**Return value** + + | Type | Description| + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeStringArray(["abc", "def"]); + console.log("RpcClient: writeStringArray is " + result); + ``` + + +### readStringArray + +readStringArray(dataIn: string[]): void + +Reads a string array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | -------------------- | + | dataIn | string[] | Yes | String array to read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeStringArray(["abc", "def"]); + console.log("RpcClient: writeStringArray is " + result); + let array = new Array(2); + data.readStringArray(array); + ``` + + +### readStringArray + +readStringArray(): string[] + +Reads the string array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | -------- | ---------------- | + | string[] | String array read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeStringArray(["abc", "def"]); + console.log("RpcClient: writeStringArray is " + result); + let array = data.readStringArray(); + console.log("RpcClient: readStringArray is " + array); + ``` + + +### writeNoException8+ + +writeNoException(): void + +Writes information to this **MessageParcel** object indicating that no exception occurred. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Example** + + ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } + class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } + onRemoteRequest(code, data, reply, option) { + if (code === 1) { + console.log("RpcServer: onRemoteRequest called"); + reply.writeNoException(); + return true; + } else { + console.log("RpcServer: unknown code: " + code); + return false; + } + } + } + ``` + +### readException8+ + +readException(): void + +Reads the exception information from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Example** + + ``` + import FA from "@ohos.ability.featureAbility"; + let proxy; + let connect = { + onConnect: function(elementName, remoteProxy) { + console.log("RpcClient: js onConnect called."); + proxy = remoteProxy; + }, + onDisconnect: function(elementName) { + console.log("RpcClient: onDisconnect"); + }, + onFailed: function() { + console.log("RpcClient: onFailed"); + } + }; + let want = { + "bundleName": "com.ohos.server", + "abilityName": "com.ohos.server.MainAbility", + }; + FA.connectAbility(want, connect); + let option = new rpc.MessageOption(); + let data = rpc.MessageParcel.create(); + let reply = rpc.MessageParcel.create(); + data.writeInt(1); + data.writeString("hello"); + proxy.sendMessageRequest(1, data, reply, option) + .then(function(errCode) { + if (errCode === 0) { + console.log("sendMessageRequest got result"); + reply.readException(); + let msg = reply.readString(); + console.log("RPCTest: reply msg: " + msg); + } else { + console.log("RPCTest: sendMessageRequest failed, errCode: " + errCode); + } + }).catch(function(e) { + console.log("RPCTest: sendMessageRequest got exception: " + e.message); + }).finally (() => { + console.log("RPCTest: sendMessageRequest ends, reclaim parcel"); + data.reclaim(); + reply.reclaim(); + }); + ``` + +### writeSequenceableArray + +writeSequenceableArray(sequenceableArray: Sequenceable[]): boolean + +Writes a sequenceable array to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ----------------- | -------------- | ---- | -------------------------- | + | sequenceableArray | Sequenceable[] | Yes | Sequenceable array to write.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + class MySequenceable { + num: number; + str: string; + constructor(num, str) { + this.num = num; + this.str = str; + } + marshalling(messageParcel) { + messageParcel.writeInt(this.num); + messageParcel.writeString(this.str); + return true; + } + unmarshalling(messageParcel) { + this.num = messageParcel.readInt(); + this.str = messageParcel.readString(); + return true; + } + } + let sequenceable = new MySequenceable(1, "aaa"); + let sequenceable2 = new MySequenceable(2, "bbb"); + let sequenceable3 = new MySequenceable(3, "ccc"); + let a = [sequenceable, sequenceable2, sequenceable3]; + let data = rpc.MessageParcel.create(); + let result = data.writeSequenceableArray(a); + console.log("RpcClient: writeSequenceableArray is " + result); + ``` + + +### readSequenceableArray8+ + +readSequenceableArray(sequenceableArray: Sequenceable[]): void + +Reads a sequenceable array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ----------------- | -------------- | ---- | -------------------------- | + | sequenceableArray | Sequenceable[] | Yes | Sequenceable array to read.| + +**Example** + + ``` + class MySequenceable { + num: number; + str: string; + constructor(num, str) { + this.num = num; + this.str = str; + } + marshalling(messageParcel) { + messageParcel.writeInt(this.num); + messageParcel.writeString(this.str); + return true; + } + unmarshalling(messageParcel) { + this.num = messageParcel.readInt(); + this.str = messageParcel.readString(); + return true; + } + } + let sequenceable = new MySequenceable(1, "aaa"); + let sequenceable2 = new MySequenceable(2, "bbb"); + let sequenceable3 = new MySequenceable(3, "ccc"); + let a = [sequenceable, sequenceable2, sequenceable3]; + let data = rpc.MessageParcel.create(); + let result = data.writeSequenceableArray(a); + console.log("RpcClient: writeSequenceableArray is " + result); + let b = [new MySequenceable(0, ""), new MySequenceable(0, ""), new MySequenceable(0, "")]; + data.readSequenceableArray(b); + ``` + + +### writeRemoteObjectArray8+ + +writeRemoteObjectArray(objectArray: IRemoteObject[]): boolean + +Writes an array of **IRemoteObject** objects to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description| + | ----------- | --------------- | ---- | ----- | + | objectArray | IRemoteObject[] | Yes | Array of **IRemoteObject** objects to write.| + +**Return value** + + | Type | Description | + | ------- | -------------------------------------------------------------------------------------------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** if the operation fails or if the **IRemoteObject** array is null.| + +**Example** + + ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } + class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + this.attachLocalInterface(this, descriptor); + } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } + asObject(): rpc.IRemoteObject { + return this; + } + } + let a = [new TestRemoteObject("testObject1"), new TestRemoteObject("testObject2"), new TestRemoteObject("testObject3")]; + let data = rpc.MessageParcel.create(); + let result = data.writeRemoteObjectArray(a); + console.log("RpcClient: writeRemoteObjectArray is " + result); + ``` + + +### readRemoteObjectArray8+ + +readRemoteObjectArray(objects: IRemoteObject[]): void + +Reads an **IRemoteObject** array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description| + | ------- | --------------- | ---- | --------- | + | objects | IRemoteObject[] | Yes | **IRemoteObject** array to read.| + +**Example** + + ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } + class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + this.attachLocalInterface(this, descriptor); + } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } + asObject(): rpc.IRemoteObject { + return this; + } + } + let a = [new TestRemoteObject("testObject1"), new TestRemoteObject("testObject2"), new TestRemoteObject("testObject3")]; + let data = rpc.MessageParcel.create(); + let result = data.writeRemoteObjectArray(a); + let b = new Array(3); + data.readRemoteObjectArray(b); + ``` + + +### readRemoteObjectArray8+ + +readRemoteObjectArray(): IRemoteObject[] + +Reads the **IRemoteObject** array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type| Description| + | --------------- | -------- | + | IRemoteObject[] | **IRemoteObject** object array obtained.| + +**Example** + + ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } + class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + this.attachLocalInterface(this, descriptor); + } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } + asObject(): rpc.IRemoteObject { + return this; + } + } + let a = [new TestRemoteObject("testObject1"), new TestRemoteObject("testObject2"), new TestRemoteObject("testObject3")]; + let data = rpc.MessageParcel.create(); + let result = data.writeRemoteObjectArray(a); + console.log("RpcClient: readRemoteObjectArray is " + result); + let b = data.readRemoteObjectArray(); + console.log("RpcClient: readRemoteObjectArray is " + b); + ``` + + +### closeFileDescriptor8+ + +static closeFileDescriptor(fd: number): void + +Closes a file descriptor. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | -------------------- | + | fd | number | Yes | File descriptor to close.| + +**Example** + + ``` + import fileio from '@ohos.fileio'; + let filePath = "path/to/file"; + let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); + rpc.MessageParcel.closeFileDescriptor(fd); + ``` + + +### dupFileDescriptor8+ + +static dupFileDescriptor(fd: number) :number + +Duplicates a file descriptor. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------------ | + | fd | number | Yes | File descriptor to duplicate.| + +**Return value** + + | Type | Description | + | ------ | -------------------- | + | number | New file descriptor.| + +**Example** + + ``` + import fileio from '@ohos.fileio'; + let filePath = "path/to/file"; + let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); + let newFd = rpc.MessageParcel.dupFileDescriptor(fd); + ``` + + +### containFileDescriptors8+ + +containFileDescriptors(): boolean + +Checks whether this **MessageParcel** object contains a file descriptor. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------- | ------------------------------------------------------------------ | + | boolean | Returns **true** if the **MessageParcel** object contains a file descriptor; returns **false** otherwise.| + +**Example** + + ``` + import fileio from '@ohos.fileio'; + let parcel = new rpc.MessageParcel(); + let filePath = "path/to/file"; + let r1 = parcel.containFileDescriptors(); + let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); + let writeResult = parcel.writeFileDescriptor(fd); + console.log("RpcTest: parcel writeFd result is : " + writeResult); + let containFD = parcel.containFileDescriptors(); + console.log("RpcTest: parcel after write fd containFd result is : " + containFD); + ``` + + +### writeFileDescriptor8+ + +writeFileDescriptor(fd: number): boolean + +Writes a file descriptor to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor to write.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + import fileio from '@ohos.fileio'; + let parcel = new rpc.MessageParcel(); + let filePath = "path/to/file"; + let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); + let writeResult = parcel.writeFileDescriptor(fd); + console.log("RpcTest: parcel writeFd result is : " + writeResult); + ``` + + +### readFileDescriptor8+ + +readFileDescriptor(): number + +Reads the file descriptor from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | ---------------- | + | number | File descriptor read.| + +**Example** + + ``` import fileio from '@ohos.fileio'; let parcel = new rpc.MessageParcel(); let filePath = "path/to/file"; @@ -2272,14 +5349,14 @@ Writes an anonymous shared object to this **MessageParcel** object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ashmem | Ashmem | Yes| Anonymous shared object to write.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ----------------------------------- | + | ashmem | Ashmem | Yes | Anonymous shared object to write.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | -------------------------------------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -2302,8 +5379,8 @@ Reads the anonymous shared object from this **MessageParcel** object. **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ------------------ | | Ashmem | Anonymous share object obtained.| **Example** @@ -2328,8 +5405,8 @@ Obtains the maximum amount of raw data that can be held by this **MessageParcel* **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ---------------------------------------------------------- | | number | 128 MB, which is the maximum amount of raw data that can be held by this **MessageParcel** object.| **Example** @@ -2351,15 +5428,15 @@ Writes raw data to this **MessageParcel** object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | rawData | number[] | Yes| Raw data to write.| - | size | number | Yes| Size of the raw data, in bytes.| + | Name | Type | Mandatory| Description | + | ------- | -------- | ---- | ---------------------------------- | + | rawData | number[] | Yes | Raw data to write. | + | size | number | Yes | Size of the raw data, in bytes.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ----------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -2382,14 +5459,14 @@ Reads raw data from this **MessageParcel** object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | size | number | Yes| Size of the raw data to read.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------------ | + | size | number | Yes | Size of the raw data to read.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | -------- | ------------------------------ | | number[] | Raw data obtained, in bytes.| **Example** @@ -2403,10 +5480,118 @@ Reads raw data from this **MessageParcel** object. console.log("RpcTest: parcel read raw data result is : " + result); ``` -## Sequenceable -Writes objects of classes to a **MessageParcel** and reads them from the **MessageParcel** during IPC. +## Parcelable9+ + +Writes an object to a **MessageSequence** and reads it from the **MessageSequence** during IPC. + +### marshalling + +marshalling(dataOut: MessageSequence): boolean + +Marshals this **Parcelable** object into a **MessageSequence** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ------- | --------------- | ---- | ------------------------------------------- | + | dataOut | MessageSequence | Yes | **MessageSequence** object to which the **Parcelable** object is to be marshaled.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + class MyParcelable { + num: number; + str: string; + constructor(num, str) { + this.num = num; + this.str = str; + } + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); + return true; + } + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); + return true; + } + } + let parcelable = new MyParcelable(1, "aaa"); + let data = rpc.MessageSequence.create(); + let result = data.writeParcelable(parcelable); + console.log("RpcClient: writeParcelable is " + result); + let ret = new MyParcelable(0, ""); + let result2 = data.readParcelable(ret); + console.log("RpcClient: readParcelable is " + result2); + ``` + + +### unmarshalling + +unmarshalling(dataIn: MessageSequence): boolean + +Unmarshals this **Parcelable** object from a **MessageSequence** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | --------------- | ---- | ----------------------------------------------- | + | dataIn | MessageSequence | Yes | **MessageSequence** object from which the **Parcelable** object is to be unmarshaled.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + class MyParcelable { + num: number; + str: string; + constructor(num, str) { + this.num = num; + this.str = str; + } + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); + return true; + } + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); + return true; + } + } + let parcelable = new MyParcelable(1, "aaa"); + let data = rpc.MessageSequence.create(); + let result = data.writeParcelable(parcelable); + console.log("RpcClient: writeParcelable is " + result); + let ret = new MyParcelable(0, ""); + let result2 = data.readParcelable(ret); + console.log("RpcClient: readParcelable is " + result2); + ``` + +## Sequenceable(deprecated) + +>This class is no longer maintained since API version 9. You are advised to use the [Parcelable](#parcelable9). + +Writes objects of classes to a **MessageParcel** and reads them from the **MessageParcel** during IPC. ### marshalling @@ -2418,14 +5603,14 @@ Marshals the sequenceable object into a **MessageParcel** object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataOut | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object to which the sequenceable object is to be marshaled.| + | Name | Type | Mandatory| Description | + | ------- | ------------------------------- | ---- | ----------------------------------------- | + | dataOut | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object to which the sequenceable object is to be marshaled.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ----------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -2461,7 +5646,7 @@ Marshals the sequenceable object into a **MessageParcel** object. ### unmarshalling -unmarshalling(dataIn: MessageParcel) : boolean +unmarshalling(dataIn: MessageParcel): boolean Unmarshals this sequenceable object from a **MessageParcel** object. @@ -2469,14 +5654,14 @@ Unmarshals this sequenceable object from a **MessageParcel** object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataIn | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object in which the sequenceable object is to be unmarshaled.| + | Name| Type | Mandatory| Description | + | ------ | ------------------------------- | ---- | --------------------------------------------- | + | dataIn | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object in which the sequenceable object is to be unmarshaled.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | --------------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -2514,7 +5699,6 @@ Unmarshals this sequenceable object from a **MessageParcel** object. Provides the holder of a remote proxy object. - ### asObject asObject(): IRemoteObject @@ -2525,9 +5709,9 @@ Obtains a proxy or remote object. This API must be implemented by its derived cl **Return value** - | Type| Description| - | -------- | -------- | - | [IRemoteObject](#iremoteobject) | Returns the [RemoteObject](#ashmem8) if it is the caller; returns the [IRemoteObject](#iremoteobject), the holder of this **RemoteProxy** object, if the caller is a [RemoteProxy](#remoteproxy) object.| + | Type | Description| + | ---- | ----- | + | [IRemoteObject](#iremoteobject) | Returns the **RemoteObject** if it is the caller; returns the [IRemoteObject](#iremoteobject), the holder of this **RemoteProxy** object, if the caller is a [RemoteProxy](#remoteproxy) object.| **Example** @@ -2553,12 +5737,10 @@ Obtains a proxy or remote object. This API must be implemented by its derived cl } ``` - ## DeathRecipient Subscribes to death notifications of a remote object. When the remote object is dead, the local end will receive a notification and **[onRemoteDied](#onremotedied)** will be called. A remote object is dead when the process holding the object is terminated or the device of the remote object is shut down or restarted. If the local and remote objects belong to different devices, the remote object is dead when the device holding the remote object is detached from the network. - ### onRemoteDied onRemoteDied(): void @@ -2577,27 +5759,61 @@ Called to perform subsequent operations when a death notification of the remote } ``` - -## SendRequestResult8+ +## RequestResult9+ Defines the response to the request. **System capability**: SystemCapability.Communication.IPC.Core - | Parameter| Value| Description| -| -------- | -------- | -------- | -| errCode | number | Error Code| -| code | number | Message code.| -| data | MessageParcel | **MessageParcel** object sent to the remote process.| -| reply | MessageParcel | **MessageParcel** object returned by the remote process.| + | Name | Type | Readable| Writable| Description | + | ------- | --------------- | ---- | ---- |-------------------------------------- | + | errCode | number | Yes | No | Error Code | + | code | number | Yes | No | Message code. | + | data | MessageSequence | Yes | No | **MessageSequence** object sent to the remote process.| + | reply | MessageSequence | Yes | No | **MessageSequence** object returned by the remote process. | + +## SendRequestResult8+(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [RequestResult](#requestresult9). + +Defines the response to the request. + +**System capability**: SystemCapability.Communication.IPC.Core + | Name | Type | Readable| Writable| Description | + | ------- | ------------- | ---- | ---- | ----------------------------------- | + | errCode | number | Yes | No | Error Code | + | code | number | Yes | No | Message code. | + | data | MessageParcel | Yes | No | **MessageParcel** object sent to the remote process.| + | reply | MessageParcel | Yes | No | **MessageParcel** object returned by the remote process. | ## IRemoteObject Provides methods to query of obtain interface descriptors, add or delete death notifications, dump object status to specific files, and send messages. +### getLocalInterface9+ + +getLocalInterface(descriptor: string): IRemoteBroker + +Obtains the interface. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ---------- | ------ | ---- | -------------------- | + | descriptor | string | Yes | Interface descriptor.| + +**Return value** + + | Type | Description | + | ------------- | --------------------------------------------- | + | IRemoteBroker | **IRemoteBroker** object bound to the specified interface token.| -### queryLocalInterface +### queryLocalInterface(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [getLocalInterface](#getlocalinterface9). queryLocalInterface(descriptor: string): IRemoteBroker @@ -2607,23 +5823,22 @@ Obtains the interface. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | descriptor | string | Yes| Interface descriptor.| + | Name | Type | Mandatory| Description | + | ---------- | ------ | ---- | -------------------- | + | descriptor | string | Yes | Interface descriptor.| **Return value** - | Type| Description| - | -------- | -------- | - | IRemoteBroker | **IRemoteBroker** object bound to the specified interface descriptor.| + | Type | Description | + | ------------- | --------------------------------------------- | + | IRemoteBroker | **IRemoteBroker** object bound to the specified interface token.| ### sendRequest(deprecated) -sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean +>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). -> **NOTE**
-> This API is deprecated since API version 8. You are advised to use [sendRequestAsync9+](#sendrequestasync9). +sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption): boolean Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. @@ -2631,26 +5846,25 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| - | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| + | Name | Type| Mandatory| Description | + | ------- | ------------------------------- | ---- | ---- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | + | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | --------------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ### sendRequest8+(deprecated) -sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult> +>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [sendRequestAsync9+](#sendrequestasync9). +sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption): Promise<SendRequestResult> Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. @@ -2658,106 +5872,206 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| - | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| + | Name | Type | Mandatory| Description | + | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | + | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | + +**Return value** + + | Type | Description | + | -------------------------------- | --------------------------------------------- | + | Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.| + + +### sendMessageRequest9+ + +sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption): Promise<RequestResult> + +Sends a **MessageSequence** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendMessageRequest** is returned, and the reply message contains the returned information. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. | + | reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | + +**Return value** + + | Type | Description | + | ---------------------------- | ----------------------------------------- | + | Promise<RequestResult> | Promise used to return the **requestResult** object.| + + +### sendMessageRequest9+ + +sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption, callback: AsyncCallback<RequestResult>): void + +Sends a **MessageSequence** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a callback will be invoked immediately and the reply message does not contain any content. If **options** is the synchronous mode, a callback will be invoked when the response to sendRequest is returned, and the reply message contains the returned information. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------- | ---------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. | + | reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | + | callback | AsyncCallback<RequestResult> | Yes | Callback for receiving the sending result. | + + +### sendRequest8+(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). + +sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback<SendRequestResult>): void + +Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a callback will be invoked immediately and the reply message does not contain any content. If **options** is the synchronous mode, a callback will be invoked when the response to sendRequest is returned, and the reply message contains the returned information. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------- | -------------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | + | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | + | callback | AsyncCallback<SendRequestResult> | Yes | Callback for receiving the sending result. | + + +### registerDeathRecipient9+ + +registerDeathRecipient(recipient: DeathRecipient, flags: number): void + +Adds a callback for receiving death notifications of the remote object. This method is called if the remote object process matching the **RemoteProxy** object is killed. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | --------- | --------------------------------- | ---- | -------------- | + | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to add.| + | flags | number | Yes | Flag of the death notification.| + +**Error Code** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900008 | proxy or remote object is invalid | -**Return value** - | Type| Description| - | -------- | -------- | - | Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.| +### addDeathrecipient(deprecated) -### sendRequestAsync9+ +>This API is no longer maintained since API version 9. You are advised to use [registerDeathRecipient](#registerdeathrecipient9). -sendRequestAsync(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult> +addDeathRecipient(recipient: DeathRecipient, flags: number): boolean -Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequestAsync** is returned, and the reply message contains the returned information. +Adds a callback for receiving death notifications of the remote object. This method is called if the remote object process matching the **RemoteProxy** object is killed. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| - | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| + | Name | Type | Mandatory| Description | + | --------- | --------------------------------- | ---- | -------------- | + | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to add.| + | flags | number | Yes | Flag of the death notification.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.| + | Type | Description | + | ------- | --------------------------------------------- | + | boolean | Returns **true** if the callback is added successfully; returns **false** otherwise.| -### sendRequest8+ -sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback<SendRequestResult>): void +### unregisterDeathRecipient9+ -Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a callback will be invoked immediately and the reply message does not contain any content. If **options** is the synchronous mode, a callback will be invoked when the response to sendRequest is returned, and the reply message contains the returned information. +unregisterDeathRecipient(recipient: DeathRecipient, flags: number): void + +Removes the callback used to receive death notifications of the remote object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| - | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| - | callback | AsyncCallback<SendRequestResult> | Yes| Callback for receiving the sending result.| + | Name | Type | Mandatory| Description | + | --------- | --------------------------------- | ---- | -------------- | + | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to remove.| + | flags | number | Yes | Flag of the death notification.| +**Error Code** -### addDeathrecipient +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). -addDeathRecipient(recipient: DeathRecipient, flags: number): boolean + | ID| Error Message| + | ------- | -------- | + | 1900008 | proxy or remote object is invalid | -Adds a callback for receiving death notifications of the remote object. This method is called if the remote object process matching the **RemoteProxy** object is killed. + +### removeDeathRecipient(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [unregisterDeathRecipient](#unregisterdeathrecipient9). + +removeDeathRecipient(recipient: DeathRecipient, flags: number): boolean + +Removes the callback used to receive death notifications of the remote object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | recipient | [DeathRecipient](#deathrecipient) | Yes| Callback to add.| - | flags | number | Yes| Flag of the death notification.| + | Name | Type | Mandatory| Description | + | --------- | --------------------------------- | ---- | -------------- | + | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to remove.| + | flags | number | Yes | Flag of the death notification.| **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the callback is added successfully; returns **false** otherwise.| + | Type | Description | + | ------- | --------------------------------------------- | + | boolean | Returns **true** if the callback is removed successfully; returns **false** otherwise.| -### removeDeathRecipient +### getDescriptor9+ -removeDeathRecipient(recipient: DeathRecipient, flags: number): boolean +getDescriptor(): string -Removes the callback used to receive death notifications of the remote object. +Obtains the interface descriptor of this object. The interface descriptor is a string. **System capability**: SystemCapability.Communication.IPC.Core -**Parameters** +**Return value** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | recipient | [DeathRecipient](#deathrecipient) | Yes| Callback to remove.| - | flags | number | Yes| Flag of the death notification.| + | Type | Description | + | ------ | ---------------- | + | string | Interface descriptor obtained.| -**Return value** +**Error Code** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the callback is removed successfully; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900008 | proxy or remote object is invalid | -### getInterfaceDescriptor +### getInterfaceDescriptor(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [getDescriptor](#getdescriptor9). getInterfaceDescriptor(): string @@ -2767,8 +6081,8 @@ Obtains the interface descriptor of this object. The interface descriptor is a s **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ---------------- | | string | Interface descriptor obtained.| @@ -2782,34 +6096,31 @@ Checks whether this object is dead. **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ------------------------------------------- | | boolean | Returns **true** if the object is dead; returns **false** otherwise.| ## RemoteProxy -Provides methods to implement **IRemoteObject**. +Provides APIs to implement **IRemoteObject**. **System capability**: SystemCapability.Communication.IPC.Core -| Parameter | Value | Description | +| Name | Value | Description | | --------------------- | ----------------------- | --------------------------------- | | PING_TRANSACTION | 1599098439 (0x5f504e47) | Internal instruction code used to test whether the IPC service is normal.| -| DUMP_TRANSACTION | 1598311760 (0x5f444d50) | Internal instruction code used to obtain the internal status of the binder.| -| INTERFACE_TRANSACTION | 1598968902 (0x5f4e5446) | Internal instruction code used to obtain the remote interface descriptor. | +| DUMP_TRANSACTION | 1598311760 (0x5f444d50) | Internal instruction code used to obtain the internal status of the binder. | +| INTERFACE_TRANSACTION | 1598968902 (0x5f4e5446) | Internal instruction code used to obtain the remote interface token. | | MIN_TRANSACTION_ID | 1 (0x00000001) | Minimum valid instruction code. | | MAX_TRANSACTION_ID | 16777215 (0x00FFFFFF) | Maximum valid instruction code. | - - ### sendRequest(deprecated) -sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean +>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). -> **NOTE**
-> This API is deprecated since API version 8. You are advised to use [sendRequestAsync9+](#sendrequestasync9-1). +sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption): boolean Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. @@ -2817,20 +6128,19 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| - | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| + | Name | Type | Mandatory| Description | + | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | + | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | --------------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - **Example** ``` @@ -2871,12 +6181,82 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch reply.reclaim(); ``` + +### sendMessageRequest9+ + +sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption): Promise<RequestResult> + +Sends a **MessageSequence** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendMessageRequest** is returned, and the reply message contains the returned information. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. | + | reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | + +**Return value** + + | Type | Description | + | ---------------------------- | ----------------------------------------- | + | Promise<RequestResult> | Promise used to return the **requestResult** object.| + +**Example** + + ``` + import FA from "@ohos.ability.featureAbility"; + let proxy; + let connect = { + onConnect: function(elementName, remoteProxy) { + console.log("RpcClient: js onConnect called."); + proxy = remoteProxy; + }, + onDisconnect: function(elementName) { + console.log("RpcClient: onDisconnect"); + }, + onFailed: function() { + console.log("RpcClient: onFailed"); + } + }; + let want = { + "bundleName": "com.ohos.server", + "abilityName": "com.ohos.server.MainAbility", + }; + FA.connectAbility(want, connect); + let option = new rpc.MessageOption(); + let data = rpc.MessageSequence.create(); + let reply = rpc.MessageSequence.create(); + data.writeInt(1); + data.writeString("hello"); + proxy.sendMessageRequest(1, data, reply, option) + .then(function(result) { + if (result.errCode === 0) { + console.log("sendMessageRequest got result"); + result.reply.readException(); + let msg = result.reply.readString(); + console.log("RPCTest: reply msg: " + msg); + } else { + console.log("RPCTest: sendMessageRequest failed, errCode: " + result.errCode); + } + }).catch(function(e) { + console.log("RPCTest: sendMessageRequest got exception: " + e.message); + }).finally (() => { + console.log("RPCTest: sendMessageRequest ends, reclaim parcel"); + data.reclaim(); + reply.reclaim(); + }); + ``` + + ### sendRequest8+(deprecated) -sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult> +>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [sendRequestAsync9+](#sendrequestasync9-1). +sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption): Promise<SendRequestResult> Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. @@ -2884,17 +6264,17 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| - | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| + | Name | Type | Mandatory| Description | + | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | + | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | -------------------------------- | --------------------------------------------- | | Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.| **Example** @@ -2943,28 +6323,219 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch }); ``` -### sendRequestAsync9+ +### sendMessageRequest9+ + +sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption, callback: AsyncCallback<RequestResult>): void + +Sends a **MessageSequence** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a callback will be invoked immediately and the reply message does not contain any content. If **options** is the synchronous mode, a callback will be invoked at certain time after the response to **sendMessageRequest** is returned, and the reply contains the returned information. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------- | ---------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. | + | reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | + | callback | AsyncCallback<RequestResult> | Yes | Callback for receiving the sending result. | + + +**Example** + + ``` + import FA from "@ohos.ability.featureAbility"; + let proxy; + let connect = { + onConnect: function(elementName, remoteProxy) { + console.log("RpcClient: js onConnect called."); + proxy = remoteProxy; + }, + onDisconnect: function(elementName) { + console.log("RpcClient: onDisconnect"); + }, + onFailed: function() { + console.log("RpcClient: onFailed"); + } + }; + let want = { + "bundleName": "com.ohos.server", + "abilityName": "com.ohos.server.MainAbility", + }; + function sendRequestCallback(result) { + if (result.errCode === 0) { + console.log("sendRequest got result"); + result.reply.readException(); + let msg = result.reply.readString(); + console.log("RPCTest: reply msg: " + msg); + } else { + console.log("RPCTest: sendRequest failed, errCode: " + result.errCode); + } + console.log("RPCTest: sendRequest ends, reclaim parcel"); + result.data.reclaim(); + result.reply.reclaim(); + } + FA.connectAbility(want, connect); + let option = new rpc.MessageOption(); + let data = rpc.MessageSequence.create(); + let reply = rpc.MessageSequence.create(); + data.writeInt(1); + data.writeString("hello"); + try { + proxy.sendRequest(1, data, reply, option, sendRequestCallback); + } catch(error) { + console.info("rpc send sequence request fail, errorCode " + error.code); + console.info("rpc send sequence request fail, errorMessage " + error.message); + } + ``` + + +### sendRequest8+(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). + +sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback<SendRequestResult>): void + +Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a callback will be invoked immediately and the reply message does not contain any content. If **options** is the synchronous mode, a callback will be invoked when the response to sendRequest is returned, and the reply message contains the returned information. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------- | -------------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | + | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | + | callback | AsyncCallback<SendRequestResult> | Yes | Callback for receiving the sending result. | + +**Example** + + ``` + import FA from "@ohos.ability.featureAbility"; + let proxy; + let connect = { + onConnect: function(elementName, remoteProxy) { + console.log("RpcClient: js onConnect called."); + proxy = remoteProxy; + }, + onDisconnect: function(elementName) { + console.log("RpcClient: onDisconnect"); + }, + onFailed: function() { + console.log("RpcClient: onFailed"); + } + }; + let want = { + "bundleName": "com.ohos.server", + "abilityName": "com.ohos.server.MainAbility", + }; + function sendRequestCallback(result) { + if (result.errCode === 0) { + console.log("sendRequest got result"); + result.reply.readException(); + let msg = result.reply.readString(); + console.log("RPCTest: reply msg: " + msg); + } else { + console.log("RPCTest: sendRequest failed, errCode: " + result.errCode); + } + console.log("RPCTest: sendRequest ends, reclaim parcel"); + result.data.reclaim(); + result.reply.reclaim(); + } + FA.connectAbility(want, connect); + let option = new rpc.MessageOption(); + let data = rpc.MessageParcel.create(); + let reply = rpc.MessageParcel.create(); + data.writeInt(1); + data.writeString("hello"); + proxy.sendRequest(1, data, reply, option, sendRequestCallback); + ``` + + +### getLocalInterface9+ + +getLocalInterface(interface: string): IRemoteBroker + +Obtains the **LocalInterface** object of an interface token. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | --------- | ------ | ---- | ---------------------- | + | interface | string | Yes | Interface descriptor.| + +**Return value** + + | Type | Description | + | ------------- | ------------------------------------------ | + | IRemoteBroker | Returns **Null** by default, which indicates a proxy interface.| + +**Error Code** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900006 | only remote object permitted | + +**Example** + + ``` + import FA from "@ohos.ability.featureAbility"; + let proxy; + let connect = { + onConnect: function(elementName, remoteProxy) { + console.log("RpcClient: js onConnect called."); + proxy = remoteProxy; + }, + onDisconnect: function (elementName) { + console.log("RpcClient: onDisconnect"); + }, + onFailed: function() { + console.log("RpcClient: onFailed"); + } + }; + let want = { + "bundleName":"com.ohos.server", + "abilityName":"com.ohos.server.MainAbility", + }; + FA.connectAbility(want, connect); + try { + let broker = proxy.getLocalInterface("testObject"); + console.log("RpcClient: getLocalInterface is " + broker); + } catch(error) { + console.info("rpc get local interface fail, errorCode " + error.code); + console.info("rpc get local interface fail, errorMessage " + error.message); + } + ``` + + +### queryLocalInterface(deprecated) -sendRequestAsync(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult> +>This API is no longer maintained since API version 9. You are advised to use [getLocalInterface](#getlocalinterface9). + +queryLocalInterface(interface: string): IRemoteBroker -Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequestAsync** is returned, and the reply message contains the returned information. +Obtains the **LocalInterface** object of an interface token. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| - | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| + | Name | Type | Mandatory| Description | + | --------- | ------ | ---- | ---------------------- | + | interface | string | Yes | Interface descriptor.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.| + | Type | Description | + | ------------- | ------------------------------------------ | + | IRemoteBroker | Returns **Null** by default, which indicates a proxy interface.| **Example** @@ -2976,7 +6547,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch console.log("RpcClient: js onConnect called."); proxy = remoteProxy; }, - onDisconnect: function(elementName) { + onDisconnect: function (elementName) { console.log("RpcClient: onDisconnect"); }, onFailed: function() { @@ -2984,51 +6555,37 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch } }; let want = { - "bundleName": "com.ohos.server", - "abilityName": "com.ohos.server.MainAbility", + "bundleName":"com.ohos.server", + "abilityName":"com.ohos.server.MainAbility", }; FA.connectAbility(want, connect); - let option = new rpc.MessageOption(); - let data = rpc.MessageParcel.create(); - let reply = rpc.MessageParcel.create(); - data.writeInt(1); - data.writeString("hello"); - proxy.sendRequestAsync(1, data, reply, option) - .then(function(result) { - if (result.errCode === 0) { - console.log("sendRequestAsync got result"); - result.reply.readException(); - let msg = result.reply.readString(); - console.log("RPCTest: reply msg: " + msg); - } else { - console.log("RPCTest: sendRequestAsync failed, errCode: " + result.errCode); - } - }).catch(function(e) { - console.log("RPCTest: sendRequestAsync got exception: " + e.message); - }).finally (() => { - console.log("RPCTest: sendRequestAsync ends, reclaim parcel"); - data.reclaim(); - reply.reclaim(); - }); + let broker = proxy.queryLocalInterface("testObject"); + console.log("RpcClient: queryLocalInterface is " + broker); ``` -### sendRequest8+ -sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback<SendRequestResult>): void +### registerDeathRecipient9+ -Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a callback will be invoked immediately and the reply message does not contain any content. If **options** is the synchronous mode, a callback will be invoked when the response to sendRequest is returned, and the reply message contains the returned information. +registerDeathRecipient(recipient: DeathRecipient, flags: number): void + +Adds a callback for receiving death notifications of the remote object. This method is called if the remote object process matching the **RemoteProxy** object is killed. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| - | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| - | callback | AsyncCallback<SendRequestResult> | Yes| Callback for receiving the sending result.| + | Name | Type | Mandatory| Description | + | --------- | --------------------------------- | ---- | -------------- | + | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to add.| + | flags | number | Yes | Flag of the death notification.| + +**Error Code** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900008 | proxy or remote object is invalid | **Example** @@ -3051,48 +6608,44 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch "bundleName": "com.ohos.server", "abilityName": "com.ohos.server.MainAbility", }; - function sendRequestCallback(result) { - if (result.errCode === 0) { - console.log("sendRequest got result"); - result.reply.readException(); - let msg = result.reply.readString(); - console.log("RPCTest: reply msg: " + msg); - } else { - console.log("RPCTest: sendRequest failed, errCode: " + result.errCode); + FA.connectAbility(want, connect); + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); } - console.log("RPCTest: sendRequest ends, reclaim parcel"); - result.data.reclaim(); - result.reply.reclaim(); } - FA.connectAbility(want, connect); - let option = new rpc.MessageOption(); - let data = rpc.MessageParcel.create(); - let reply = rpc.MessageParcel.create(); - data.writeInt(1); - data.writeString("hello"); - proxy.sendRequest(1, data, reply, option, sendRequestCallback); + let deathRecipient = new MyDeathRecipient(); + try { + proxy.registerDeathRecippient(deathRecipient, 0); + } catch(error) { + console.info("proxy register deathRecipient fail, errorCode " + error.code); + console.info("proxy register deathRecipient fail, errorMessage " + error.message); + } ``` -### queryLocalInterface +### addDeathRecippient(deprecated) -queryLocalInterface(interface: string): IRemoteBroker +>This API is no longer maintained since API version 9. You are advised to use [registerDeathRecipient](#registerdeathrecipient9). + +addDeathRecipient(recipient: DeathRecipient, flags: number): boolean -Obtains the **LocalInterface** object of an interface descriptor. +Adds a callback for receiving the death notifications of the remote object, including the death notifications of the remote proxy. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | interface | string | Yes| Interface descriptor.| + | Name | Type | Mandatory| Description | + | --------- | --------------------------------- | ---- | --------------------------------- | + | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to add. | + | flags | number | Yes | Flag of the death notification. This parameter is reserved. It is set to **0**.| **Return value** - | Type| Description| - | -------- | -------- | - | IRemoteBroker | Returns **Null** by default, which indicates a proxy interface.| + | Type | Description | + | ------- | --------------------------------------------- | + | boolean | Returns **true** if the callback is added successfully; returns **false** otherwise.| **Example** @@ -3104,7 +6657,7 @@ Obtains the **LocalInterface** object of an interface descriptor. console.log("RpcClient: js onConnect called."); proxy = remoteProxy; }, - onDisconnect: function (elementName) { + onDisconnect: function(elementName) { console.log("RpcClient: onDisconnect"); }, onFailed: function() { @@ -3112,35 +6665,41 @@ Obtains the **LocalInterface** object of an interface descriptor. } }; let want = { - "bundleName":"com.ohos.server", - "abilityName":"com.ohos.server.MainAbility", + "bundleName": "com.ohos.server", + "abilityName": "com.ohos.server.MainAbility", }; FA.connectAbility(want, connect); - let broker = proxy.queryLocalInterface("testObject"); - console.log("RpcClient: queryLocalInterface is " + broker); + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } + let deathRecipient = new MyDeathRecipient(); + proxy.addDeathRecippient(deathRecipient, 0); ``` +### unregisterDeathRecipient9+ -### addDeathRecippient +unregisterDeathRecipient(recipient: DeathRecipient, flags: number): boolean -addDeathRecipient(recipient : DeathRecipient, flags : number): boolean - -Adds a callback for receiving the death notifications of the remote object, including the death notifications of the remote proxy. +Removes the callback used to receive death notifications of the remote object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | recipient | [DeathRecipient](#deathrecipient) | Yes| Callback to add.| - | flags | number | Yes| Flag of the death notification. This parameter is reserved. It is set to **0**.| + | Name | Type | Mandatory| Description | + | --------- | --------------------------------- | ---- | -------------- | + | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to remove.| + | flags | number | Yes | Flag of the death notification.| -**Return value** +**Error Code** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the callback is added successfully; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900008 | proxy or remote object is invalid | **Example** @@ -3170,13 +6729,21 @@ Adds a callback for receiving the death notifications of the remote object, incl } } let deathRecipient = new MyDeathRecipient(); - proxy.addDeathRecippient(deathRecipient, 0); + try { + proxy.registerDeathRecippient(deathRecipient, 0); + proxy.unregisterDeathRecippient(deathRecipient, 0); + } catch(error) { + console.info("proxy register deathRecipient fail, errorCode " + error.code); + console.info("proxy register deathRecipient fail, errorMessage " + error.message); + } ``` -### removeDeathRecipient +### removeDeathRecipient(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [unregisterDeathRecipient](#unregisterdeathrecipient9). -removeDeathRecipient(recipient : DeathRecipient, flags : number): boolean +removeDeathRecipient(recipient: DeathRecipient, flags: number): boolean Removes the callback used to receive death notifications of the remote object. @@ -3184,15 +6751,15 @@ Removes the callback used to receive death notifications of the remote object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | recipient | [DeathRecipient](#deathrecipient) | Yes| Callback to remove.| - | flags | number | Yes| Flag of the death notification. This parameter is reserved. It is set to **0**.| + | Name | Type | Mandatory| Description | + | --------- | --------------------------------- | ---- | --------------------------------- | + | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to remove. | + | flags | number | Yes | Flag of the death notification. This parameter is reserved. It is set to **0**.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | --------------------------------------------- | | boolean | Returns **true** if the callback is removed successfully; returns **false** otherwise.| **Example** @@ -3228,7 +6795,64 @@ Removes the callback used to receive death notifications of the remote object. ``` -### getInterfaceDescriptor +### getDescriptor9+ + +getDescriptor(): string + +Obtains the interface descriptor of this object. The interface descriptor is a string. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | ---------------- | + | string | Interface descriptor obtained.| + +**Error Code** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | -------- | ------- | + | 1900008 | proxy or remote object is invalid | + | 1900007 | communication failed | + +**Example** + + ``` + import FA from "@ohos.ability.featureAbility"; + let proxy; + let connect = { + onConnect: function(elementName, remoteProxy) { + console.log("RpcClient: js onConnect called."); + proxy = remoteProxy; + }, + onDisconnect: function(elementName) { + console.log("RpcClient: onDisconnect"); + }, + onFailed: function() { + console.log("RpcClient: onFailed"); + } + }; + let want = { + "bundleName": "com.ohos.server", + "abilityName": "com.ohos.server.MainAbility", + }; + FA.connectAbility(want, connect); + try { + let descriptor = proxy.getDescriptor(); + console.log("RpcClient: descriptor is " + descriptor); + } catch(error) { + console.info("rpc get interface descriptor fail, errorCode " + error.code); + console.info("rpc get interface descriptor fail, errorMessage " + error.message); + } + ``` + + +### getInterfaceDescriptor(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [getDescriptor](#getdescriptor9). getInterfaceDescriptor(): string @@ -3238,8 +6862,8 @@ Obtains the interface descriptor of this proxy object. **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ------------------ | | string | Interface descriptor obtained.| **Example** @@ -3279,8 +6903,8 @@ Checks whether the **RemoteObject** is dead. **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | --------------------------------------------------------- | | boolean | Returns **true** if the **RemoteObject** is dead; returns **false** otherwise.| **Example** @@ -3312,21 +6936,36 @@ Checks whether the **RemoteObject** is dead. ## MessageOption -Provides common message options (flag and wait time). The flag is used to construct the specified **MessageOption** object. +Provides common message options (flag and wait time). Use the specified flag to construct the **MessageOption** object. + +**System capability**: SystemCapability.Communication.IPC.Core + + | Name | Value | Description | + | ------------- | ---- | ----------------------------------------------------------- | + | TF_SYNC | 0 | Synchronous call. | + | TF_ASYNC | 1 | Asynchronous call. | + | TF_ACCEPT_FDS | 0x10 | Indication to **sendMessageRequest9+** for returning the file descriptor.| + | TF_WAIT_TIME | 8 | Default waiting time, in seconds. | + + +### constructor9+ + +constructor(async?: boolean); + +A constructor used to create a **MessageOption** object. **System capability**: SystemCapability.Communication.IPC.Core - | Parameter| Value| Description| -| -------- | -------- | -------- | -| TF_SYNC | 0 | Synchronous call.| -| TF_ASYNC | 1 | Asynchronous call.| -| TF_ACCEPT_FDS | 0x10 | Indication to [sendRequestAsync](#sendrequestasync9) for returning the file descriptor.| -| TF_WAIT_TIME | 8 | Time to wait, in seconds.| +**Parameters** + + | Name | Type | Mandatory| Description | + | --------- | ------ | ---- | -------------------------------------- | + | syncFlags | number | No | Call flag, which can be synchronous or asynchronous. The default value is **synchronous**.| ### constructor -constructor(syncFlags?: number, waitTime = TF_WAIT_TIME) +constructor(syncFlags?: number, waitTime?: number) A constructor used to create a **MessageOption** object. @@ -3334,10 +6973,34 @@ A constructor used to create a **MessageOption** object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | syncFlags | number | No| Call flag, which can be synchronous or asynchronous. The default value is **synchronous**.| - | waitTime | number | No| Maximum wait time for an RPC call. The default value is **TF_WAIT_TIME**.| + | Name | Type | Mandatory| Description | + | --------- | ------ | ---- | --------------------------------------------- | + | syncFlags | number | No | Call flag, which can be synchronous or asynchronous. The default value is **synchronous**. | + | waitTime | number | No | Maximum wait time for an RPC call. The default value is **TF_WAIT_TIME**.| + + +### isAsync9+ + +isAsync(): boolean; + +Checks whether **SendMessageRequest** is called synchronously or asynchronously. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------- | ------------------------------------ | + | boolean | Call mode obtained.| + + +### setAsync9+ + +setAsync(async: boolean): void; + +Sets whether **SendMessageRequest** is called synchronously or asynchronously. + +**System capability**: SystemCapability.Communication.IPC.Core ### getFlags @@ -3350,8 +7013,8 @@ Obtains the call flag, which can be synchronous or asynchronous. **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ------------------------------------ | | number | Call mode obtained.| @@ -3365,9 +7028,9 @@ Sets the call flag, which can be synchronous or asynchronous. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | flags | number | Yes| Call flag to set.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------------ | + | flags | number | Yes | Call flag to set.| ### getWaitTime @@ -3380,8 +7043,8 @@ Obtains the maximum wait time for this RPC call. **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ----------------- | | number | Maximum wait time obtained.| @@ -3395,16 +7058,15 @@ Sets the maximum wait time for this RPC call. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | waitTime | number | Yes| Maximum wait time to set.| + | Name | Type | Mandatory| Description | + | -------- | ------ | ---- | --------------------- | + | waitTime | number | Yes | Maximum wait time to set.| ## IPCSkeleton Obtains IPC context information, including the UID and PID, local and remote device IDs, and whether the method is invoked on the same device. - ### getContextObject static getContextObject(): IRemoteObject @@ -3415,8 +7077,8 @@ Obtains the system capability manager. **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------------------- | -------------------- | | [IRemoteObject](#iremoteobject) | System capability manager obtained.| **Example** @@ -3437,20 +7099,20 @@ Obtains the PID of the caller. This method is invoked by the **RemoteObject** ob **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ----------------- | | number | PID of the caller.| **Example** ``` class Stub extends rpc.RemoteObject { - onRemoteRequest(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let callerPid = rpc.IPCSkeleton.getCallingPid(); console.log("RpcServer: getCallingPid result: " + callerPid); return true; } - } + } ``` @@ -3464,15 +7126,15 @@ Obtains the UID of the caller. This method is invoked by the **RemoteObject** ob **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ----------------- | | number | UID of the caller.| **Example** ``` class Stub extends rpc.RemoteObject { - onRemoteRequest(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let callerUid = rpc.IPCSkeleton.getCallingUid(); console.log("RpcServer: getCallingUid result: " + callerUid); return true; @@ -3480,6 +7142,7 @@ Obtains the UID of the caller. This method is invoked by the **RemoteObject** ob } ``` + ### getCallingTokenId8+ static getCallingTokenId(): number; @@ -3488,17 +7151,18 @@ Obtains the caller's token ID, which is used to verify the caller identity. **System capability**: SystemCapability.Communication.IPC.Core -* Return value - - | Type | Description | - | ------ | --------------------- | - | number | Token ID of the caller obtained.| -* Example +**Return value** + + | Type | Description | + | ------ | --------------------- | + | number | Token ID of the caller obtained.| + +**Example** ``` class Stub extends rpc.RemoteObject { - onRemoteRequest(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let callerTokenId = rpc.IPCSkeleton.getCallingTokenId(); console.log("RpcServer: getCallingTokenId result: " + callerTokenId); return true; @@ -3517,15 +7181,15 @@ Obtains the ID of the device hosting the caller's process. **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ---------------------------- | | string | Device ID obtained.| **Example** ``` class Stub extends rpc.RemoteObject { - onRemoteRequest(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let callerDeviceID = rpc.IPCSkeleton.getCallingDeviceID(); console.log("RpcServer: callerDeviceID is: " + callerDeviceID); return true; @@ -3544,15 +7208,15 @@ Obtains the local device ID. **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ------------------ | | string | Local device ID obtained.| **Example** ``` class Stub extends rpc.RemoteObject { - onRemoteRequest(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let localDeviceID = rpc.IPCSkeleton.getLocalDeviceID(); console.log("RpcServer: localDeviceID is: " + localDeviceID); return true; @@ -3571,15 +7235,15 @@ Checks whether the remote process is a process of the local device. **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | --------------------------------------------------------- | | boolean | Returns **true** if the local and remote processes are on the same device; returns **false** otherwise.| **Example** ``` class Stub extends rpc.RemoteObject { - onRemoteRequest(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let isLocalCalling = rpc.IPCSkeleton.isLocalCalling(); console.log("RpcServer: isLocalCalling is: " + isLocalCalling); return true; @@ -3588,9 +7252,9 @@ Checks whether the remote process is a process of the local device. ``` -### flushCommands +### flushCmdBuffer9+ -static flushCommands(object : IRemoteObject): number +static flushCmdBuffer(object: IRemoteObject): void Flushes all suspended commands from the specified **RemoteProxy** to the corresponding **RemoteObject**. It is recommended that this method be called before any time-sensitive operation is performed. @@ -3598,15 +7262,49 @@ Flushes all suspended commands from the specified **RemoteProxy** to the corresp **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | object | [IRemoteObject](#iremoteobject) | Yes| **RemoteProxy** specified. | + | Name| Type | Mandatory| Description | + | ------ | ------------------------------- | ---- | ------------------- | + | object | [IRemoteObject](#iremoteobject) | Yes | **RemoteProxy** specified. | + + +**Example** + + ``` + class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + } + } + let remoteObject = new TestRemoteObject("aaa"); + try { + rpc.IPCSkeleton.flushCmdBuffer(remoteObject); + } catch(error) { + console.info("proxy set calling identity fail, errorCode " + error.code); + console.info("proxy set calling identity fail, errorMessage " + error.message); + } + ``` + + +### flushCommands(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [flushCmdBuffer](#flushcmdbuffer9). + +static flushCommands(object: IRemoteObject): number +Flushes all suspended commands from the specified **RemoteProxy** to the corresponding **RemoteObject**. It is recommended that this method be called before any time-sensitive operation is performed. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------------------------------- | ---- | ------------------- | + | object | [IRemoteObject](#iremoteobject) | Yes | **RemoteProxy** specified. | **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | --------------------------------------------------------------------------------- | | number | Returns **0** if the operation is successful; returns an error code if the input object is null or a **RemoteObject**, or if the operation fails.| **Example** @@ -3636,37 +7334,70 @@ Flushes all suspended commands from the specified **RemoteProxy** to the corresp console.log("RpcServer: flushCommands result: " + ret); ``` - ### resetCallingIdentity -static resetCallingIdentity(): string +static resetCallingIdentity(): string + +Changes the UID and PID of the remote user to the UID and PID of the local user. This method is used in scenarios such as identity authentication. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | ------------------------------------ | + | string | String containing the UID and PID of the remote user.| + +**Example** + + ``` + class Stub extends rpc.RemoteObject { + onRemoteMessageRequest(code, data, reply, option) { + let callingIdentity = rpc.IPCSkeleton.resetCallingIdentity(); + console.log("RpcServer: callingIdentity is: " + callingIdentity); + return true; + } + } + ``` + + +### restoreCallingIdentity9+ + +static restoreCallingIdentity(identity: string): void Changes the UID and PID of the remote user to the UID and PID of the local user. This method is used in scenarios such as identity authentication. **System capability**: SystemCapability.Communication.IPC.Core -**Return value** +**Parameters** - | Type| Description| - | -------- | -------- | - | string | String containing the UID and PID of the remote user.| + | Name | Type | Mandatory| Description | + | -------- | ------ | ---- | ------------------------------------------------------------------ | + | identity | string | Yes | String containing the remote user UID and PID, which are returned by **resetCallingIdentity**.| **Example** ``` class Stub extends rpc.RemoteObject { - onRemoteRequest(code, data, reply, option) { - let callingIdentity = rpc.IPCSkeleton.resetCallingIdentity(); - console.log("RpcServer: callingIdentity is: " + callingIdentity); + onRemoteMessageRequest(code, data, reply, option) { + let callingIdentity = null; + try { + callingIdentity = rpc.IPCSkeleton.resetCallingIdentity(); + console.log("RpcServer: callingIdentity is: " + callingIdentity); + } finally { + rpc.IPCSkeleton.restoreCallingIdentity("callingIdentity "); + } return true; } } ``` -### setCallingIdentity +### setCallingIdentity(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [restoreCallingIdentity](#restorecallingidentity9). -static setCallingIdentity(identity : string): boolean +static setCallingIdentity(identity: string): boolean Restores the UID and PID of the remote user. It is usually called when the UID and PID of the remote user are required. The UID and PID of the remote user are returned by **resetCallingIdentity**. @@ -3674,21 +7405,21 @@ Restores the UID and PID of the remote user. It is usually called when the UID a **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | identity | string | Yes| String containing the remote user UID and PID, which are returned by **resetCallingIdentity**.| + | Name | Type | Mandatory| Description | + | -------- | ------ | ---- | ------------------------------------------------------------------ | + | identity | string | Yes | String containing the remote user UID and PID, which are returned by **resetCallingIdentity**.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ----------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** ``` class Stub extends rpc.RemoteObject { - onRemoteRequest(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let callingIdentity = null; try { callingIdentity = rpc.IPCSkeleton.resetCallingIdentity(); @@ -3707,7 +7438,6 @@ Restores the UID and PID of the remote user. It is usually called when the UID a Provides methods to implement **RemoteObject**. The service provider must inherit from this class. - ### constructor constructor(descriptor: string) @@ -3718,17 +7448,16 @@ A constructor used to create a **RemoteObject** object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | descriptor | string | Yes| Interface descriptor.| + | Name | Type | Mandatory| Description | + | ---------- | ------ | ---- | ------------ | + | descriptor | string | Yes | Interface descriptor.| ### sendRequest(deprecated) -sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean +>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). -> **NOTE**
-> This API is deprecated since API version 8. You are advised to use [sendRequestAsync9+](#sendrequestasync9-2). +sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption): boolean Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. @@ -3736,20 +7465,19 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| - | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| + | Name | Type | Mandatory| Description | + | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | + | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | --------------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - **Example** ``` @@ -3794,10 +7522,9 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch ### sendRequest8+(deprecated) -sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult> +>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [sendRequestAsync9+](#sendrequestasync9-2). +sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption): Promise<SendRequestResult> Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. @@ -3805,20 +7532,19 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| - | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| + | Name | Type | Mandatory| Description | + | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | + | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | -------------------------------- | --------------------------------------------- | | Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.| - **Example** ``` @@ -3866,77 +7592,115 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch }); ``` -### sendRequestAsync9+ +### sendMessageRequest9+ -sendRequestAsync(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult> +sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption): Promise<RequestResult> -Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequestAsync** is returned, and the reply message contains the returned information. +Sends a **MessageSequence** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendMessageRequest** is returned, and the reply message contains the returned information. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| - | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| + | Name | Type | Mandatory| Description | + | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. | + | reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | **Return value** - | Type| Description| - | -------- | -------- | - | Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.| + | Type | Description | + | ---------------------------- | --------------------------------------------- | + | Promise<RequestResult> | Promise used to return the **sendRequestResult** object.| **Example** ``` - class MyDeathRecipient { - onRemoteDied() { - console.log("server died"); - } - } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - isObjectDead(): boolean { - return false; - } } let testRemoteObject = new TestRemoteObject("testObject"); let option = new rpc.MessageOption(); - let data = rpc.MessageParcel.create(); - let reply = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); + let reply = rpc.MessageSequence.create(); data.writeInt(1); data.writeString("hello"); - testRemoteObject.sendRequestAsync(1, data, reply, option) + testRemoteObject.sendMessageRequest(1, data, reply, option) .then(function(result) { if (result.errCode === 0) { - console.log("sendRequestAsync got result"); + console.log("sendMessageRequest got result"); result.reply.readException(); let msg = result.reply.readString(); console.log("RPCTest: reply msg: " + msg); } else { - console.log("RPCTest: sendRequestAsync failed, errCode: " + result.errCode); + console.log("RPCTest: sendMessageRequest failed, errCode: " + result.errCode); } }).catch(function(e) { - console.log("RPCTest: sendRequestAsync got exception: " + e.message); + console.log("RPCTest: sendMessageRequest got exception: " + e.message); }).finally (() => { - console.log("RPCTest: sendRequestAsync ends, reclaim parcel"); + console.log("RPCTest: sendMessageRequest ends, reclaim parcel"); data.reclaim(); reply.reclaim(); }); ``` -### sendRequest8+ + +### sendMessageRequest9+ + +sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption, callback: AsyncCallback<RequestResult>): void + +Sends a **MessageSequence** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a callback will be invoked immediately and the reply message does not contain any content. If **options** is the synchronous mode, a callback will be invoked when the response to **sendMessageRequest** is returned, and the reply message contains the returned information. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ------------- | ---------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. | + | reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | + | AsyncCallback | AsyncCallback<RequestResult> | Yes | Callback for receiving the sending result. | + +**Example** + + ``` + class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + } + } + function sendRequestCallback(result) { + if (result.errCode === 0) { + console.log("sendRequest got result"); + result.reply.readException(); + let msg = result.reply.readString(); + console.log("RPCTest: reply msg: " + msg); + } else { + console.log("RPCTest: sendRequest failed, errCode: " + result.errCode); + } + console.log("RPCTest: sendRequest ends, reclaim parcel"); + result.data.reclaim(); + result.reply.reclaim(); + } + let testRemoteObject = new TestRemoteObject("testObject"); + let option = new rpc.MessageOption(); + let data = rpc.MessageSequence.create(); + let reply = rpc.MessageSequence.create(); + data.writeInt(1); + data.writeString("hello"); + testRemoteObject.sendMessageRequest(1, data, reply, option, sendRequestCallback); + ``` + + +### sendRequest8+(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback<SendRequestResult>): void @@ -3946,14 +7710,13 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| - | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| - | AsyncCallback | AsyncCallback<SendRequestResult> | Yes| Callback for receiving the sending result.| - + | Name | Type | Mandatory| Description | + | ------------- | -------------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | + | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | + | AsyncCallback | AsyncCallback<SendRequestResult> | Yes | Callback for receiving the sending result. | **Example** @@ -4002,32 +7765,29 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch ### onRemoteRequest8+(deprecated) +>This API is no longer maintained since API version 9. You are advised to use [onRemoteMessageRequest](#onremotemessagerequest9). -onRemoteRequest(code : number, data : MessageParcel, reply: MessageParcel, options : MessageOption): boolean - -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [onRemoteRequestEx9+](#onremoterequestex9). +onRemoteRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption): boolean -Provides a response to **sendRequestAsync()**. The server processes the request and returns a response in this function. +Provides a response to **sendMessageRequest()**. The server processes the request and returns a response in this API. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Service request code sent by the remote end.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that holds the parameters called by the client.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object carrying the result.| - | option | [MessageOption](#messageoption) | Yes| Whether the operation is synchronous or asynchronous.| + | Name| Type | Mandatory| Description | + | ------ | ------------------------------- | ---- | --------------------------------------- | + | code | number | Yes | Service request code sent by the remote end. | + | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that holds the parameters called by the client.| + | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object carrying the result. | + | option | [MessageOption](#messageoption) | Yes | Whether the operation is synchronous or asynchronous. | **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ----------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - **Example** ```ets @@ -4049,7 +7809,6 @@ Provides a response to **sendRequestAsync()**. The server processes the request isObjectDead(): boolean { return false; } - onRemoteRequest(code, data, reply, option) { if (code === 1) { console.log("RpcServer: onRemoteRequest called"); @@ -4061,59 +7820,47 @@ Provides a response to **sendRequestAsync()**. The server processes the request } } ``` -### onRemoteRequestEx9+ -onRemoteRequestEx(code : number, data : MessageParcel, reply: MessageParcel, options : MessageOption): boolean | Promise +### onRemoteMessageRequest9+ + +onRemoteMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption): boolean | Promise\ > **NOTE**
->- You are advised to overload **onRemoteRequestEx** preferentially, which implements synchronous and asynchronous message processing. ->- If both **onRemoteRequest** and **onRemoteRequestEx** are overloaded, only **onRemoteRequestEx** takes effect. +> +>* You are advised to overload **onRemoteMessageRequest** preferentially, which implements synchronous and asynchronous message processing. +>* If both onRemoteRequest() and onRemoteMessageRequest() are overloaded, only the onRemoteMessageRequest() takes effect. -Provides a response to **sendRequestAsync()**. The server processes the request synchronously or asynchronously and returns the result in this API. +Provides a response to **sendMessageRequest()**. The server processes the request synchronously or asynchronously and returns the result in this API. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Service request code sent by the remote end.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that holds the parameters called by the client.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object carrying the result.| - | option | [MessageOption](#messageoption) | Yes| Whether the operation is synchronous or asynchronous.| + | Name| Type | Mandatory| Description | + | ------ | ------------------------------- | ---- | ----------------------------------------- | + | code | number | Yes | Service request code sent by the remote end. | + | data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that holds the parameters called by the client.| + | reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object to which the result is written. | + | option | [MessageOption](#messageoption) | Yes | Whether the operation is synchronous or asynchronous. | **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns a Boolean value if the request is processed synchronously in **onRemoteRequestEx**. If the operation is successful, **true** is returned. Otherwise, **false** is returned.| - | Promise | Returns a promise object if the request is processed asynchronously in **onRemoteRequestEx**.| - + | Type | Description | + | ----------------- | ---------------------------------------------------------------------------------------------- | + | boolean | Returns a Boolean value if the request is processed synchronously in **onRemoteMessageRequest**. If the operation is successful, **true** is returned. Otherwise, **false** is returned.| + | Promise\ | Returns a promise object if the request is processed asynchronously in **onRemoteMessageRequest**. | -**Example**: Overload **onRemoteRequestEx** to process a request synchronously. +**Example**: Overload **onRemoteMessageRequest** to process requests synchronously. ```ets - class MyDeathRecipient { - onRemoteDied() { - console.log("server died"); - } - } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - isObjectDead(): boolean { - return false; - } - onRemoteRequestEx(code, data, reply, option) { + + onRemoteMessageRequest(code, data, reply, option) { if (code === 1) { - console.log("RpcServer: sync onRemoteRequestEx is called"); + console.log("RpcServer: sync onRemoteMessageRequest is called"); return true; } else { console.log("RpcServer: unknown code: " + code); @@ -4122,30 +7869,18 @@ Provides a response to **sendRequestAsync()**. The server processes the request } } ``` - **Example**: Overload **onRemoteRequestEx** to process a request asynchronously. + + **Example**: Overload **onRemoteMessageRequest** to process requests asynchronously. ```ets - class MyDeathRecipient { - onRemoteDied() { - console.log("server died"); - } - } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - isObjectDead(): boolean { - return false; - } - async onRemoteRequestEx(code, data, reply, option) { + + async onRemoteMessageRequest(code, data, reply, option) { if (code === 1) { - console.log("RpcServer: async onRemoteRequestEx is called"); + console.log("RpcServer: async onRemoteMessageRequest is called"); } else { console.log("RpcServer: unknown code: " + code); return false; @@ -4157,94 +7892,72 @@ Provides a response to **sendRequestAsync()**. The server processes the request } } ``` -**Example**: Overload **onRemoteRequestEx** and **onRemoteRequest** to process requests synchronously. + +**Example**: Overload **onRemoteMessageRequest** and **onRemoteRequest** to process requests synchronously. ```ets - class MyDeathRecipient { - onRemoteDied() { - console.log("server died"); - } - } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - isObjectDead(): boolean { - return false; - } + onRemoteRequest(code, data, reply, option) { if (code === 1) { - console.log("RpcServer: sync onRemoteRequestEx is called"); + console.log("RpcServer: sync onRemoteMessageRequest is called"); return true; } else { console.log("RpcServer: unknown code: " + code); return false; } } - // Only onRemoteRequestEx is executed when onRemoteRequestEx and onRemoteRequest are called. - onRemoteRequestEx(code, data, reply, option) { + // Only onRemoteMessageRequest is executed. + onRemoteMessageRequest(code, data, reply, option) { if (code === 1) { - console.log("RpcServer: async onRemoteRequestEx is called"); + console.log("RpcServer: async onRemoteMessageRequest is called"); } else { console.log("RpcServer: unknown code: " + code); return false; } - + return true; } } ``` - **Example**: Overload **onRemoteRequestEx** and **onRemoteRequest** to process requests asynchronously. + + **Example**: Overload **onRemoteMessageRequest** and **onRemoteRequest** to process requests asynchronously. ```ets - class MyDeathRecipient { - onRemoteDied() { - console.log("server died"); - } - } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - isObjectDead(): boolean { - return false; - } + onRemoteRequest(code, data, reply, option) { if (code === 1) { - console.log("RpcServer: sync onRemoteRequestEx is called"); + console.log("RpcServer: sync onRemoteRequest is called"); return true; } else { console.log("RpcServer: unknown code: " + code); return false; } } - // Only onRemoteRequestEx is executed when onRemoteRequestEx and onRemoteRequest are called. - async onRemoteRequestEx(code, data, reply, option) { + // Only onRemoteMessageRequest is executed. + async onRemoteMessageRequest(code, data, reply, option) { if (code === 1) { - console.log("RpcServer: async onRemoteRequestEx is called"); + console.log("RpcServer: async onRemoteMessageRequest is called"); } else { console.log("RpcServer: unknown code: " + code); return false; } - await new Promise((resolve) => { + await new Promise((resolve) => { setTimeout(resolve, 100); }) return true; } } ``` + + ### getCallingUid getCallingUid(): number @@ -4254,11 +7967,118 @@ Obtains the UID of the remote process. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ----------------------- | | number | UID of the remote process obtained.| +**Example** + + ``` + class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + } + } + let testRemoteObject = new TestRemoteObject("testObject"); + console.log("RpcServer: getCallingUid: " + testRemoteObject.getCallingUid()); + ``` + +### getCallingPid + +getCallingPid(): number + +Obtains the PID of the remote process. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | ----------------------- | + | number | PID of the remote process obtained.| + +**Example** + + ``` + class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + } + } + let testRemoteObject = new TestRemoteObject("testObject"); + console.log("RpcServer: getCallingPid: " + testRemoteObject.getCallingPid()); + ``` + +### getLocalInterface9+ + +getLocalInterface(descriptor: string): IRemoteBroker + +Obtains the interface. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ---------- | ------ | ---- | -------------------- | + | descriptor | string | Yes | Interface descriptor.| + +**Return value** + + | Type | Description | + | ------------- | --------------------------------------------- | + | IRemoteBroker | **IRemoteBroker** object bound to the specified interface token.| + + +**Example** + + ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } + class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + } + registerDeathRecipient(recipient: MyDeathRecipient, flags: number); + unregisterDeathRecipient(recipient: MyDeathRecipient, flags: number); + isObjectDead(): boolean { + return false; + } + } + let testRemoteObject = new TestRemoteObject("testObject"); + try { + let broker = testRemoteObject.getLocalInterface("testObject"); + } catch(error) { + console.info(rpc get local interface fail, errorCode " + error.code); + console.info(rpc get local interface fail, errorMessage " + error.message); + } + ``` + + +### queryLocalInterface(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [getLocalInterface](#getlocalinterface9). + +queryLocalInterface(descriptor: string): IRemoteBroker + +Checks whether the remote object corresponding to the specified interface token exists. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ---------- | ------ | ---- | ---------------------- | + | descriptor | string | Yes | Interface descriptor.| + +**Return value** + + | Type | Description | + | ------------- | ------------------------------------------------------------------ | + | IRemoteBroker | Returns the remote object if a match is found; returns **Null** otherwise.| **Example** @@ -4283,24 +8103,31 @@ Obtains the UID of the remote process. } } let testRemoteObject = new TestRemoteObject("testObject"); - console.log("RpcServer: getCallingUid: " + testRemoteObject.getCallingUid()); + let broker = testRemoteObject.queryLocalInterface("testObject"); ``` -### getCallingPid +### getDescriptor9+ -getCallingPid(): number +getDescriptor(): string -Obtains the PID of the remote process. +Obtains the interface descriptor of this object. The interface descriptor is a string. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | number | PID of the remote process obtained.| + | Type | Description | + | ------ | ---------------- | + | string | Interface descriptor obtained.| + +**Error Code** +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900008 | proxy or remote object is invalid | **Example** @@ -4314,41 +8141,38 @@ Obtains the PID of the remote process. constructor(descriptor) { super(descriptor); } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } + addDeathRecipient(recipient: MyDeathRecipient, flags: number); + unregisterDeathRecipient(recipient: MyDeathRecipient, flags: number); isObjectDead(): boolean { return false; } } let testRemoteObject = new TestRemoteObject("testObject"); - console.log("RpcServer: getCallingPid: " + testRemoteObject.getCallingPid()); + try { + let descriptor = testRemoteObject.getDescriptor(); + } catch(error) { + console.info(rpc get local interface fail, errorCode " + error.code); + console.info(rpc get local interface fail, errorMessage " + error.message); + } + console.log("RpcServer: descriptor is: " + descriptor); ``` -### queryLocalInterface - -queryLocalInterface(descriptor: string): IRemoteBroker +### getInterfaceDescriptor(deprecated) -Checks whether the remote object corresponding to the specified interface descriptor exists. +>This API is no longer maintained since API version 9. You are advised to use [getDescriptor](#getdescriptor9). -**System capability**: SystemCapability.Communication.IPC.Core +getInterfaceDescriptor(): string -**Parameters** +Obtains the interface descriptor. - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | descriptor | string | Yes| Interface descriptor.| +**System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | IRemoteBroker | Returns the remote object if a match is found; returns **Null** otherwise.| - + | Type | Description | + | ------ | ---------------- | + | string | Interface descriptor obtained.| **Example** @@ -4373,23 +8197,25 @@ Checks whether the remote object corresponding to the specified interface descri } } let testRemoteObject = new TestRemoteObject("testObject"); - let broker = testRemoteObject.queryLocalInterface("testObject"); + let descriptor = testRemoteObject.getInterfaceDescriptor(); + console.log("RpcServer: descriptor is: " + descriptor); ``` -### getInterfaceDescriptor +### modifyLocalInterface9+ -getInterfaceDescriptor(): string +modifyLocalInterface(localInterface: IRemoteBroker, descriptor: string): void -Obtains the interface descriptor. +Binds an interface descriptor to an **IRemoteBroker** object. **System capability**: SystemCapability.Communication.IPC.Core -**Return value** +**Parameters** - | Type| Description| - | -------- | -------- | - | string | Interface descriptor obtained.| + | Name | Type | Mandatory| Description | + | -------------- | ------------- | ---- | ------------------------------------- | + | localInterface | IRemoteBroker | Yes | **IRemoteBroker** object. | + | descriptor | string | Yes | Interface descriptor.| **Example** @@ -4403,24 +8229,28 @@ Obtains the interface descriptor. class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); + try { + this.modifyLocalInterface(this, descriptor); + } catch(error) { + console.info(rpc attach local interface fail, errorCode " + error.code); + console.info(rpc attach local interface fail, errorMessage " + error.message); + } } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } + registerDeathRecipient(recipient: MyDeathRecipient, flags: number); + unregisterDeathRecipient(recipient: MyDeathRecipient, flags: number); isObjectDead(): boolean { return false; } + asObject(): rpc.IRemoteObject { + return this; + } } let testRemoteObject = new TestRemoteObject("testObject"); - let descriptor = testRemoteObject.getInterfaceDescriptor(); - console.log("RpcServer: descriptor is: " + descriptor); ``` +### attachLocalInterface(deprecated) -### attachLocalInterface +>This API is no longer maintained since API version 9. You are advised to use [modifyLocalInterface](#modifylocalinterface9). attachLocalInterface(localInterface: IRemoteBroker, descriptor: string): void @@ -4430,11 +8260,10 @@ Binds an interface descriptor to an **IRemoteBroker** object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | localInterface | IRemoteBroker | Yes| **IRemoteBroker** object.| - | descriptor | string | Yes| Interface descriptor.| - + | Name | Type | Mandatory| Description | + | -------------- | ------------- | ---- | ------------------------------------- | + | localInterface | IRemoteBroker | Yes | **IRemoteBroker** object. | + | descriptor | string | Yes | Interface descriptor.| **Example** @@ -4474,17 +8303,17 @@ The table below describes the protection types of the mapped memory. **System capability**: SystemCapability.Communication.IPC.Core - | Name| Value| Description| -| -------- | -------- | -------- | -| PROT_EXEC | 4 | The mapped memory is executable.| -| PROT_NONE | 0 | The mapped memory is inaccessible.| -| PROT_READ | 1 | The mapped memory is readable.| -| PROT_WRITE | 2 | The mapped memory is writeable.| + | Name | Value | Description | + | ---------- | --- | ------------------ | + | PROT_EXEC | 4 | The mapped memory is executable. | + | PROT_NONE | 0 | The mapped memory is inaccessible.| + | PROT_READ | 1 | The mapped memory is readable. | + | PROT_WRITE | 2 | The mapped memory is writeable. | -### createAshmem8+ +### create9+ -static createAshmem(name: string, size: number): Ashmem +static create(name: string, size: number): Ashmem Creates an **Ashmem** object with the specified name and size. @@ -4492,18 +8321,56 @@ Creates an **Ashmem** object with the specified name and size. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | name | string | Yes| Name of the **Ashmem** object to create.| - | size | number | Yes| Size (in bytes) of the **Ashmem** object to create.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ---------------------------- | + | name | string | Yes | Name of the **Ashmem** object to create. | + | size | number | Yes | Size (in bytes) of the **Ashmem** object to create.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ---------------------------------------------- | | Ashmem | Returns the **Ashmem** object if it is created successfully; returns null otherwise.| +**Example** + + ``` + let ashmem; + try { + ashmem = rpc.Ashmem.create("ashmem", 1024*1024); + } catch(error) { + console.info("Rpc creat ashmem fail, errorCode " + error.code); + console.info("Rpc creat ashmem fail, errorMessage " + error.message); + } + let size = ashmem.getAshmemSize(); + console.log("RpcTest: get ashemm by create : " + ashmem + " size is : " + size); + ``` + + +### createAshmem8+(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [create](#create9). + +static createAshmem(name: string, size: number): Ashmem + +Creates an **Ashmem** object with the specified name and size. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ---------------------------- | + | name | string | Yes | Name of the **Ashmem** object to create. | + | size | number | Yes | Size (in bytes) of the **Ashmem** object to create.| + +**Return value** + + | Type | Description | + | ------ | ---------------------------------------------- | + | Ashmem | Returns the **Ashmem** object if it is created successfully; returns null otherwise.| + **Example** ``` @@ -4513,9 +8380,9 @@ Creates an **Ashmem** object with the specified name and size. ``` -### createAshmemFromExisting8+ +### create9+ -static createAshmemFromExisting(ashmem: Ashmem): Ashmem +static create(ashmem: Ashmem): Ashmem Creates an **Ashmem** object by copying the file descriptor (FD) of an existing Ashmem object. The two **Ashmem** objects point to the same shared memory region. @@ -4523,17 +8390,55 @@ Creates an **Ashmem** object by copying the file descriptor (FD) of an existing **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ashmem | Ashmem | Yes| Existing **Ashmem** object.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | -------------------- | + | ashmem | Ashmem | Yes | Existing **Ashmem** object.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ---------------------- | | Ashmem | **Ashmem** object created.| +**Example** + + ``` + let ashmem2; + try { + let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); + let ashmem2 = rpc.Ashmem.create(ashmem); + } catch(error) { + console.info("Rpc creat ashmem from existing fail, errorCode " + error.code); + console.info("Rpc creat ashmem from existing fail, errorMessage " + error.message); + } + let size = ashmem2.getAshmemSize(); + console.log("RpcTest: get ashemm by create : " + ashmem2 + " size is : " + size); + ``` + + +### createAshmemFromExisting8+(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [create](#create9). + +static createAshmemFromExisting(ashmem: Ashmem): Ashmem + +Creates an **Ashmem** object by copying the file descriptor (FD) of an existing Ashmem object. The two **Ashmem** objects point to the same shared memory region. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | -------------------- | + | ashmem | Ashmem | Yes | Existing **Ashmem** object.| + +**Return value** + + | Type | Description | + | ------ | ---------------------- | + | Ashmem | **Ashmem** object created.| + **Example** ``` @@ -4555,7 +8460,7 @@ Closes this **Ashmem** object. **Example** ``` - let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); + let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); ashmem.closeAshmem(); ``` @@ -4571,7 +8476,7 @@ Deletes the mappings for the specified address range of this **Ashmem** object. **Example** ``` - let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); + let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); ashmem.unmapAshmem(); ``` @@ -4586,8 +8491,8 @@ Obtains the memory size of this **Ashmem** object. **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | -------------------------- | | number | **Ashmem** size obtained.| **Example** @@ -4599,7 +8504,44 @@ Obtains the memory size of this **Ashmem** object. ``` -### mapAshmem8+ +### mapTypedAshmem9+ + +mapTypedAshmem(mapType: number): void + +Creates the shared file mapping on the virtual address space of this process. The size of the mapping region is specified by this **Ashmem** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ------- | ------ | ---- | ------------------------------ | + | mapType | number | Yes | Protection level of the memory region to which the shared file is mapped.| + +**Error Code** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ------ | + | 1900001 | call mmap function failed | + +**Example** + + ``` + let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); + try { + ashmem.mapTypedAshmem(ashmem.PROT_READ | ashmem.PROT_WRITE); + } catch(error) { + console.info("Rpc map ashmem fail, errorCode " + error.code); + console.info("Rpc map ashmem fail, errorMessage " + error.message); + } + ``` + + +### mapAshmem8+(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [mapTypedAshmem](#maptypedashmem9). mapAshmem(mapType: number): boolean @@ -4609,14 +8551,14 @@ Creates the shared file mapping on the virtual address space of this process. Th **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | mapType | number | Yes| Protection level of the memory region to which the shared file is mapped.| + | Name | Type | Mandatory| Description | + | ------- | ------ | ---- | ------------------------------ | + | mapType | number | Yes | Protection level of the memory region to which the shared file is mapped.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ----------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -4628,7 +8570,38 @@ Creates the shared file mapping on the virtual address space of this process. Th ``` -### mapReadAndWriteAshmem8+ +### mapReadWriteAshmem9+ + +mapReadWriteAshmem(): void + +Maps the shared file to the readable and writable virtual address space of the process. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Error Code** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900001 | call mmap function failed | + +**Example** + + ``` + let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); + try { + ashmem.mapReadWriteAshmem(); + } catch(error) { + console.info("Rpc map read and write ashmem fail, errorCode " + error.code); + console.info("Rpc map read and write ashmem fail, errorMessage " + error.message); + } + ``` + + +### mapReadAndWriteAshmem8+(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [mapReadWriteAshmem](#mapreadwriteashmem9). mapReadAndWriteAshmem(): boolean @@ -4638,8 +8611,8 @@ Maps the shared file to the readable and writable virtual address space of the p **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ----------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -4651,7 +8624,38 @@ Maps the shared file to the readable and writable virtual address space of the p ``` -### mapReadOnlyAshmem8+ +### mapReadonlyAshmem9+ + +mapReadonlyAshmem(): void + +Maps the shared file to the read-only virtual address space of the process. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Error Code** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900001 | call mmap function failed | + +**Example** + + ``` + let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); + try { + ashmem.mapReadonlyAshmem(); + } catch(error) { + console.info("Rpc map read and write ashmem fail, errorCode " + error.code); + console.info("Rpc map read and write ashmem fail, errorMessage " + error.message); + } + ``` + + +### mapReadOnlyAshmem8+(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [mapReadonlyAshmem](#mapreadonlyashmem9). mapReadOnlyAshmem(): boolean @@ -4661,8 +8665,8 @@ Maps the shared file to the read-only virtual address space of the process. **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ----------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -4674,7 +8678,44 @@ Maps the shared file to the read-only virtual address space of the process. ``` -### setProtection8+ +### setProtectionType9+ + +setProtectionType(protectionType: number): void + +Sets the protection level of the memory region to which the shared file is mapped. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------------- | ------ | ---- | ------------------ | + | protectionType | number | Yes | Protection type to set.| + +**Error Code** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | -------- | ------- | + | 1900002 | call os ioctl function failed | + +**Example** + + ``` + let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); + try { + ashmem.setProtection(ashmem.PROT_READ); + } catch(error) { + console.info("Rpc set protection type fail, errorCode " + error.code); + console.info("Rpc set protection type fail, errorMessage " + error.message); + } + ``` + + +### setProtection8+(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [setProtectionType](#setprotectiontype9). setProtection(protectionType: number): boolean @@ -4684,14 +8725,14 @@ Sets the protection level of the memory region to which the shared file is mappe **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | protectionType | number | Yes| Protection type to set.| + | Name | Type | Mandatory| Description | + | -------------- | ------ | ---- | ------------------ | + | protectionType | number | Yes | Protection type to set.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ----------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -4703,7 +8744,48 @@ Sets the protection level of the memory region to which the shared file is mappe ``` -### writeToAshmem8+ +### writeAshmem9+ + +writeAshmem(buf: number[], size: number, offset: number): void + +Writes data to the shared file associated with this **Ashmem** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | -------------------------------------------------- | + | buf | number[] | Yes | Data to write. | + | size | number | Yes | Size of the data to write. | + | offset | number | Yes | Start position of the data to write in the memory region associated with this **Ashmem** object.| + +**Error Code** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900003 | write to ashmem failed | + +**Example** + + ``` + let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); + ashmem.mapReadWriteAshmem(); + var ByteArrayVar = [1, 2, 3, 4, 5]; + try { + ashmem.writeAshmem(ByteArrayVar, 5, 0); + } catch(error) { + console.info("Rpc write to ashmem fail, errorCode " + error.code); + console.info("Rpc write to ashmem fail, errorMessage " + error.message); + } + ``` + + +### writeToAshmem8+(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [writeAshmem](#writeashmem9). writeToAshmem(buf: number[], size: number, offset: number): boolean @@ -4713,16 +8795,16 @@ Writes data to the shared file associated with this **Ashmem** object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | buf | number[] | Yes| Data to write.| - | size | number | Yes| Size of the data to write.| - | offset | number | Yes| Start position of the data to write in the memory region associated with this **Ashmem** object.| + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | -------------------------------------------------- | + | buf | number[] | Yes | Data to write. | + | size | number | Yes | Size of the data to write. | + | offset | number | Yes | Start position of the data to write in the memory region associated with this **Ashmem** object.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ----------------------------------------------------------------------------------------- | | boolean | Returns **true** is the data is written successfully; returns **false** otherwise.| **Example** @@ -4737,9 +8819,9 @@ Writes data to the shared file associated with this **Ashmem** object. ``` -### readFromAshmem8+ +### readAshmem9+ -readFromAshmem(size: number, offset: number): number[] +readAshmem(size: number, offset: number): number[] Reads data from the shared file associated with this **Ashmem** object. @@ -4747,21 +8829,68 @@ Reads data from the shared file associated with this **Ashmem** object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | size | number | Yes| Size of the data to read.| - | offset | number | Yes| Start position of the data to read in the memory region associated with this **Ashmem** object.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | -------------------------------------------------- | + | size | number | Yes | Size of the data to read. | + | offset | number | Yes | Start position of the data to read in the memory region associated with this **Ashmem** object.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | -------- | ---------------- | | number[] | Data read.| +**Error Code** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID | Error Message| + | -------- | -------- | + | 1900004 | read from ashmem failed | **Example** ``` + let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); + ashmem.mapReadWriteAshmem(); + var ByteArrayVar = [1, 2, 3, 4, 5]; + ashmem.writeAshmem(ByteArrayVar, 5, 0); + try { + let readResult = ashmem.readAshmem(5, 0); + console.log("RpcTest: read from Ashmem result is : " + readResult); + } catch(error) { + console.info("Rpc read from ashmem fail, errorCode " + error.code); + console.info("Rpc read from ashmem fail, errorMessage " + error.message); + } + ``` + + +### readFromAshmem8+(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [readAshmem](#readashmem9). + +readFromAshmem(size: number, offset: number): number[] + +Reads data from the shared file associated with this **Ashmem** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | -------------------------------------------------- | + | size | number | Yes | Size of the data to read. | + | offset | number | Yes | Start position of the data to read in the memory region associated with this **Ashmem** object.| + +**Return value** + + | Type | Description | + | -------- | ---------------- | + | number[] | Data read.| + +**Example** + + ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let mapResult = ashmem.mapReadAndWriteAshmem(); console.info("RpcTest map ashmem result is " + mapResult); diff --git a/en/application-dev/reference/apis/js-apis-tagSession.md b/en/application-dev/reference/apis/js-apis-tagSession.md index e6073f2dca4b101454fbdf14dd9bdd406a8eaade..3138f52c7089ba4a53809711c442b79f6a1aa1aa 100644 --- a/en/application-dev/reference/apis/js-apis-tagSession.md +++ b/en/application-dev/reference/apis/js-apis-tagSession.md @@ -1,8 +1,9 @@ -# NFC Tag Session +# tagSession The **tagSession** module provides common APIs for establishing connections and transferring data. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## **Modules to Import** @@ -15,17 +16,15 @@ import tag from '@ohos.nfc.tag'; Provides common APIs for establishing connections and transferring data. **tagSession** is the base class of all [NFC tag technologies](js-apis-nfctech.md). -A child class instance is required to access the following interfaces. You can use **get**XX**Tag()** to obtain a child class instance. +A child class instance is required to access the following interfaces. You can use **get**XXX() to obtain a child class instance. The specific API varies with the NFC tag technology in use. For details, see [NFC Tags](js-apis-nfcTag.md). -### tagSession.connectTag - -connectTag(): boolean; +### tagSession.getTagInfo -Connects to this tag. +getTagInfo(): tag.TagInfo -Call this API to set up a connection before reading data from or writing data to a tag. +Obtains the **tagInfo** object provided by the NFC service when the tag is dispatched. **Required permissions**: ohos.permission.NFC_TAG @@ -35,23 +34,25 @@ Call this API to set up a connection before reading data from or writing data to | **Type**| **Description** | | ------------------ | --------------------------| -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| TagInfo | **Taginfo** object obtained.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let isNfcConnected = tag.getXXXTag(taginfo).connectTag(); -console.log("isNfcConnected:" +isNfcConnected); +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +let tagInfo = tag.getIsoDep(tagInfo).getTagInfo(); +console.log("tag tagInfo: " + tagInfo); ``` -### tagSession.reset() +### tagSession.connectTag -reset(): void +connectTag(): boolean; -Resets the connection to this tag and restores the default timeout duration for writing data to the tag. +Connects to this tag. Call this API to set up a connection before reading data from or writing data to a tag. **Required permissions**: ohos.permission.NFC_TAG @@ -68,9 +69,32 @@ Resets the connection to this tag and restores the default timeout duration for ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let reset = tag.getXXXTag(taginfo).reset(); -console.log("reset:" +reset); +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +let connectStatus = tag.getIsoDep(tagInfo).connectTag(); +console.log("connectStatus: " + connectStatus); +``` + +### tagSession.reset() + +reset(): void + +Resets the connection to this tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +tag.getIsoDep(tagInfo).reset(); ``` ### tagSession.isTagConnected @@ -94,16 +118,18 @@ Checks whether the tag is connected. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let isTagConnected = tag.getXXXTag(taginfo).isTagConnected(); -console.log("isTagConnected:" +isTagConnected); +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +let isTagConnected = tag.getIsoDep(tagInfo).isTagConnected(); +console.log("isTagConnected: " + isTagConnected); ``` ### tagSession.getMaxSendLength getMaxSendLength(): number -Obtains the maximum length of the data that can be sent to the tag. +Obtains the maximum length of the data that can be sent to this tag. **Required permissions**: ohos.permission.NFC_TAG @@ -113,14 +139,167 @@ Obtains the maximum length of the data that can be sent to the tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number | Maximum data length obtained.| +| number | Maximum data length obtained. The value cannot be a negative number.| + +**Example** +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +let maxSendLen = tag.getIsoDep(tagInfo).getMaxSendLength(); +console.log("tag maxSendLen: " + maxSendLen); +``` + +### tagSession.getSendDataTimeout + +getSendDataTimeout(): number + +Obtains the timeout period for sending data to this tag, in milliseconds. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number | Timeout period obtained, in milliseconds. The value cannot be a negative number.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +let sendDataTimeout = tag.getIsoDep(tagInfo).getSendDataTimeout(); +console.log("tag sendDataTimeout: " + sendDataTimeout); +``` + +### tagSession.setSendDataTimeout + +setSendDataTimeout(timeout: number): boolean + +Sets the timeout period for sending data to this tag, in milliseconds. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| timeout | number | Yes| Timeout period to set, in milliseconds. The value cannot be a negative number.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| boolean | Returns **true** if the timeout period is set successfully; returns **false** otherwise.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +let timeoutMs = 700; // Change it as required. +let setStatus = tag.getIsoDep(tagInfo).setSendDataTimeout(timeoutMs); +console.log("tag setSendDataTimeout setStatus: " + setStatus); +``` + +### tagSession.sendData + +sendData(data: number[]): Promise + +Sends data to this tag. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| data | number[] | Yes| Data to send. The data consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise | Promise used to return the response from the tag. The response consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +// Connect to the tag if it is not connected. +if (!tag.getIsoDep(tagInfo).isTagConnected()) { + if (!tag.getIsoDep(tagInfo).connectTag()) { + console.log("tagSession connectTag failed."); + return; + } +} + +let cmdData = [0x01, 0x02, 0x03, 0x04]; // Change it as required. +tag.getIsoDep(tagInfo).sendData(cmdData).then((response) => { + console.log("tagSession sendData Promise response: " + response); +}).catch((err)=> { + console.log("tagSession sendData Promise err: " + err); +}); +``` + +### tagSession.sendData + +sendData(data: number[], callback: AsyncCallback): void + +Sends data to this tag. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| data | number[] | Yes| Data to send. The data consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| +| callback | AsyncCallback | Yes| Callback invoked to return the response from the tag. The response consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let mazSendLen = tag.getXXXTag(taginfo).getMaxSendLength(); -console.log("mazSendLen:" +mazSendLen); +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +// Connect to the tag if it is not connected. +if (!tag.getIsoDep(tagInfo).isTagConnected()) { + if (!tag.getIsoDep(tagInfo).connectTag()) { + console.log("tagSession connectTag failed."); + return; + } +} + +let cmdData = [0x01, 0x02, 0x03, 0x04]; // Change it as required. +tag.getIsoDep(tagInfo).sendData(cmdData, (err, response)=> { + if (err) { + console.log("tagSession sendData AsyncCallback err: " + err); + } else { + console.log("tagSession sendData AsyncCallback response: " + response); + } +}); ``` diff --git a/en/application-dev/reference/apis/js-apis-wifi.md b/en/application-dev/reference/apis/js-apis-wifi.md index a8221a78898accf8d18724193df311a13693b998..6af6bc0a51e3a862a159b6bf450c9ce90bd31346 100644 --- a/en/application-dev/reference/apis/js-apis-wifi.md +++ b/en/application-dev/reference/apis/js-apis-wifi.md @@ -1,7 +1,9 @@ -# WLAN +# @ohos.wifi (WLAN) + The **WLAN** module provides basic wireless local area network (WLAN) functions, peer-to-peer (P2P) functions, and WLAN message notification services. It allows applications to communicate with other devices over WLAN. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -166,20 +168,17 @@ Represents WLAN hotspot information. **System capability**: SystemCapability.Communication.WiFi.STA -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| ssid | string | Read only| Service set identifier (SSID) of the hotspot, in UTF-8 format.| -| bssid | string | Read only| Basic service set identifier (BSSID) of the hotspot.| -| capabilities | string | Read only| Hotspot capabilities.| -| securityType | [WifiSecurityType](#wifisecuritytype) | Read only| WLAN security type.| -| rssi | number | Read only| Received signal strength indicator (RSSI) of the hotspot, in dBm.| -| band | number | Read only| Frequency band of the WLAN access point (AP).| -| frequency | number | Read only| Frequency of the WLAN AP.| -| channelWidth | number | Read only| Channel width of the WLAN AP.| -| centerFrequency09+ | number | Read only| Center frequency of the hotspot.| -| centerFrequency19+ | number | Read only| Center frequency of the hotspot. If the hotspot uses two non-overlapping WLAN channels, two center frequencies, namely **centerFrequency0** and **centerFrequency1**, are returned.| -| infoElems9+ | Array<[WifiInfoElem](#wifiinfoelem9)> | Read only| Information elements.| -| timestamp | number | Read only| Timestamp.| +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| Service set identifier (SSID) of the hotspot, in UTF-8 format.| +| bssid | string | Yes| No| Basic service set identifier (BSSID) of the hotspot.| +| capabilities | string | Yes| No| Hotspot capabilities.| +| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| WLAN security type.| +| rssi | number | Yes| No| Received signal strength indicator (RSSI) of the hotspot, in dBm.| +| band | number | Yes| No| Frequency band of the WLAN access point (AP).| +| frequency | number | Yes| No| Frequency of the WLAN AP.| +| channelWidth | number | Yes| No| Channel width of the WLAN AP.| +| timestamp | number | Yes| No| Timestamp.| ## WifiSecurityType @@ -189,50 +188,13 @@ Enumerates the WLAN security types. **System capability**: SystemCapability.Communication.WiFi.Core -| **Name**| **Default Value**| **Description**| +| **Name**| **Value**| **Description**| | -------- | -------- | -------- | | WIFI_SEC_TYPE_INVALID | 0 | Invalid security type.| | WIFI_SEC_TYPE_OPEN | 1 | Open security type.| | WIFI_SEC_TYPE_WEP | 2 | Wired Equivalent Privacy (WEP).| | WIFI_SEC_TYPE_PSK | 3 | Pre-shared key (PSK).| | WIFI_SEC_TYPE_SAE | 4 | Simultaneous Authentication of Equals (SAE).| -| WIFI_SEC_TYPE_EAP9+ | 5 | Extensible Authentication protocol (EAP).| -| WIFI_SEC_TYPE_EAP_SUITE_B9+ | 6 | Suite B 192-bit encryption.| -| WIFI_SEC_TYPE_OWE9+ | 7 | Opportunistic Wireless Encryption (OWE).| -| WIFI_SEC_TYPE_WAPI_CERT9+ | 8 | WLAN Authentication and Privacy Infrastructure (WAPI) in certificate-based mode (WAPI-CERT).| -| WIFI_SEC_TYPE_WAPI_PSK9+ | 9 | WAPI-PSK.| - - -## WifiInfoElem9+ - -Represents a WLAN information element. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Communication.WiFi.STA - - -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| eid | number | Read only| ID of the information element.| -| content | Uint8Array | Read only| Content of the information element.| - - -## WifiChannelWidth9+ - -Enumerates the WLAN channel widths. - -**System capability**: SystemCapability.Communication.WiFi.STA - - -| **Name**| **Default Value**| **Description**| -| -------- | -------- | -------- | -| WIDTH_20MHZ | 0 | 20 MHz.| -| WIDTH_40MHZ | 1 | 40 MHz.| -| WIDTH_80MHZ | 2 | 80 MHz.| -| WIDTH_160MHZ | 3 | 160 MHz.| -| WIDTH_80MHZ_PLUS | 4 | 80 MHz+.| -| WIDTH_INVALID | 5 | Invalid value.| ## wifi.getScanInfosSync9+ @@ -274,7 +236,7 @@ Adds network configuration. This API uses a promise to return the result. | **Type**| **Description**| | -------- | -------- | - | Promise<number> | Promise used to return the WLAN configuration ID. If **-1** is returned, the operation has failed.| + | Promise<number> | Promise used to return the WLAN configuration ID. If **-1** is returned, the network configuration fails to be added.| ## WifiDeviceConfig @@ -283,33 +245,32 @@ Represents the WLAN configuration. **System capability**: SystemCapability.Communication.WiFi.STA -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| ssid | string | Read only| SSID of the hotspot, in UTF-8 format.| -| bssid | string | Read only| BSSID of the hotspot.| -| preSharedKey | string | Read only| PSK of the hotspot.| -| isHiddenSsid | boolean | Read only| Whether the network is hidden.| -| securityType | [WifiSecurityType](#wifisecuritytype) | Read only| Security type.| -| creatorUid | number | Read only| ID of the creator.
**System API**: This is a system API.| -| disableReason | number | Read only| Reason for disabling WLAN.
**System API**: This is a system API.| -| netId | number | Read only| Network ID.
**System API**: This is a system API.| -| randomMacType | number | Read only| Random MAC type.
**System API**: This is a system API.| -| randomMacAddr | string | Read only| Random MAC address.
**System API**: This is a system API.| -| ipType | [IpType](#iptype7) | Read only| IP address type.
**System API**: This is a system API.| -| staticIp | [IpConfig](#ipconfig7) | Read only| Static IP address configuration.
**System API**: This is a system API.| -| eapConfig9+ | [WifiEapConfig](#wifieapconfig9) | Read only| EAP configuration.
**System API**: This is a system API.| +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| +| bssid | string | Yes| No| BSSID of the hotspot.| +| preSharedKey | string | Yes| No| PSK of the hotspot.| +| isHiddenSsid | boolean | Yes| No| Whether the network is hidden.| +| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| Security type.| +| creatorUid | number | Yes| No| ID of the creator.
**System API**: This is a system API.| +| disableReason | number | Yes| No| Reason for disabling WLAN.
**System API**: This is a system API.| +| netId | number | Yes| No| Network ID.
**System API**: This is a system API.| +| randomMacType | number | Yes| No| Random MAC type.
**System API**: This is a system API.| +| randomMacAddr | string | Yes| No| Random MAC address.
**System API**: This is a system API.| +| ipType | [IpType](#iptype7) | Yes| No| IP address type.
**System API**: This is a system API.| +| staticIp | [IpConfig](#ipconfig7) | Yes| No| Static IP address configuration.
**System API**: This is a system API.| ## IpType7+ -Enumerates the IP address types. +Enumerate the IP address types. **System API**: This is a system API. **System capability**: SystemCapability.Communication.WiFi.STA -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | STATIC | 0 | Static IP address.| | DHCP | 1 | IP address allocated by DHCP.| @@ -324,78 +285,12 @@ Represents IP configuration information. **System capability**: SystemCapability.Communication.WiFi.STA -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| ipAddress | number | Read only| IP address.| -| gateway | number | Read only| Gateway.| -| dnsServers | number[] | Read only| Domain name server (DNS) information.| -| domains | Array<string> | Read only| Domain information.| - - -## WifiEapConfig9+ - -Represents EAP configuration information. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Communication.WiFi.STA - -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| eapMethod | [EapMethod](#eapmethod9) | Read only| EAP authentication method.| -| phase2Method | [Phase2Method](#phase2method9) | Read only| Phase 2 authentication method.| -| identity | string | Read only| Identity Information.| -| anonymousIdentity | string | Read only| Anonymous identity.| -| password | string | Read only| Password.| -| caCertAliases | string | Read only| CA certificate alias.| -| caPath | string | Read only| CA certificate path.| -| clientCertAliases | string | Read only| Client certificate alias.| -| altSubjectMatch | string | Read only| A string to match the alternate subject.| -| domainSuffixMatch | string | Read only| A string to match the domain suffix.| -| realm | string | Read only| Realm for the passpoint credential.| -| plmn | string | Read only| Public land mobile network (PLMN) of the passpoint credential provider.| -| eapSubId | number | Read only| Sub-ID of the SIM card.| - - -## EapMethod9+ - -Enumerates the EAP authentication methods. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Communication.WiFi.STA - -| Name| Default Value| Description| -| -------- | -------- | -------- | -| EAP_NONE | 0 | Not specified.| -| EAP_PEAP | 1 | PEAP.| -| EAP_TLS | 2 | TLS.| -| EAP_TTLS | 3 | TTLS.| -| EAP_PWD | 4 | Password.| -| EAP_SIM | 5 | SIM.| -| EAP_AKA | 6 | AKA.| -| EAP_AKA_PRIME | 7 | AKA Prime.| -| EAP_UNAUTH_TLS | 8 | UNAUTH TLS.| - - -## Phase2Method9+ - -Enumerates the Phase 2 authentication methods. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Communication.WiFi.STA - -| Name| Default Value| Description| -| -------- | -------- | -------- | -| PHASE2_NONE | 0 | Not specified.| -| PHASE2_PAP | 1 | PAP.| -| PHASE2_MSCHAP | 2 | MS-CHAP.| -| PHASE2_MSCHAPV2 | 3 | MS-CHAPv2.| -| PHASE2_GTC | 4 | GTC .| -| PHASE2_SIM | 5 | SIM.| -| PHASE2_AKA | 6 | AKA.| -| PHASE2_AKA_PRIME | 7 | AKA Prime.| +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ipAddress | number | Yes| No| IP address.| +| gateway | number | Yes| No| Gateway.| +| dnsServers | number[] | Yes| No| Domain name server (DNS) information.| +| domains | Array<string> | Yes| No| Domain information.| ## wifi.addDeviceConfig @@ -500,122 +395,6 @@ Removes the configuration of an untrusted network. This API uses an asynchronous | callback | AsyncCallback<boolean> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.| -## wifi.addCandidateConfig9+ - -addCandidateConfig(config: WifiDeviceConfig): Promise<number> - -Adds the configuration of a candidate network. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.SET_WIFI_INFO - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Parameters** - - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| - -**Return value** - - | **Type**| **Description**| - | -------- | -------- | - | Promise<number> | Promise used to return the network configuration ID.| - - -## wifi.addCandidateConfig9+ - -addCandidateConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>): void - -Adds the configuration of a candidate network. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.SET_WIFI_INFO - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Parameters** - - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| - | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| - - -## wifi.removeCandidateConfig9+ - -removeCandidateConfig(networkId: number): Promise<void> - -Removes the configuration of a candidate network. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.SET_WIFI_INFO - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Parameters** - - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | -| networkId | number | Yes| ID of the network configuration to remove.| - -**Return value** - - | **Type**| **Description**| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - - -## wifi.removeCandidateConfig9+ - -removeCandidateConfig(networkId: number, callback: AsyncCallback<void>): void - -Removes the configuration of a candidate network. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.SET_WIFI_INFO - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Parameters** - - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | -| networkId | number | Yes| ID of the network configuration to remove.| -| callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the operation is successful, the value of **err** is **0**. If **err** is not **0**, an error has occurred.| - - -## wifi.getCandidateConfigs9+ - -getCandidateConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> - -Obtains candidate network configuration. - -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Return value** - - | **Type**| **Description**| - | -------- | -------- | - |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Candidate network configuration obtained.| - - -## wifi.connectToCandidateConfig9+ - -connectToCandidateConfig(networkId: number): void - -Connects to a candidate network. - -**Required permissions**: ohos.permission.SET_WIFI_INFO - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Parameters** - - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | networkId | number | Yes| ID of the candidate network configuration.| - - ## wifi.connectToNetwork connectToNetwork(networkId: number): boolean @@ -725,7 +504,7 @@ Obtains WLAN connection information. This API uses a promise to return the resul | Type| Description| | -------- | -------- | - | Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise used to return the WLAN connection information obtained.| + | Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise used to return the WLAN connection information.| ## wifi.getLinkedInfo @@ -770,24 +549,23 @@ Represents the WLAN connection information. **System capability**: SystemCapability.Communication.WiFi.STA -| Name| Type| Readable/Writable| Description| -| -------- | -------- | -------- | -------- | -| ssid | string | Read only| SSID of the hotspot, in UTF-8 format.| -| bssid | string | Read only| BSSID of the hotspot.| -| networkId | number | Read only| Network configuration ID.
**System API**: This is a system API.| -| rssi | number | Read only| RSSI of the hotspot, in dBm.| -| band | number | Read only| Frequency band of the WLAN AP.| -| linkSpeed | number | Read only| Speed of the WLAN AP.| -| frequency | number | Read only| Frequency of the WLAN AP.| -| isHidden | boolean | Read only| Whether to hide the WLAN AP.| -| isRestricted | boolean | Read only| Whether to restrict data volume at the WLAN AP.| -| chload | number | Read only| Channel load. A larger value indicates a higher load.
**System API**: This is a system API.| -| snr | number | Read only| Signal-to-noise ratio (SNR).
**System API**: This is a system API.| -| macType9+ | number | Read only| MAC address type.| -| macAddress | string | Read only| MAC address of the device.| -| ipAddress | number | Read only| IP address of the device that sets up the WLAN connection.| -| suppState | [SuppState](#suppstate) | Read only| Supplicant state.
**System API**: This is a system API.| -| connState | [ConnState](#connstate) | Read only| WLAN connection state.| +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| +| bssid | string | Yes| No| BSSID of the hotspot.| +| networkId | number | Yes| No| Network configuration ID.
**System API**: This is a system API.| +| rssi | number | Yes| No| RSSI of the hotspot, in dBm.| +| band | number | Yes| No| Frequency band of the WLAN AP.| +| linkSpeed | number | Yes| No| Speed of the WLAN AP.| +| frequency | number | Yes| No| Frequency of the WLAN AP.| +| isHidden | boolean | Yes| No| Whether to hide the WLAN AP.| +| isRestricted | boolean | Yes| No| Whether to restrict data volume at the WLAN AP.| +| chload | number | Yes| No| Channel load. A larger value indicates a higher load.
**System API**: This is a system API.| +| snr | number | Yes| No| Signal-to-noise ratio (SNR).
**System API**: This is a system API.| +| macAddress | string | Yes| No| MAC address of the device.| +| ipAddress | number | Yes| No| IP address of the device that sets up the WLAN connection.| +| suppState | [SuppState](#suppstate) | Yes| No| Supplicant state.
**System API**: This is a system API.| +| connState | [ConnState](#connstate) | Yes| No| WLAN connection state.| ## ConnState @@ -796,7 +574,7 @@ Enumerates the WLAN connection states. **System capability**: SystemCapability.Communication.WiFi.STA -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | SCANNING | 0 | The device is scanning for available APs.| | CONNECTING | 1 | A WLAN connection is being established.| @@ -816,7 +594,7 @@ Enumerates the supplicant states. **System capability**: SystemCapability.Communication.WiFi.STA -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | DISCONNECTED | 0 | The supplicant is disconnected from the AP.| | INTERFACE_DISABLED | 1 | The network interface is disabled.| @@ -871,16 +649,16 @@ Obtains the features supported by this device. | Value| Description| | -------- | -------- | -| 0x0001 | WLAN infrastructure mode. | -| 0x0002 | 5 GHz feature. | -| 0x0004 | Generic Advertisement Service (GAS)/Access Network Query Protocol (ANQP) feature. | -| 0x0008 | Wi-Fi Direct. | -| 0x0010 | SoftAP. | -| 0x0040 | Wi-Fi AWare. | -| 0x8000 | WLAN AP/STA concurrency. | -| 0x8000000 | WPA3 Personal (WPA-3 SAE). | -| 0x10000000 | WPA3-Enterprise Suite B. | -| 0x20000000 | Enhanced open feature. | +| 0x0001 | WLAN infrastructure mode| +| 0x0002 | 5 GHz feature| +| 0x0004 | Generic Advertisement Service (GAS)/Access Network Query Protocol (ANQP) feature| +| 0x0008 | Wi-Fi Direct| +| 0x0010 | SoftAP| +| 0x0040 | Wi-Fi AWare| +| 0x8000 | WLAN AP/STA concurrency| +| 0x8000000 | WPA3 Personal (WPA-3 SAE)| +| 0x10000000 | WPA3-Enterprise Suite B | +| 0x20000000 | Enhanced open feature| ## wifi.isFeatureSupported7+ @@ -949,15 +727,15 @@ Represents IP information. **System capability**: SystemCapability.Communication.WiFi.STA -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| ipAddress | number | Read only| IP address.| -| gateway | number | Read only| Gateway.| -| netmask | number | Read only| Subnet mask.| -| primaryDns | number | Read only| IP address of the preferred DNS server.| -| secondDns | number | Read only| IP address of the alternate DNS server.| -| serverIp | number | Read only| IP address of the DHCP server.| -| leaseDuration | number | Read only| Lease duration of the IP address.| +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ipAddress | number | Yes| No| IP address.| +| gateway | number | Yes| No| Gateway.| +| netmask | number | Yes| No| Subnet mask.| +| primaryDns | number | Yes| No| IP address of the preferred DNS server.| +| secondDns | number | Yes| No| IP address of the alternate DNS server.| +| serverIp | number | Yes| No| IP address of the DHCP server.| +| leaseDuration | number | Yes| No| Lease duration of the IP address.| ## wifi.getCountryCode7+ @@ -1237,13 +1015,13 @@ Represents the hotspot configuration. **System capability**: SystemCapability.Communication.WiFi.AP.Core -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| ssid | string | Read only| SSID of the hotspot, in UTF-8 format.| -| securityType | [WifiSecurityType](#wifisecuritytype) | Read only| Security type.| -| band | number | Read only| Hotspot band. The value **1** stands for 2.4 GHz, the value **2** for 5 GHz, and the value **3** for dual band.| -| preSharedKey | string | Read only| PSK of the hotspot.| -| maxConn | number | Read only| Maximum number of connections allowed.| +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| +| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| Security type.| +| band | number | Yes| No| Hotspot band. The value **1** stands for 2.4 GHz, the value **2** for 5 GHz, and the value **3** for dual band.| +| preSharedKey | string | Yes| No| PSK of the hotspot.| +| maxConn | number | Yes| No| Maximum number of connections allowed.| ## wifi.getHotspotConfig7+ @@ -1292,11 +1070,11 @@ Represents the station information. **System capability**: SystemCapability.Communication.WiFi.AP.Core -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| name | string | Read only| Device name.| -| macAddress | string | Read only| MAC address.| -| ipAddress | string | Read only| IP address.| +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| name | string | Yes| No| Device name.| +| macAddress | string | Yes| No| MAC address.| +| ipAddress | string | Yes| No| IP address.| ## wifi.getP2pLinkedInfo8+ @@ -1323,11 +1101,11 @@ Represents the P2P link information. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Type| Readable/Writable| Description| -| -------- | -------- | -------- | -------- | -| connectState | [P2pConnectState](#p2pconnectstate8) | Read only| P2P connection state.| -| isGroupOwner | boolean | Read only| Whether the device is the group owner.| -| groupOwnerAddr | string | Read only| MAC address of the group. +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| connectState | [P2pConnectState](#p2pconnectstate8) | Yes| No| P2P connection state.| +| isGroupOwner | boolean | Yes| No| Whether the device is the group owner.| +| groupOwnerAddr | string | Yes| No| MAC address of the group. ## P2pConnectState8+ @@ -1336,7 +1114,7 @@ Enumerates the P2P connection states. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | DISCONNECTED | 0 | Disconnected.| | CONNECTED | 1 | Connected.| @@ -1373,7 +1151,7 @@ Obtains the current P2P group information. This API uses a promise to return the | Type| Description| | -------- | -------- | - | Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | Promise used to return the group information obtained.| + | Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | Promise used to return the P2P group information obtained.| ## wifi.getCurrentGroup8+ @@ -1433,13 +1211,13 @@ Represents the P2P device information. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Type| Readable/Writable| Description| -| -------- | -------- | -------- | -------- | -| deviceName | string | Read only| Device name.| -| deviceAddress | string | Read only| MAC address of the device.| -| primaryDeviceType | string | Read only| Type of the primary device.| -| deviceStatus | [P2pDeviceStatus](#p2pdevicestatus8) | Read only| Device status.| -| groupCapabilitys | number | Read only| Group capabilities.| +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| deviceName | string | Yes| No| Device name.| +| deviceAddress | string | Yes| No| MAC address of the device.| +| primaryDeviceType | string | Yes| No| Type of the primary device.| +| deviceStatus | [P2pDeviceStatus](#p2pdevicestatus8) | Yes| No| Device status.| +| groupCapabilitys | number | Yes| No| Group capabilities.| ## P2pDeviceStatus8+ @@ -1448,7 +1226,7 @@ Enumerates the P2P device states. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | CONNECTED | 0 | Connected.| | INVITED | 1 | Invited.| @@ -1457,40 +1235,6 @@ Enumerates the P2P device states. | UNAVAILABLE | 4 | Unavailable.| -## wifi.getP2pLocalDevice9+ - -getP2pLocalDevice(): Promise<WifiP2pDevice> - -Obtains the local device information in the P2P connection. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG - -**System capability**: SystemCapability.Communication.WiFi.P2P - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<[WifiP2pDevice](#wifip2pdevice8)> | Promise used to return the local device information obtained.| - - -## wifi.getP2pLocalDevice9+ - -getP2pLocalDevice(callback: AsyncCallback<WifiP2pDevice>): void - -Obtains the local device information in the P2P connection. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG - -**System capability**: SystemCapability.Communication.WiFi.P2P - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiP2pDevice](#wifip2pdevice8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the local device information obtained. If **err** is not **0**, an error has occurred.| - - ## wifi.createGroup8+ createGroup(config: WifiP2PConfig): boolean @@ -1520,13 +1264,13 @@ Represents P2P group configuration. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Type| Readable/Writable| Description| -| -------- | -------- | -------- | -------- | -| deviceAddress | string | Read only| Device address.| -| netId | number | Read only| Network ID. The value **-1** indicates a temporary group, and **-2** indicates a persistent group.| -| passphrase | string | Read only| Passphrase of the group.| -| groupName | string | Read only| Name of the group.| -| goBand | [GroupOwnerBand](#groupownerband8) | Read only| Frequency band of the group.| +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| deviceAddress | string | Yes| No| Device address.| +| netId | number | Yes| No| Network ID. The value **-1** indicates a temporary group, and **-2** indicates a persistent group.| +| passphrase | string | Yes| No| Passphrase of the group.| +| groupName | string | Yes| No| Name of the group.| +| goBand | [GroupOwnerBand](#groupownerband8) | Yes| No| Frequency band of the group.| ## GroupOwnerBand8+ @@ -1535,7 +1279,7 @@ Enumerates the P2P group frequency bands. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | GO_BAND_AUTO | 0 | Auto.| | GO_BAND_2GHZ | 1 | 2 GHz.| @@ -1727,61 +1471,23 @@ Deletes a persistent group. | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -## wifi.getP2pGroups9+ - -getP2pGroups(): Promise<Array<WifiP2pGroupInfo>> - -Obtains information about all P2P groups. This API uses a promise to return the result. - -**System API**: This is a system API. - -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION - -**System capability**: SystemCapability.Communication.WiFi.P2P - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> > | Promise used to return the group information obtained.| - - ## WifiP2pGroupInfo8+ Represents the P2P group information. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Type| Readable/Writable| Description| -| -------- | -------- | -------- | -------- | -| isP2pGo | boolean | Read only| Whether the device is the group owner.| -| ownerInfo | [WifiP2pDevice](#wifip2pdevice8) | Read only| Device information of the group.| -| passphrase | string | Read only| Passphrase of the group.| -| interface | string | Read only| Interface name.| -| groupName | string | Read only| Group name.| -| networkId | number | Read only| Network ID.| -| frequency | number | Read only| Frequency of the group.| -| clientDevices | [WifiP2pDevice[]](#wifip2pdevice8) | Read only| List of connected devices.| -| goIpAddress | string | Read only| IP address of the group.| - - -## wifi.getP2pGroups9+ - -getP2pGroups(callback: AsyncCallback<Array<WifiP2pGroupInfo>>): void - -Obtains information about all P2P groups. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION - -**System capability**: SystemCapability.Communication.WiFi.P2P - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo8)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| isP2pGo | boolean | Yes| No| Whether the device is the group owner.| +| ownerInfo | [WifiP2pDevice](#wifip2pdevice8) | Yes| No| Device information of the group.| +| passphrase | string | Yes| No| Passphrase of the group.| +| interface | string | Yes| No| Interface name.| +| groupName | string | Yes| No| Group name.| +| networkId | number | Yes| No| Network ID.| +| frequency | number | Yes| No| Frequency of the group.| +| clientDevices | [WifiP2pDevice[]](#wifip2pdevice8) | Yes| No| List of connected devices.| +| goIpAddress | string | Yes| No| IP address of the group.| ## wifi.setDeviceName8+ @@ -1830,10 +1536,10 @@ Registers the WLAN state change events. | **Value**| **Description**| | -------- | -------- | -| 0 | Deactivated. | -| 1 | Activated. | -| 2 | Activating. | -| 3 | Deactivating. | +| 0 | Deactivated| +| 1 | Activated| +| 2 | Activating| +| 3 | Deactivating| ## wifi.off('wifiStateChange')7+ @@ -2012,10 +1718,10 @@ Registers the hotspot state change events. | **Value**| **Description**| | -------- | -------- | -| 0 | Deactivated. | -| 1 | Activated. | -| 2 | Activating. | -| 3 | Deactivating. | +| 0 | Deactivated| +| 1 | Activated| +| 2 | Activating| +| 3 | Deactivating| ## wifi.off('hotspotStateChange')7+ @@ -2057,11 +1763,11 @@ Registers the P2P state change events. | **Value**| **Description**| | -------- | -------- | -| 1 | Available. | -| 2 | Opening. | -| 3 | Opened. | -| 4 | Closing. | -| 5 | Closed. | +| 1 | Available| +| 2 | Opening| +| 3 | Opened| +| 4 | Closing| +| 5 | Closed| ## wifi.off('p2pStateChange')8+ diff --git a/en/application-dev/reference/apis/js-apis-wifiManager.md b/en/application-dev/reference/apis/js-apis-wifiManager.md new file mode 100644 index 0000000000000000000000000000000000000000..d02a9a1676fd35fa74528ac457086ac91d61dd08 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-wifiManager.md @@ -0,0 +1,2187 @@ +# @ohos.wifiManager (WLAN) + +The **WLAN** module provides basic wireless local area network (WLAN) functions, peer-to-peer (P2P) functions, and WLAN message notification services. It allows applications to communicate with other devices over WLAN. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + +```js +import wifiManager from '@ohos.wifiManager'; +``` + +## wifi.enableWifi9+ + +enableWifi(): void + +Enables WLAN. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.disableWifi9+ + +disableWifi(): void + +Disables WLAN. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.isWifiActive9+ + +isWifiActive(): boolean + +Checks whether WLAN is enabled. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if WLAN is enabled; returns **false** otherwise.| + + +## wifi.scan9+ + +scan(): void + +Starts a scan for WLAN. + +**Required permissions**: **ohos.permission.SET_WIFI_INFO** and **ohos.permission.LOCATION** + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.getScanResults9+ + +getScanResults(): Promise<Array<WifiScanInfo>> + +Obtains the scan result. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_PEERS_MAC (or ohos.permission.LOCATION) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | Promise< Array<[WifiScanInfo](#wifiscaninfo)> > | Promise used to return the detected hotspots.| + + +## wifi.getScanResults9+ + +getScanResults(callback: AsyncCallback<Array<WifiScanInfo>>): void + +Obtains the scan result. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_PEERS_MAC (or ohos.permission.LOCATION) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback< Array<[WifiScanInfo](#wifiscaninfo)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the detected hotspots. Otherwise, **err** is a non-zero value and **data** is empty.| + +**Example** + ```js + import wifi from '@ohos.wifi'; + + wifi.getScanInfos((err, result) => { + if (err) { + console.error("get scan info error"); + return; + } + + var len = Object.keys(result).length; + console.log("wifi received scan info: " + len); + for (var i = 0; i < len; ++i) { + console.info("ssid: " + result[i].ssid); + console.info("bssid: " + result[i].bssid); + console.info("capabilities: " + result[i].capabilities); + console.info("securityType: " + result[i].securityType); + console.info("rssi: " + result[i].rssi); + console.info("band: " + result[i].band); + console.info("frequency: " + result[i].frequency); + console.info("channelWidth: " + result[i].channelWidth); + console.info("timestamp: " + result[i].timestamp); + } + }); + + wifi.getScanInfos().then(result => { + var len = Object.keys(result).length; + console.log("wifi received scan info: " + len); + for (var i = 0; i < len; ++i) { + console.info("ssid: " + result[i].ssid); + console.info("bssid: " + result[i].bssid); + console.info("capabilities: " + result[i].capabilities); + console.info("securityType: " + result[i].securityType); + console.info("rssi: " + result[i].rssi); + console.info("band: " + result[i].band); + console.info("frequency: " + result[i].frequency); + console.info("channelWidth: " + result[i].channelWidth); + console.info("timestamp: " + result[i].timestamp); + } + }); + ``` + + +## WifiScanInfo9+ + +Represents WLAN hotspot information. + +**System capability**: SystemCapability.Communication.WiFi.STA + + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| Service set identifier (SSID) of the hotspot, in UTF-8 format.| +| bssid | string | Yes| No| Basic service set identifier (BSSID) of the hotspot.| +| capabilities | string | Yes| No| Hotspot capabilities.| +| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| WLAN security type.| +| rssi | number | Yes| No| Received signal strength indicator (RSSI) of the hotspot, in dBm.| +| band | number | Yes| No| Frequency band of the WLAN access point (AP).| +| frequency | number | Yes| No| Frequency of the WLAN AP.| +| channelWidth | number | Yes| No| Channel width of the WLAN AP.| +| centerFrequency0 | number | Yes| No| Center frequency of the hotspot.| +| centerFrequency1 | number | Yes| No| Center frequency of the hotspot. If the hotspot uses two non-overlapping WLAN channels, two center frequencies, namely **centerFrequency0** and **centerFrequency1**, are returned.| +| infoElems | Array<[WifiInfoElem](#wifiinfoelem9)> | Yes| No| Information elements.| +| timestamp | number | Yes| No| Timestamp.| + + +## WifiSecurityType9+ + +Enumerates the WLAN security types. + +**System capability**: SystemCapability.Communication.WiFi.Core + + +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| WIFI_SEC_TYPE_INVALID | 0 | Invalid security type.| +| WIFI_SEC_TYPE_OPEN | 1 | Open security type.| +| WIFI_SEC_TYPE_WEP | 2 | Wired Equivalent Privacy (WEP).| +| WIFI_SEC_TYPE_PSK | 3 | Pre-shared key (PSK).| +| WIFI_SEC_TYPE_SAE | 4 | Simultaneous Authentication of Equals (SAE).| +| WIFI_SEC_TYPE_EAP9+ | 5 | Extensible Authentication protocol (EAP).| +| WIFI_SEC_TYPE_EAP_SUITE_B9+ | 6 | Suite B 192-bit encryption.| +| WIFI_SEC_TYPE_OWE9+ | 7 | Opportunistic Wireless Encryption (OWE).| +| WIFI_SEC_TYPE_WAPI_CERT9+ | 8 | WLAN Authentication and Privacy Infrastructure (WAPI) in certificate-based mode (WAPI-CERT).| +| WIFI_SEC_TYPE_WAPI_PSK9+ | 9 | WAPI-PSK.| + + +## WifiInfoElem9+ + +Represents a WLAN information element. + +**System capability**: SystemCapability.Communication.WiFi.STA + + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| eid | number | Yes| No| ID of the information element.| +| content | Uint8Array | Yes| No| Content of the information element.| + + +## WifiChannelWidth9+ + +Enumerates the WLAN channel widths. + +**System capability**: SystemCapability.Communication.WiFi.STA + + +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| WIDTH_20MHZ | 0 | 20 MHz.| +| WIDTH_40MHZ | 1 | 40 MHz.| +| WIDTH_80MHZ | 2 | 80 MHz.| +| WIDTH_160MHZ | 3 | 160 MHz.| +| WIDTH_80MHZ_PLUS | 4 | 80 MHz+.| +| WIDTH_INVALID | 5 | Invalid value.| + + +## wifi.getScanResultsSync9+ + +getScanResultsSync():  Array<[WifiScanInfo](#wifiscaninfo)> + +Obtains the scan result. This API returns the result synchronously. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_PEERS_MAC (or ohos.permission.LOCATION) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + |  Array<[WifiScanInfo](#wifiscaninfo)> | Scan result obtained.| + + +## wifi.addDeviceConfig9+ + +addDeviceConfig(config: WifiDeviceConfig): Promise<number> + +Adds network configuration. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.SET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | Promise<number> | Promise used to return the ID of the added network configuration. If **-1** is returned, the network configuration fails to be added.| + +## WifiDeviceConfig9+ + +Represents the WLAN configuration. + +**System capability**: SystemCapability.Communication.WiFi.STA + + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| +| bssid | string | Yes| No| BSSID of the hotspot.| +| preSharedKey | string | Yes| No| PSK of the hotspot.| +| isHiddenSsid | boolean | Yes| No| Whether the network is hidden.| +| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| Security type.| +| creatorUid | number | Yes| No| ID of the creator.
**System API**: This is a system API.| +| disableReason | number | Yes| No| Reason for disabling WLAN.
**System API**: This is a system API.| +| netId | number | Yes| No| Network ID.
**System API**: This is a system API.| +| randomMacType | number | Yes| No| Random MAC type.
**System API**: This is a system API.| +| randomMacAddr | string | Yes| No| Random MAC address.
**System API**: This is a system API.| +| ipType | [IpType](#iptype9) | Yes| No| IP address type.
**System API**: This is a system API.| +| staticIp | [IpConfig](#ipconfig9) | Yes| No| Static IP address configuration.
**System API**: This is a system API.| +| eapConfig9+ | [WifiEapConfig](#wifieapconfig9) | Yes| No| EAP configuration.
**System API**: This is a system API.| + + +## IpType9+ + +Enumerates the IP address types. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + + +| Name| Value| Description| +| -------- | -------- | -------- | +| STATIC | 0 | Static IP address.| +| DHCP | 1 | IP address allocated by DHCP.| +| UNKNOWN | 2 | Not specified.| + + +## IpConfig9+ + +Represents IP configuration information. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ipAddress | number | Yes| No| IP address.| +| gateway | number | Yes| No| Gateway.| +| prefixLength | number | Yes| No| Subnet mask.| +| dnsServers | number[] | Yes| No| Domain name server (DNS) information.| +| domains | Array<string> | Yes| No| Domain information.| + + +## WifiEapConfig9+ + +Represents EAP configuration information. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| eapMethod | [EapMethod](#eapmethod9) | Yes| No| EAP authentication method.| +| phase2Method | [Phase2Method](#phase2method9) | Yes| No| Phase 2 authentication method.| +| identity | string | Yes| No| Identity Information.| +| anonymousIdentity | string | Yes| No| Anonymous identity.| +| password | string | Yes| No| Password.| +| caCertAliases | string | Yes| No| CA certificate alias.| +| caPath | string | Yes| No| CA certificate path.| +| clientCertAliases | string | Yes| No| Client certificate alias.| +| altSubjectMatch | string | Yes| No| A string to match the alternate subject.| +| domainSuffixMatch | string | Yes| No| A string to match the domain suffix.| +| realm | string | Yes| No| Realm for the passpoint credential.| +| plmn | string | Yes| No| Public land mobile network (PLMN) of the passpoint credential provider.| +| eapSubId | number | Yes| No| Sub-ID of the SIM card.| + + +## EapMethod9+ + +Enumerates the EAP authentication methods. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Value| Description| +| -------- | -------- | -------- | +| EAP_NONE | 0 | Not specified.| +| EAP_PEAP | 1 | PEAP.| +| EAP_TLS | 2 | TLS.| +| EAP_TTLS | 3 | TTLS.| +| EAP_PWD | 4 | Password.| +| EAP_SIM | 5 | SIM.| +| EAP_AKA | 6 | AKA.| +| EAP_AKA_PRIME | 7 | AKA Prime.| +| EAP_UNAUTH_TLS | 8 | UNAUTH TLS.| + + +## Phase2Method9+ + +Enumerates the Phase 2 authentication methods. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Value| Description| +| -------- | -------- | -------- | +| PHASE2_NONE | 0 | Not specified.| +| PHASE2_PAP | 1 | PAP.| +| PHASE2_MSCHAP | 2 | MS-CHAP.| +| PHASE2_MSCHAPV2 | 3 | MS-CHAPv2.| +| PHASE2_GTC | 4 | GTC .| +| PHASE2_SIM | 5 | SIM.| +| PHASE2_AKA | 6 | AKA.| +| PHASE2_AKA_PRIME | 7 | AKA Prime.| + + +## wifi.addDeviceConfig9+ + +addDeviceConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>): void + +Adds network configuration. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.SET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| + + +## wifi.addCandidateConfig9+ + +addCandidateConfig(config: WifiDeviceConfig): Promise<number> + +Adds the configuration of a candidate network. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | Promise<number> | Promise used to return the network configuration ID.| + + +## wifi.addCandidateConfig9+ + +addCandidateConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>): void + +Adds the configuration of a candidate network. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| + + +## wifi.removeCandidateConfig9+ + +removeCandidateConfig(networkId: number): Promise<void> + +Removes the configuration of a candidate network. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| ID of the network configuration to remove.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + + +## wifi.removeCandidateConfig9+ + +removeCandidateConfig(networkId: number, callback: AsyncCallback<void>): void + +Removes the configuration of a candidate network. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| ID of the network configuration to remove.| + | callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the operation is successful, the value of **err** is **0**. If **err** is not **0**, an error has occurred.| + + +## wifi.getCandidateConfigs9+ + +getCandidateConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> + +Obtains candidate network configuration. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Candidate network configuration obtained.| + + +## wifi.connectToCandidateConfig9+ + +connectToCandidateConfig(networkId: number): void + +Connects to a candidate network. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| ID of the candidate network configuration.| + + +## wifi.connectToNetwork9+ + +connectToNetwork(networkId: number): void + +Connects to the specified network. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| Network configuration ID.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.connectToDevice9+ + +connectToDevice(config: WifiDeviceConfig): void + +Connects to the specified network. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO, ohos.permission.SET_WIFI_CONFIG, and ohos.permissio.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: + SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.disconnect9+ + +disconnect(): void + +Disconnects the network. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: + SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.getSignalLevel9+ + +getSignalLevel(rssi: number, band: number): number + +Obtains the WLAN signal level. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | rssi | number | Yes| RSSI of the hotspot, in dBm.| + | band | number | Yes| Frequency band of the WLAN AP.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | number | Signal level obtained. The value range is [0, 4].| + + +## wifi.getLinkedInfo9+ + +getLinkedInfo(): Promise<WifiLinkedInfo> + +Obtains WLAN connection information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise used to return the WLAN connection information obtained.| + + +## wifi.getLinkedInfo9+ + +getLinkedInfo(callback: AsyncCallback<WifiLinkedInfo>): void + +Obtains WLAN connection information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiLinkedInfo](#wifilinkedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the WLAN connection information obtained. If **err** is not **0**, an error has occurred.| + +**Example** + ```js + import wifi from '@ohos.wifi'; + + wifi.getLinkedInfo((err, data) => { + if (err) { + console.error("get linked info error"); + return; + } + console.info("get wifi linked info: " + JSON.stringify(data)); + }); + + wifi.getLinkedInfo().then(data => { + console.info("get wifi linked info: " + JSON.stringify(data)); + }).catch(error => { + console.info("get linked info error"); + }); + ``` + + +## WifiLinkedInfo9+ + +Represents the WLAN connection information. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| +| bssid | string | Yes| No| BSSID of the hotspot.| +| networkId | number | Yes| No| Network configuration ID.
**System API**: This is a system API.| +| rssi | number | Yes| No| RSSI of the hotspot, in dBm.| +| band | number | Yes| No| Frequency band of the WLAN AP.| +| linkSpeed | number | Yes| No| Speed of the WLAN AP.| +| frequency | number | Yes| No| Frequency of the WLAN AP.| +| isHidden | boolean | Yes| No| Whether to hide the WLAN AP.| +| isRestricted | boolean | Yes| No| Whether to restrict data volume at the WLAN AP.| +| chload | number | Yes| No| Channel load. A larger value indicates a higher load.
**System API**: This is a system API.| +| snr | number | Yes| No| Signal-to-noise ratio (SNR).
**System API**: This is a system API.| +| macType9+ | number | Yes| No| MAC address type.| +| macAddress | string | Yes| No| MAC address of the device.| +| ipAddress | number | Yes| No| IP address of the device that sets up the WLAN connection.| +| suppState | [SuppState](#suppstate) | Yes| No| Supplicant state.
**System API**: This is a system API.| +| connState | [ConnState](#connstate) | Yes| No| WLAN connection state.| + + +## ConnState9+ + +Enumerates the WLAN connection states. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Value| Description| +| -------- | -------- | -------- | +| SCANNING | 0 | The device is scanning for available APs.| +| CONNECTING | 1 | A WLAN connection is being established.| +| AUTHENTICATING | 2 | An authentication is being performed for a WLAN connection.| +| OBTAINING_IPADDR | 3 | The IP address of the WLAN connection is being acquired.| +| CONNECTED | 4 | A WLAN connection is established.| +| DISCONNECTING | 5 | The WLAN connection is being disconnected.| +| DISCONNECTED | 6 | The WLAN connection is disconnected.| +| UNKNOWN | 7 | Failed to set up the WLAN connection.| + + +## SuppState9+ + +Enumerates the supplicant states. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Value| Description| +| -------- | -------- | -------- | +| DISCONNECTED | 0 | The supplicant is disconnected from the AP.| +| INTERFACE_DISABLED | 1 | The network interface is disabled.| +| INACTIVE | 2 | The supplicant is inactive.| +| SCANNING | 3 | The supplicant is scanning for a WLAN connection.| +| AUTHENTICATING | 4 | The supplicant is being authenticated.| +| ASSOCIATING | 5 | The supplicant is being associated with an AP.| +| ASSOCIATED | 6 | The supplicant is associated with an AP.| +| FOUR_WAY_HANDSHAKE | 7 | A four-way handshake is being performed for the supplicant.| +| GROUP_HANDSHAKE | 8 | A group handshake is being performed for the supplicant.| +| COMPLETED | 9 | The authentication is complete.| +| UNINITIALIZED | 10 | The supplicant failed to set up the connection.| +| INVALID | 11 | Invalid value.| + + +## wifi.isConnected9+ + +isConnected(): boolean + +Checks whether the WLAN is connected. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.| + + +## wifi.getSupportedFeatures9+ + +getSupportedFeatures(): number + +Obtains the features supported by this device. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | number | Feature value. | + +**Feature IDs** + +| Value| Description| +| -------- | -------- | +| 0x0001 | WLAN infrastructure mode| +| 0x0002 | 5 GHz feature| +| 0x0004 | Generic Advertisement Service (GAS)/Access Network Query Protocol (ANQP) feature| +| 0x0008 | Wi-Fi Direct| +| 0x0010 | SoftAP| +| 0x0040 | Wi-Fi AWare| +| 0x8000 | WLAN AP/STA concurrency| +| 0x8000000 | WPA3 Personal (WPA-3 SAE)| +| 0x10000000 | WPA3-Enterprise Suite B | +| 0x20000000 | Enhanced open feature| + + +## wifi.isFeatureSupported9+ + +isFeatureSupported(featureId: number): boolean + +Checks whether the device supports the specified WLAN feature. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.Core + +**Parameters** + + + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | featureId | number | Yes| Feature ID.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| + + +## wifi.getDeviceMacAddress9+ + +getDeviceMacAddress(): string[] + +Obtains the device MAC address. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_LOCAL_MAC and ohos.permission.GET_WIFI_INFO (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | string[] | MAC address obtained.| + + +## wifi.getIpInfo9+ + +getIpInfo(): IpInfo + +Obtains IP information. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | [IpInfo](#ipinfo9) | IP information obtained.| + + +## IpInfo9+ + +Represents IP information. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ipAddress | number | Yes| No| IP address.| +| gateway | number | Yes| No| Gateway.| +| netmask | number | Yes| No| Subnet mask.| +| primaryDns | number | Yes| No| IP address of the preferred DNS server.| +| secondDns | number | Yes| No| IP address of the alternate DNS server.| +| serverIp | number | Yes| No| IP address of the DHCP server.| +| leaseDuration | number | Yes| No| Lease duration of the IP address.| + + +## wifi.getCountryCode9+ + +getCountryCode(): string + +Obtains the country code. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | string | Country code obtained.| + + +## wifi.reassociate9+ + +reassociate(): void + +Re-associates with the network. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.reconnect9+ + +reconnect(): void + +Reconnects to the network. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.getDeviceConfigs9+ + +getDeviceConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> + +Obtains network configuration. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.GET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Array of network configuration obtained.| + + +## wifi.updateNetwork9+ + +updateNetwork(config: WifiDeviceConfig): number + +Updates network configuration. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.SET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | +| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| New WLAN configuration.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | number | ID of the updated network configuration. The value **-1** indicates that the operation has failed.| + + +## wifi.disableNetwork9+ + +disableNetwork(netId: number): void + +Disables network configuration. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | netId | number | Yes| ID of the network configuration to disable.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.removeAllNetwork9+ + +removeAllNetwork(): void + +Removes the configuration of all networks. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.removeDevice9+ + +removeDevice(id: number): void + +Removes the specified network configuration. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | +| id | number | Yes| ID of the network configuration to remove.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.enableHotspot9+ + +enableHotspot(): void + +Enables this hotspot. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.disableHotspot9+ + +disableHotspot(): void + +Disables this hotspot. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.isHotspotDualBandSupported9+ + +isHotspotDualBandSupported(): boolean + +Checks whether the hotspot supports dual band. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| + + +## wifi.isHotspotActive9+ + +isHotspotActive(): boolean + +Checks whether this hotspot is active. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the hotspot is active; returns **false** otherwise.| + + +## wifi.setHotspotConfig9+ + +setHotspotConfig(config: HotspotConfig): void + +Sets hotspot configuration. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [HotspotConfig](#hotspotconfig9) | Yes| Hotspot configuration to set.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## HotspotConfig9+ + +Represents the hotspot configuration. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| +| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| Security type.| +| band | number | Yes| No| Hotspot band. The value **1** stands for 2.4 GHz, the value **2** for 5 GHz, and the value **3** for dual band.| +| preSharedKey | string | Yes| No| PSK of the hotspot.| +| maxConn | number | Yes| No| Maximum number of connections allowed.| + + +## wifi.getHotspotConfig9+ + +getHotspotConfig(): HotspotConfig + +obtains hotspot configuration. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | [HotspotConfig](#hotspotconfig9) | Hotspot configuration obtained.| + + +## wifi.getStations9+ + +getStations():  Array<[StationInfo](#stationinfo9)> + +Obtains information about the connected stations. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + |  Array<[StationInfo](#stationinfo9)> | Connected stations obtained.| + + +## StationInfo9+ + +Represents the station information. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| name | string | Yes| No| Device name.| +| macAddress | string | Yes| No| MAC address.| +| ipAddress | string | Yes| No| IP address.| + + +## wifi.getP2pLinkedInfo9+ + +getP2pLinkedInfo(): Promise<WifiP2pLinkedInfo> + +Obtains P2P link information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Promise used to return the P2P link information obtained.| + + + +## WifiP2pLinkedInfo9+ + +Represents the P2P link information. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| connectState | [P2pConnectState](#p2pconnectstate9) | Yes| No| P2P connection state.| +| isGroupOwner | boolean | Yes| No| Whether the device is the group owner.| +| groupOwnerAddr | string | Yes| No| MAC address of the group. + + +## P2pConnectState9+ + +Enumerates the P2P connection states. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Value| Description| +| -------- | -------- | -------- | +| DISCONNECTED | 0 | Disconnected.| +| CONNECTED | 1 | Connected.| + + +## wifi.getP2pLinkedInfo9+ + +getP2pLinkedInfo(callback: AsyncCallback<WifiP2pLinkedInfo>): void + +Obtains P2P link information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the P2P link information. If **err** is not **0**, an error has occurred.| + + +## wifi.getCurrentGroup9+ + +getCurrentGroup(): Promise<WifiP2pGroupInfo> + +Obtains the current P2P group information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> | Promise used to return the P2P group information obtained.| + + +## wifi.getCurrentGroup9+ + +getCurrentGroup(callback: AsyncCallback<WifiP2pGroupInfo>): void + +Obtains the current P2P group information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| + + +## wifi.getP2pPeerDevices9+ + +getP2pPeerDevices(): Promise<WifiP2pDevice[]> + +Obtains the peer device list in the P2P connection. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pDevice[]](#wifip2pdevice9)> | Promise used to return the peer device list.| + + +## wifi.getP2pPeerDevices9+ + +getP2pPeerDevices(callback: AsyncCallback<WifiP2pDevice[]>): void + +Obtains the peer device list in the P2P connection. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pDevice[]](#wifip2pdevice9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the peer device list obtained. If **err** is not **0**, an error has occurred.| + + +## WifiP2pDevice9+ + +Represents the P2P device information. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| deviceName | string | Yes| No| Device name.| +| deviceAddress | string | Yes| No| MAC address of the device.| +| primaryDeviceType | string | Yes| No| Type of the primary device.| +| deviceStatus | [P2pDeviceStatus](#p2pdevicestatus9) | Yes| No| Device status.| +| groupCapabilities | number | Yes| No| Group capabilities.| + + +## P2pDeviceStatus9+ + +Enumerates the P2P device states. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Value| Description| +| -------- | -------- | -------- | +| CONNECTED | 0 | Connected.| +| INVITED | 1 | Invited.| +| FAILED | 2 | Failed.| +| AVAILABLE | 3 | Available.| +| UNAVAILABLE | 4 | Unavailable.| + + +## wifi.getP2pLocalDevice9+ + +getP2pLocalDevice(): Promise<WifiP2pDevice> + +Obtains the local device information in the P2P connection. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pDevice](#wifip2pdevice9)> | Promise used to return the local device information obtained.| + + +## wifi.getP2pLocalDevice9+ + +getP2pLocalDevice(callback: AsyncCallback<WifiP2pDevice>): void + +Obtains the local device information in the P2P connection. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pDevice](#wifip2pdevice9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the local device information obtained. If **err** is not **0**, an error has occurred.| + + +## wifi.createGroup9+ + +createGroup(config: WifiP2PConfig): void + +Creates a P2P group. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiP2PConfig](#wifip2pconfig9) | Yes| Group configuration.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## WifiP2PConfig9+ + +Represents P2P group configuration. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| deviceAddress | string | Yes| No| Device address.| +| netId | number | Yes| No| Network ID. The value **-1** indicates a temporary group, and **-2** indicates a persistent group.| +| passphrase | string | Yes| No| Passphrase of the group.| +| groupName | string | Yes| No| Name of the group.| +| goBand | [GroupOwnerBand](#groupownerband9) | Yes| No| Frequency band of the group.| + + +## GroupOwnerBand9+ + +Enumerates the P2P group frequency bands. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Value| Description| +| -------- | -------- | -------- | +| GO_BAND_AUTO | 0 | Auto.| +| GO_BAND_2GHZ | 1 | 2 GHz.| +| GO_BAND_5GHZ | 2 | 5 GHz.| + + +## wifi.removeGroup9+ + +removeGroup(): void + +Removes this P2P group. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.p2pConnect9+ + +p2pConnect(config: WifiP2PConfig): void + +Sets up a P2P connection. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiP2PConfig](#wifip2pconfig9) | Yes| P2P group configuration.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +**Example** + ```js + import wifi from '@ohos.wifi'; + + var recvP2pConnectionChangeFunc = result => { + console.info("p2p connection change receive event: " + JSON.stringify(result)); + wifi.getP2pLinkedInfo((err, data) => { + if (err) { + console.error('failed to get getP2pLinkedInfo: ' + JSON.stringify(err)); + return; + } + console.info("get getP2pLinkedInfo: " + JSON.stringify(data)); + }); + } + wifi.on("p2pConnectionChange", recvP2pConnectionChangeFunc); + + var recvP2pDeviceChangeFunc = result => { + console.info("p2p device change receive event: " + JSON.stringify(result)); + } + wifi.on("p2pDeviceChange", recvP2pDeviceChangeFunc); + + var recvP2pPeerDeviceChangeFunc = result => { + console.info("p2p peer device change receive event: " + JSON.stringify(result)); + wifi.getP2pPeerDevices((err, data) => { + if (err) { + console.error('failed to get peer devices: ' + JSON.stringify(err)); + return; + } + console.info("get peer devices: " + JSON.stringify(data)); + var len = Object.keys(data).length; + for (var i = 0; i < len; ++i) { + if (data[i].deviceName === "my_test_device") { + console.info("p2p connect to test device: " + data[i].deviceAddress); + var config = { + "deviceAddress":data[i].deviceAddress, + "netId":-2, + "passphrase":"", + "groupName":"", + "goBand":0, + } + wifi.p2pConnect(config); + } + } + }); + } + wifi.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); + + var recvP2pPersistentGroupChangeFunc = () => { + console.info("p2p persistent group change receive event"); + + wifi.getCurrentGroup((err, data) => { + if (err) { + console.error('failed to get current group: ' + JSON.stringify(err)); + return; + } + console.info("get current group: " + JSON.stringify(data)); + }); + } + wifi.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); + + setTimeout(function() {wifi.off("p2pConnectionChange", recvP2pConnectionChangeFunc);}, 125 * 1000); + setTimeout(function() {wifi.off("p2pDeviceChange", recvP2pDeviceChangeFunc);}, 125 * 1000); + setTimeout(function() {wifi.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);}, 125 * 1000); + setTimeout(function() {wifi.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);}, 125 * 1000); + console.info("start discover devices -> " + wifi.startDiscoverDevices()); + ``` + +## wifi.p2pCancelConnect9+ + +p2pCancelConnect(): void + +Cancels this P2P connection. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.startDiscoverDevices9+ + +startDiscoverDevices(): void + +Starts to discover devices. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.stopDiscoverDevices9+ + +stopDiscoverDevices(): void + +Stops discovering devices. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.deletePersistentGroup9+ + +deletePersistentGroup(netId: number): void + +Deletes a persistent group. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | netId | number | Yes| ID of the group to delete.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.getP2pGroups9+ + +getP2pGroups(): Promise<Array<WifiP2pGroupInfo>> + +Obtains information about all P2P groups. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> > | Promise used to return the group information obtained.| + + +## WifiP2pGroupInfo9+ + +Represents the P2P group information. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| isP2pGo | boolean | Yes| No| Whether the device is the group owner.| +| ownerInfo | [WifiP2pDevice](#wifip2pdevice9) | Yes| No| Device information of the group.| +| passphrase | string | Yes| No| Passphrase of the group.| +| interface | string | Yes| No| Interface name.| +| groupName | string | Yes| No| Group name.| +| networkId | number | Yes| No| Network ID.| +| frequency | number | Yes| No| Frequency of the group.| +| clientDevices | [WifiP2pDevice[]](#wifip2pdevice9) | Yes| No| List of connected devices.| +| goIpAddress | string | Yes| No| IP address of the group.| + + +## wifi.getP2pGroups9+ + +getP2pGroups(callback: AsyncCallback<Array<WifiP2pGroupInfo>>): void + +Obtains information about all P2P groups. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo9)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| + + +## wifi.setDeviceName9+ + +setDeviceName(devName: string): void + +Sets the device name. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | devName | string | Yes| Device name to set.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.on('wifiStateChange')9+ + +on(type: "wifiStateChange", callback: Callback<number>): void + +Registers the WLAN state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the WLAN state.| + +**WLAN states** + +| **Value**| **Description**| +| -------- | -------- | +| 0 | Deactivated| +| 1 | Activated| +| 2 | Activating| +| 3 | Deactivating| + + +## wifi.off('wifiStateChange')9+ + +off(type: "wifiStateChange", callback?: Callback<number>): void + +Unregisters the WLAN state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiStateChange**.| + | callback | Callback<number> | No| Callback for the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + +**Example** + ```js + import wifi from '@ohos.wifi'; + + var recvPowerNotifyFunc = result => { + console.info("Receive power state change event: " + result); + } + + // Register an event. + wifi.on("wifiStateChange", recvPowerNotifyFunc); + + // Unregister an event. + wifi.off("wifiStateChange", recvPowerNotifyFunc); + ``` + + +## wifi.on('wifiConnectionChange')7+ + +on(type: "wifiConnectionChange", callback: Callback<number>): void + +Registers the WLAN connection state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiConnectionChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the WLAN connection state.| + +**WLAN connection states** + +| **Value**| **Description**| +| -------- | -------- | +| 0 | Disconnected.| +| 1 | Connected.| + + +## wifi.off('wifiConnectionChange')9+ + +off(type: "wifiConnectionChange", callback?: Callback<number>): void + +Unregisters the WLAN connection state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiConnectionChange**.| + | callback | Callback<number> | No| Callback for the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('wifiScanStateChange')9+ + +on(type: "wifiScanStateChange", callback: Callback<number>): void + +Registers the WLAN scan state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiScanStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the WLAN scan state.| + +**WLAN scan states** + +| **Value**| **Description**| +| -------- | -------- | +| 0 | Scan failed.| +| 1 | Scan successful.| + + +## wifi.off('wifiScanStateChange')9+ + +off(type: "wifiScanStateChange", callback?: Callback<number>): void + +Unregisters the WLAN scan state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiScanStateChange**.| +| callback | Callback<number> | No| Callback for the WLAN scan state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('wifiRssiChange')9+ + +on(type: "wifiRssiChange", callback: Callback<number>): void + +Registers the RSSI change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiRssiChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the RSSI, in dBm.| + + +## wifi.off('wifiRssiChange')9+ + +off(type: "wifiRssiChange", callback?: Callback<number>): void + +Unregisters the RSSI change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiRssiChange**.| +| callback | Callback<number> | No| Callback for the RSSI. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('hotspotStateChange')9+ + +on(type: "hotspotStateChange", callback: Callback<number>): void + +Registers the hotspot state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **hotspotStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the hotspot state.| + +**Hotspot states** + +| **Value**| **Description**| +| -------- | -------- | +| 0 | Deactivated| +| 1 | Activated| +| 2 | Activating| +| 3 | Deactivating| + + +## wifi.off('hotspotStateChange')9+ + +off(type: "hotspotStateChange", callback?: Callback<number>): void + +Unregisters the hotspot state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **hotspotStateChange**.| +| callback | Callback<number> | No| Callback for the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('p2pStateChange')9+ + +on(type: "p2pStateChange", callback: Callback<number>): void + +Registers the P2P state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the P2P state.| + +**P2P states** + +| **Value**| **Description**| +| -------- | -------- | +| 1 | Available| +| 2 | Opening| +| 3 | Opened| +| 4 | Closing| +| 5 | Closed| + +## wifi.off('p2pStateChange')9+ + +off(type: "p2pStateChange", callback?: Callback<number>): void + +Unregisters the P2P state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pStateChange**.| +| callback | Callback<number> | No| Callback for the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + + ## wifi.on('p2pConnectionChange')9+ + +on(type: "p2pConnectionChange", callback: Callback<WifiP2pLinkedInfo>): void + +Registers the P2P connection state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pConnectionChange**.| + | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Yes| Callback invoked to return the P2P connection state.| + + +## wifi.off('p2pConnectionChange')9+ + +off(type: "p2pConnectionChange", callback?: Callback<WifiP2pLinkedInfo>): void + +Unregisters the P2P connection state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pConnectionChange**.| + | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | No| Callback for the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('p2pDeviceChange')9+ + +on(type: "p2pDeviceChange", callback: Callback<WifiP2pDevice>): void + +Registers the P2P device state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDeviceChange**.| + | callback | Callback<[WifiP2pDevice](#wifip2pdevice9)> | Yes| Callback invoked to return the P2P device state.| + + +## wifi.off('p2pDeviceChange')9+ + +off(type: "p2pDeviceChange", callback?: Callback<WifiP2pDevice>): void + +Unregisters the P2P device state change events. + +**Required permissions**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDeviceChange**.| + | callback | Callback<[WifiP2pDevice](#wifip2pdevice9)> | No| Callback for the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('p2pPeerDeviceChange')9+ + +on(type: "p2pPeerDeviceChange", callback: Callback<WifiP2pDevice[]>): void + +Registers the P2P peer device state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| + | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice9)> | Yes| Callback invoked to return the P2P peer device state.| + + +## wifi.off('p2pPeerDeviceChange')9+ + +off(type: "p2pPeerDeviceChange", callback?: Callback<WifiP2pDevice[]>): void + +Unregisters the P2P peer device state change events. + +**Required permissions**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| + | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice9)> | No| Callback for the peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('p2pPersistentGroupChange')9+ + +on(type: "p2pPersistentGroupChange", callback: Callback<void>): void + +Registers the P2P persistent group state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| + | callback | Callback<void> | Yes| Callback invoked to return the P2P persistent group state.| + + +## wifi.off('p2pPersistentGroupChange')9+ + +off(type: "p2pPersistentGroupChange", callback?: Callback<void>): void + +Unregisters the P2P persistent group state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| + | callback | Callback<void> | No| Callback for the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('p2pDiscoveryChange')9+ + +on(type: "p2pDiscoveryChange", callback: Callback<number>): void + +Registers the P2P device discovery state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the P2P device discovery state.| + +**P2P discovered device states** + +| **Value**| **Description**| +| -------- | -------- | +| 0 | Initial state.| +| 1 | Discovered.| + + +## wifi.off('p2pDiscoveryChange')9+ + +off(type: "p2pDiscoveryChange", callback?: Callback<number>): void + +Unregisters the P2P device discovery state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| + | callback | Callback<number> | No| Callback for the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| diff --git a/en/application-dev/reference/apis/js-apis-wifiManagerExt.md b/en/application-dev/reference/apis/js-apis-wifiManagerExt.md new file mode 100644 index 0000000000000000000000000000000000000000..4c93d07e02f3db72cb30a9735fc1497381d822c6 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-wifiManagerExt.md @@ -0,0 +1,150 @@ +# @ohos.wifiManagerExt + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +The APIs described in this document are used only for non-universal products, such as routers. + + +## Modules to Import + +```js +import wifiManagerExt from '@ohos.wifiManagerExt'; +``` + +## wifiext.enableHotspot + +enableHotspot(): boolean; + +Enables the WLAN hotspot. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifiext.disableHotspot + +disableHotspot(): boolean; + +Disables the WLAN hotspot. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifiext.getSupportedPowerModel + +getSupportedPowerModel(): Promise<Array<PowerModel>> + +Obtains the supported power models. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<Array<[PowerModel](#powermodel)>> | Promise used to return the power models obtained.| + + +## PowerModel + +Enumerates the power models. + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +| Name| Value| Description| +| -------- | -------- | -------- | +| SLEEPING | 0 | Sleeping| +| GENERAL | 1 | General| +| THROUGH_WALL | 2 | Through_wall| + + +## wifiext.getSupportedPowerModel + +getSupportedPowerModel(callback: AsyncCallback<Array<PowerModel>>): void + +Obtains the supported power models. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<Array<[PowerModel](#powermodel)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is 0 and **data** is the power models obtained. If **err** is not **0**, an error has occurred.| + + +## wifiext.getPowerModel + +getPowerModel(): Promise<PowerModel> + +Obtains the power model. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[PowerModel](#powermodel)> | Promise used to return the power model obtained.| + + +## wifiext.getPowerModel + +getPowerModel(callback: AsyncCallback<PowerModel>): void + +Obtains the power model. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[PowerModel](#powermodel)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the power model obtained. If **err** is not **0**, an error has occurred.| + + +## wifiext.setPowerModel + +setPowerModel(model: PowerModel) : boolean; + + Sets the power model. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | model | [PowerModel](#powermodel) | Yes| Power model to set.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| diff --git a/en/application-dev/reference/apis/js-apis-wifiext.md b/en/application-dev/reference/apis/js-apis-wifiext.md index 9ce53d76e2517eb199067f779168fb9fe9d8b032..70961ffe279bf5543bbe28168f8571a54ca46651 100644 --- a/en/application-dev/reference/apis/js-apis-wifiext.md +++ b/en/application-dev/reference/apis/js-apis-wifiext.md @@ -1,7 +1,9 @@ -# WLAN +# @ohos.wifiext + This **wifiext** module provides WLAN extension interfaces for non-universal products. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. The APIs described in this document are used only for non-universal products, such as routers. @@ -69,7 +71,7 @@ Enumerates the power models. **System capability**: SystemCapability.Communication.WiFi.AP.Extension -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | SLEEPING | 0 | Sleeping| | GENERAL | 1 | General| @@ -90,7 +92,7 @@ Obtains the supported power models. This API uses an asynchronous callback to re | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[PowerModel](#powermodel)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is 0 and **data** is the power models obtained. If **err** is not **0**, an error has occurred.| + | callback | AsyncCallback<Array<[PowerModel](#powermodel)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is 0 and **data** is the power models obtained. If **err** is not **0**, an error has occurred.| ## wifiext.getPowerModel @@ -141,7 +143,7 @@ setPowerModel(model: PowerModel) : boolean; | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | model | AsyncCallback<[PowerModel](#powermodel)> | Yes| Power model to set.| + | model | [PowerModel](#powermodel) | Yes| Power model to set.| **Return value** diff --git a/en/application-dev/reference/errorcodes/errorcode-nfc.md b/en/application-dev/reference/errorcodes/errorcode-nfc.md new file mode 100644 index 0000000000000000000000000000000000000000..500d870366c8a88a9036454ada2d0ffe0a3c04a9 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-nfc.md @@ -0,0 +1,43 @@ +# NFC Error Codes + +## 3100101 + +**Error Message** + +NFC opening or closing state is abnormal in service. + +**Description** + +The NFC service fails to enable or disable NFC. + +**Possible Causes** + +Communication with the NFC service failed. + +**Solution** + +Enable or disable NFC again. + +## 3100201 + +**Error Message** + +Tag running state is abnormal in service. + +**Description** + +An error occurs when the NFC service executes the tag service logic. + +**Possible Causes** +1. The tag parameters do not match the API to invoke. +2. The NFC is disabled. +3. The tag is disconnected before the tag operation. +4. The tag chip returns an error status or response timeout. +5. Binding with the NFC service has not been established. + +**Solution** +1. Check whether the NFC parameters match the API to invoke. +2. Enable NFC for the device. +3. Connect to the tag and then perform the read and write operations. +4. Touch and read the card again. +5. Exit the app and read the card again.