diff --git a/README.md b/README.md index 7e19add93fd8c1818e41387bfd4c8ad34efa2b71..0b1fe4ea284ed5df055c0031d96d3cfb759948a3 100644 --- a/README.md +++ b/README.md @@ -22,9 +22,11 @@ This repository stores device and application development documents provided by - OpenHarmony 3.1 Release. [Learn more](en/release-notes/OpenHarmony-v3.1-release.md) + This version is upgraded to OpenHarmony 3.1.1 LTS. [Learn more](en/release-notes/OpenHarmony-v3.1.1-release.md) + - OpenHarmony 3.0 LTS. [Learn more](en/release-notes/OpenHarmony-v3.0-LTS.md) - This version is upgraded to OpenHarmony 3.0.3 LTS. [Learn more](en/release-notes/OpenHarmony-v3.0.3-LTS.md) + This version is upgraded to OpenHarmony 3.0.5 LTS. [Learn more](en/release-notes/OpenHarmony-v3.0.5-LTS.md) - OpenHarmony 2.2 Beta2. [Learn more](en/release-notes/OpenHarmony-v2.2-beta2.md) @@ -41,10 +43,14 @@ OpenHarmony_v1.x_release: OpenHarmony v1.1.4 LTS. [Learn more](en/release-notes/ Third-party license: [Third-Party Open-Source Software and License Notice](en/contribute/third-party-open-source-software-and-license-notice.md) -## How to Contribute +## Contribution A great open-source project wouldn't be possible without the hard work of many contributors. We'd like to invite anyone from around the world to [participate](en/contribute/how-to-contribute.md) in this exciting journey, and we're grateful for your time, passion, and efforts! You can evaluate available documents, make simple modifications, provide feedback on document quality, and contribute your original content. For details, see [Documentation Contribution](en/contribute/documentation-contribution.md). Excellent contributors will be awarded and the contributions will be publicized in the developer community. + +- Mail list: docs@openharmony.io + +- Zulip group: documentation_sig \ No newline at end of file diff --git a/en/application-dev/ability/fa-serviceability.md b/en/application-dev/ability/fa-serviceability.md index 75a605c39be73f29e1db8cecf988535c5495ee4a..48270359d9d49f9ea7d7111b021cd8b81da3df82 100644 --- a/en/application-dev/ability/fa-serviceability.md +++ b/en/application-dev/ability/fa-serviceability.md @@ -30,7 +30,7 @@ A Service ability is used to run tasks in the background, such as playing music }, onConnect(want) { console.log('ServiceAbility OnConnect'); - return null; + return new FirstServiceAbilityStub('test'); }, onDisconnect(want) { console.log('ServiceAbility OnDisConnect'); @@ -113,8 +113,6 @@ let promise = featureAbility.startAbility( Once created, the Service ability keeps running in the background. The system does not stop or destroy it unless memory resources must be reclaimed. - - ### Connecting to a Local Service Ability If you need to connect a Service ability to a Page ability or to a Service ability in another application, you must first implement the **IAbilityConnection** API for the connection. A Service ability allows other abilities to connect to it through **connectAbility()**. @@ -124,7 +122,7 @@ You can use either of the following methods to connect to a Service ability: 1. Using the IDL to automatically generate code - Use OpenHarmony Interface Definition Language (IDL) to automatically generate the corresponding client, server, and **IRemoteObject** code. For details, see [“Development Using TS” in OpenHarmony IDL Specifications and User Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/IDL/idl-guidelines.md#development-using-ts). + Use OpenHarmony Interface Definition Language (IDL) to automatically generate the corresponding client, server, and **IRemoteObject** code. For details, see “Development Using TS" in [OpenHarmony IDL Specifications and User Guide](../IDL/idl-guidelines.md). 2. Writing code in the corresponding file @@ -134,42 +132,37 @@ You can use either of the following methods to connect to a Service ability: ```javascript import prompt from '@system.prompt' - - let mRemote; - function onConnectCallback(element, remote){ - console.log('onConnectLocalService onConnectDone element: ' + element); - console.log('onConnectLocalService onConnectDone remote: ' + remote); - mRemote = remote; - if (mRemote == null) { - prompt.showToast({ - message: "onConnectLocalService not connected yet" - }); - return; - } - let option = new rpc.MessageOption(); - let data = new rpc.MessageParcel(); - let reply = new rpc.MessageParcel(); - data.writeInt(1); - data.writeInt(99); - mRemote.sendRequest(1, data, reply, option).then((result) => { - console.log('sendRequest success'); - let msg = reply.readInt(); + + var option = { + onConnect: function onConnectCallback(element, proxy) { + console.log(`onConnectLocalService onConnectDone`) + if (proxy === null) { + prompt.showToast({ + message: "Connect service failed" + }) + return + } + let data = rpc.MessageParcel.create() + let reply = rpc.MessageParcel.create() + let option = new rpc.MessageOption() + data.writeInterfaceToken("connect.test.token") + proxy.sendRequest(0, data, reply, option) prompt.showToast({ - message: "onConnectLocalService connect result: " + msg, - duration: 3000 - }); - }).catch((e) => { - console.log('sendRequest error:' + e); - }); - - } - - function onDisconnectCallback(element){ - console.log('ConnectAbility onDisconnect Callback') - } - - function onFailedCallback(code){ - console.log('ConnectAbility onFailed Callback') + message: "Connect service success" + }) + }, + onDisconnect: function onDisconnectCallback(element) { + console.log(`onConnectLocalService onDisconnectDone element:${element}`) + prompt.showToast({ + message: "Disconnect service success" + }) + }, + onFailed: function onFailedCallback(code) { + console.log(`onConnectLocalService onFailed errCode:${code}`) + prompt.showToast({ + message: "Connect local service onFailed" + }) + } } ``` @@ -196,45 +189,28 @@ You can use either of the following methods to connect to a Service ability: ```javascript import rpc from "@ohos.rpc"; - - let mMyStub; - export default { - onStart() { - class MyStub extends rpc.RemoteObject{ - constructor(des) { - if (typeof des === 'string') { - super(des); - } - return null; - } - onRemoteRequest(code, data, reply, option) { - console.log("ServiceAbility onRemoteRequest called"); - if (code === 1) { - let op1 = data.readInt(); - let op2 = data.readInt(); - console.log("op1 = " + op1 + ", op2 = " + op2); - reply.writeInt(op1 + op2); - } else { - console.log("ServiceAbility unknown request code"); - } - return true; - } - } - mMyStub = new MyStub("ServiceAbility-test"); - }, - onCommand(want, startId) { - console.log('ServiceAbility onCommand'); - }, - onConnect(want) { - console.log('ServiceAbility OnConnect'); - return mMyStub; - }, - onDisconnect(want) { - console.log('ServiceAbility OnDisConnect'); - }, - onStop() { - console.log('ServiceAbility onStop'); - }, + + class FirstServiceAbilityStub extends rpc.RemoteObject { + constructor(des: any) { + if (typeof des === 'string') { + super(des) + } else { + return + } + } + + onRemoteRequest(code: number, data: any, reply: any, option: any) { + console.log(printLog + ` onRemoteRequest called`) + if (code === 1) { + let string = data.readString() + console.log(printLog + ` string=${string}`) + let result = Array.from(string).sort().join('') + console.log(printLog + ` result=${result}`) + reply.writeString(result) + } else { + console.log(printLog + ` unknown request code`) + } + return true; } ``` @@ -253,40 +229,36 @@ The following code snippet shows how to implement the callbacks: ```ts import prompt from '@system.prompt' -let mRemote; -function onConnectCallback(element, remote){ - console.log('onConnectRemoteService onConnectDone element: ' + element); - console.log('onConnectRemoteService onConnectDone remote: ' + remote); - mRemote = remote; - if (mRemote == null) { - prompt.showToast({ - message: "onConnectRemoteService not connected yet" - }); - return; - } - let option = new rpc.MessageOption(); - let data = new rpc.MessageParcel(); - let reply = new rpc.MessageParcel(); - data.writeInt(1); - data.writeInt(99); - mRemote.sendRequest(1, data, reply, option).then((result) => { - console.log('sendRequest success'); - let msg = reply.readInt(); +var option = { + onConnect: function onConnectCallback(element, proxy) { + console.log(`onConnectRemoteService onConnectDone`) + if (proxy === null) { + prompt.showToast({ + message: "Connect service failed" + }) + return + } + let data = rpc.MessageParcel.create() + let reply = rpc.MessageParcel.create() + let option = new rpc.MessageOption() + data.writeInterfaceToken("connect.test.token") + proxy.sendRequest(0, data, reply, option) prompt.showToast({ - message: "onConnectRemoteService connect result: " + msg, - duration: 3000 - }); - }).catch((e) => { - console.log('sendRequest error:' + e); - }); -} - -function onDisconnectCallback(element){ - console.log('ConnectRemoteAbility onDisconnect Callback') -} - -function onFailedCallback(code){ - console.log('ConnectRemoteAbility onFailed Callback') + message: "Connect service success" + }) + }, + onDisconnect: function onDisconnectCallback(element) { + console.log(`onConnectRemoteService onDisconnectDone element:${element}`) + prompt.showToast({ + message: "Disconnect service success" + }) + }, + onFailed: function onFailedCallback(code) { + console.log(`onConnectRemoteService onFailed errCode:${code}`) + prompt.showToast({ + message: "Connect local service onFailed" + }) + } } ``` @@ -372,23 +344,25 @@ The following code snippet shows how the Service ability instance returns itself ```ts import rpc from "@ohos.rpc"; -class FirstServiceAbilityStub extends rpc.RemoteObject{ - constructor(des) { +class FirstServiceAbilityStub extends rpc.RemoteObject { + constructor(des: any) { if (typeof des === 'string') { - super(des); + super(des) } else { - return null; + return } } - onRemoteRequest(code, data, reply, option) { - console.log("ServiceAbility onRemoteRequest called"); + + onRemoteRequest(code: number, data: any, reply: any, option: any) { + console.log(printLog + ` onRemoteRequest called`) if (code === 1) { - let op1 = data.readInt(); - let op2 = data.readInt(); - console.log("op1 = " + op1 + ", op2 = " + op2); - reply.writeInt(op1 + op2); + let string = data.readString() + console.log(printLog + ` string=${string}`) + let result = Array.from(string).sort().join('') + console.log(printLog + ` result=${result}`) + reply.writeString(result) } else { - console.log("ServiceAbility unknown request code"); + console.log(printLog + ` unknown request code`) } return true; } diff --git a/en/application-dev/napi/napi-guidelines.md b/en/application-dev/napi/napi-guidelines.md index e58eed34cccb7dd820e1144a616dfb93a10f4d34..86854eb072b19c7ee359dcb70413ce22580cb8f7 100644 --- a/en/application-dev/napi/napi-guidelines.md +++ b/en/application-dev/napi/napi-guidelines.md @@ -14,6 +14,7 @@ You can `import` the native .so that contains the JS processing logic. For examp * Add **static** to the **nm_register_func** function to prevent symbol conflicts with other .so files. * The name of the module registration entry, that is, the function decorated by **\_\_attribute\_\_((constructor))**, must be unique. + ### .so Naming Rules Each module has a .so file. For example, if the module name is `hello`, name the .so file **libhello.so**. The `nm_modname` field in `napi_module` must be `hello`, which is the same as the module name. The sample code for importing the .so file is `import hello from 'libhello.so'`. @@ -25,6 +26,10 @@ The Ark engine prevents NAPIs from being called to operate JS objects in non-JS * The NAPIs can be used only in JS threads. * **env** is bound to a thread and cannot be used across threads. The JS object created by a NAPI can be used only in the thread, in which the object is created, that is, the JS object is bound to the **env** of the thread. +### Importing Header Files + +Before using NAPI objects and methods, include **napi/native_api.h**. Otherwise, when only the third-party library header file is included, an error will be reporting, indicating that the interface cannot be found. + ### napi_create_async_work **napi_create_async_work** has two callbacks: @@ -635,3 +640,8 @@ export default { } } ``` +## Samples +The following samples are provided for native API development: +- [`NativeAPI`: NativeAPI (eTS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/Native/NativeAPI) +- [First Native C++ Application (eTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/NativeTemplateDemo) +- [Native Component (eTS) (API9) ](https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/XComponent) diff --git a/en/application-dev/reference/apis/js-apis-appAccount.md b/en/application-dev/reference/apis/js-apis-appAccount.md index f216c6b08806daa6c5bc87471a3effd749130094..ef0e355c63726bc167dac72801adfdce030827f3 100644 --- a/en/application-dev/reference/apis/js-apis-appAccount.md +++ b/en/application-dev/reference/apis/js-apis-appAccount.md @@ -89,7 +89,7 @@ Adds an app account name and additional information (information that can be con ### addAccount -addAccount(name: string, extraInfo: string): Promise<void> +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. @@ -100,7 +100,7 @@ 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.| +| extraInfo | string | No | Additional information to add. The additional information cannot contain sensitive information, such as the app account password.| **Return value** @@ -1696,7 +1696,7 @@ Checks whether an app account has specific labels. This API uses an asynchronous | 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<void> | Yes | Callback invoked to return the result. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. | **Example** @@ -1710,7 +1710,7 @@ Checks whether an app account has specific labels. This API uses an asynchronous ### checkAccountLabels9+ -checkAccountLabels(name: string, owner: string, labels: Array<string>): Promise<void> +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. @@ -1771,7 +1771,7 @@ Selects the accounts accessible to the requester based on the options. This API ### selectAccountsByOptions9+ -selectAccountsByOptions(options: SelectAccountsOptions): Promise<void> +selectAccountsByOptions(options: SelectAccountsOptions): Promise<Array<AppAccountInfo>> Selects the accounts accessible to the requester based on the options. This API uses a promise to return the result. @@ -1836,7 +1836,7 @@ Verifies the user credential. This API uses an asynchronous callback to return t ### verifyCredential9+ -verifyCredential(name: string, owner: string, options, callback: AuthenticatorCallback): void; +verifyCredential(name: string, owner: string, options: VerifyCredentialOptions, callback: AuthenticatorCallback): void; Verifies the user credential. This API uses an asynchronous callback to return the result. @@ -1952,11 +1952,11 @@ Defines OAuth token information. **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. | +| Name | Type | Mandatory | Description | +| -------------------- | -------------- | ----- | ---------------- | +| authType | string | Yes | Authentication type. | +| token | string | Yes | Value of the token. | +| account9+ | AppAccountInfo | No | Account information of the token.| ## AuthenticatorInfo8+ @@ -1978,7 +1978,7 @@ Represents the options for selecting accounts. | Name | Type | Mandatory | Description | | --------------- | --------------------------- | ----- | ------------------- | -| allowedAccounts | Array<[AppAccountInfo](#appAccountinfo)> | No | Allowed accounts. | +| allowedAccounts | Array<[AppAccountInfo](#appaccountinfo)> | No | Allowed accounts. | | allowedOwners | Array<string> | No | Allowed account owners.| | requiredLabels | Array<string> | No | Labels required for the authenticator. | @@ -2012,21 +2012,21 @@ Enumerates the constants. **System capability**: SystemCapability.Account.AppAccount -| Name | Default 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.| -| KEY_TOKEN | "token" | Token. | -| KEY_ACTION | "action" | Operation. | -| KEY_AUTH_TYPE | "authType" | Authentication type. | -| KEY_SESSION_ID | "sessionId" | Session ID. | -| KEY_CALLER_PID | "callerPid" | PID of the caller. | -| KEY_CALLER_UID | "callerUid" | UID of the caller. | -| KEY_CALLER_BUNDLE_NAME | "callerBundleName" | Bundle name of the caller. | -| KEY_REQUIRED_LABELS | "requiredLabels" | Required labels. | -| KEY_BOOLEAN_RESULT | "booleanResult" | Return value of the Boolean type. | +| Name | Default 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.| +| KEY_TOKEN | "token" | Token. | +| KEY_ACTION | "action" | Operation. | +| KEY_AUTH_TYPE | "authType" | Authentication type. | +| KEY_SESSION_ID | "sessionId" | Session ID. | +| KEY_CALLER_PID | "callerPid" | PID of the caller. | +| KEY_CALLER_UID | "callerUid" | UID of the caller. | +| KEY_CALLER_BUNDLE_NAME | "callerBundleName" | Bundle name of the caller. | +| KEY_REQUIRED_LABELS9+ | "requiredLabels" | Required labels. | +| KEY_BOOLEAN_RESULT9+ | "booleanResult" | Return value of the Boolean type. | ## ResultCode8+ @@ -2125,7 +2125,7 @@ Called to redirect a request. ### onRequestContinued9+ -onRequestContinued: () => void +onRequestContinued?: () => void Called to continue to process the request. diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index 473c530ac8c4a2af7fc1bd049bdac984d0740429..a518c72880e74ad35cc76e2f0f8c15f92a0b764f 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -2148,11 +2148,10 @@ Subscribes to audio capturer change events. **System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** - | Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ------------------------------------------------------------------- ---- | +| -------- | ------- | --------- | ----------------------------------------------------------------------- | | type | string | Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes. | -| callback | Callback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the result. | +| callback | Callback\<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the result. | **Example** ``` diff --git a/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md index 94182ce2915f60bd6998f512d17288920549d3f8..ae94a539b922fc9aca76dbfe80f3b942171c631c 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md @@ -18,9 +18,11 @@ The **ApplicationInfo** module provides application information. Unless otherwis | systemApp | boolean | Yes | No | Whether the application is a system application. The default value is **false**. | | enabled | boolean | Yes | No | Whether the application is enabled. The default value is **true**. | | label | string | Yes | No | Application label. | -| labelId | string | Yes | No | Application label ID. | +| labelId(deprecated) | string | Yes | No | Application label ID.
\- **NOTE**: This attribute is deprecated from API version 9. Use **labelIndex** instead. | +| labelIndex9+ | number | Yes | No | Index of the application label.| | icon | string | Yes | No | Application icon. | -| iconId | string | Yes | No | Application icon ID. | +| iconId(deprecated) | string | Yes | No | Application icon ID.
\- **NOTE**: This attribute is deprecated from API version 9. Use **iconIndex** instead. | +| iconIndex9+ | number | Yes | No | Index of the application icon.| | process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used. | | supportedModes | number | Yes | No | Running modes supported by the application. | | moduleSourceDirs | Array\ | Yes | No | Relative paths for storing application resources. | diff --git a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md index 82935f9623b2cfb1878112aa2b7a8b27564f7ec7..f6702d14d391a025bf9a16f2d8bf79a97772ed0a 100644 --- a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md +++ b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md @@ -2,9 +2,11 @@ The **DataShareResultSet** module provides APIs for accessing the result set obtained from the database. You can access the values in the specified rows or the value of the specified data type. ->**NOTE** +> **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. +> 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. +> +> The APIs provided by this module are system APIs. ## Modules to Import @@ -44,7 +46,10 @@ dataShareHelper.query(uri, da, columns).then((data) => { }); ``` -## Attributes +## DataShareResultSet +Provides methods for accessing the result sets generated by querying the database. + +### Attributes **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -55,7 +60,7 @@ dataShareHelper.query(uri, da, columns).then((data) => { | rowCount | number | Yes | Number of rows in the result set. | | isClosed | boolean | Yes | Whether the result set is closed.| -## goToFirstRow +### goToFirstRow goToFirstRow(): boolean @@ -76,7 +81,7 @@ let isGoTOFirstRow = resultSet.goToFirstRow(); console.info('resultSet.goToFirstRow: ' + isGoTOFirstRow); ``` -## goToLastRow +### goToLastRow goToLastRow(): boolean @@ -97,7 +102,7 @@ let isGoToLastRow = resultSet.goToLastRow(); console.info('resultSet.goToLastRow: ' + isGoToLastRow); ``` -## goToNextRow +### goToNextRow goToNextRow(): boolean @@ -118,7 +123,7 @@ let isGoToNextRow = resultSet.goToNextRow(); console.info('resultSet.goToNextRow: ' + isGoToNextRow); ``` -## goToPreviousRow +### goToPreviousRow goToPreviousRow(): boolean @@ -139,7 +144,7 @@ let isGoToPreviousRow = resultSet.goToPreviousRow(); console.info('resultSet.goToPreviousRow: ' + isGoToPreviousRow); ``` -## goTo +### goTo goTo(offset:number): boolean @@ -167,7 +172,7 @@ let isGoTo = resultSet.goTo(goToNum); console.info('resultSet.goTo: ' + isGoTo); ``` -## goToRow +### goToRow goToRow(position: number): boolean @@ -195,7 +200,7 @@ let isGoToRow = resultSet.goToRow(goToRowNum); console.info('resultSet.goToRow: ' + isGoToRow); ``` -## getBlob +### getBlob getBlob(columnIndex: number): Uint8Array @@ -224,7 +229,7 @@ let getBlob = resultSet.getBlob(columnIndex); console.info('resultSet.getBlob: ' + getBlob); ``` -## getString +### getString getString(columnIndex: number): *string* @@ -253,7 +258,7 @@ let getString = resultSet.getString(columnIndex); console.info('resultSet.getString: ' + getString); ``` -## getLong +### getLong getLong(columnIndex: number): number @@ -282,7 +287,7 @@ let getLong = resultSet.getLong(columnIndex); console.info('resultSet.getLong: ' + getLong); ``` -## getDouble +### getDouble getDouble(columnIndex: number): number @@ -311,7 +316,7 @@ let getDouble = resultSet.getDouble(columnIndex); console.info('resultSet.getDouble: ' + getDouble); ``` -## close +### close close(): void @@ -325,7 +330,7 @@ Closes this result set. resultSet.close(); ``` -## getColumnIndex +### getColumnIndex getColumnIndex(columnName: string): number @@ -353,7 +358,7 @@ let getColumnIndex = resultSet.getColumnIndex(ColumnName) console.info('resultSet.getColumnIndex: ' + getColumnIndex); ``` -## getColumnName +### getColumnName getColumnName(columnIndex: number): *string* @@ -381,7 +386,7 @@ let getColumnName = resultSet.getColumnName(columnIndex) console.info('resultSet.getColumnName: ' + getColumnName); ``` -## getDataType +### getDataType getDataType(columnIndex: number): DataType diff --git a/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md b/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md index 16c1c1c7b622782a577719bae992d10b1f4634a0..2f54d7d7c47b10403fbc96edf92ce1d55cdcb41b 100644 --- a/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md +++ b/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md @@ -1,10 +1,12 @@ # Data Share Predicates -You can use **DataSharePredicates** to specify conditions for [updating](js-apis-data-dataShare.md#update), [deleting](js-apis-data-dataShare.md#delete), and [querying](js-apis-data-dataShare.md#query) data with **DataShare**. +You can use **DataSharePredicates** to specify conditions for [updating](js-apis-data-dataShare.md#update), [deleting](js-apis-data-dataShare.md#delete), and [querying](js-apis-data-dataShare.md#query) data when **DataShare** is used to manage data. ->**NOTE** +> **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. +> 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. +> +> The APIs provided by this module are system APIs. ## Modules to Import @@ -13,11 +15,14 @@ You can use **DataSharePredicates** to specify conditions for [updating](js-apis import dataSharePredicates from '@ohos.data.dataSharePredicates'; ``` -## equalTo +## DataSharePredicates +Provides methods for setting different **DataSharePredicates** objects. + +### equalTo equalTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value equal to the specified value. +Sets a **DataSharePredicates** object to match the data that is equal to the specified value. Currently, only the relational database (RDB) and key-value database (KVDB, schema) support this **DataSharePredicates** object. @@ -34,7 +39,7 @@ Currently, only the relational database (RDB) and key-value database (KVDB, sche | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -43,11 +48,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.equalTo("NAME", "Rose") ``` -## notEqualTo +### notEqualTo notEqualTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value not equal to the specified value. +Sets a **DataSharePredicates** object to match the data that is not equal to the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -64,7 +69,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -73,11 +78,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.notEqualTo("NAME", "Rose") ``` -## beginWrap +### beginWrap beginWrap(): DataSharePredicates -Adds a left parenthesis to this **DataSharePredicates**. Currently, only the RDB supports this **DataSharePredicates** object. +Adds a left parenthesis to this **DataSharePredicates**. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -99,11 +106,13 @@ predicates.equalTo("NAME", "lisi") .endWrap() ``` -## endWrap +### endWrap endWrap(): DataSharePredicates -Adds a right parenthesis to this **DataSharePredicates** object. Currently, only the RDB supports this **DataSharePredicates** object. +Adds a right parenthesis to this **DataSharePredicates** object. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -125,7 +134,7 @@ predicates.equalTo("NAME", "lisi") .endWrap() ``` -## or +### or or(): DataSharePredicates @@ -150,7 +159,7 @@ predicates.equalTo("NAME", "lisi") .equalTo("NAME", "Rose") ``` -## and +### and and(): DataSharePredicates @@ -175,11 +184,13 @@ predicates.equalTo("NAME", "lisi") .equalTo("SALARY", 200.5) ``` -## contains +### contains contains(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the string that contains the specified value. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to match the data that contains the specified value. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -188,13 +199,13 @@ Sets a **DataSharePredicates** object to match the string that contains the spec | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | | field | string | Yes | Column name in the database table. | -| value | string | Yes | Value contained in the string.| +| value | string | Yes | Value to match.| **Return value** | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -203,11 +214,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.contains("NAME", "os") ``` -## beginsWith +### beginsWith beginsWith(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match a string that starts with the specified value. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to match the data that begins with the specified value. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -216,13 +229,13 @@ Sets a **DataSharePredicates** object to match a string that starts with the spe | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | string | Yes | Start value of the string.| +| value | string | Yes | Start value to match.| **Return value** | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -231,11 +244,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.beginsWith("NAME", "os") ``` -## endsWith +### endsWith endsWith(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match a string that ends with the specified value. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to match the data that ends with the specified value. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -244,13 +259,13 @@ Sets a **DataSharePredicates** object to match a string that ends with the speci | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | string | Yes | End value of the string.| +| value | string | Yes | End value to match.| **Return value** | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -259,11 +274,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.endsWith("NAME", "os") ``` -## isNull +### isNull isNull(field: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the field whose value is null. +Sets a **DataSharePredicates** object to match the data whose value is null. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -279,7 +294,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -288,11 +303,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.isNull("NAME") ``` -## isNotNull +### isNotNull isNotNull(field: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the field whose value is not null. +Sets a **DataSharePredicates** object to match the data whose value is not null. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -308,7 +323,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -317,11 +332,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.isNotNull("NAME") ``` -## like +### like like(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match a string that is similar to the specified value. +Sets a **DataSharePredicates** object to match the data that is similar to the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -338,7 +353,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -347,11 +362,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.like("NAME", "%os%") ``` -## unlike +### unlike unlike(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match a string that is not similar to the specified value. +Sets a **DataSharePredicates** object to match the data that is not not similar to the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -368,7 +383,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -377,11 +392,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.unlike("NAME", "%os%") ``` -## glob +### glob glob(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the specified string. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to match the specified string. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -396,7 +413,7 @@ Sets a **DataSharePredicates** object to match the specified string. Currently, | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified string.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -405,11 +422,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.glob("NAME", "?h*g") ``` -## between +### between between(field: string, low: ValueType, high: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value within the specified range. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to match the data that is within the specified range. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -425,7 +444,7 @@ Sets a **DataSharePredicates** object to match the field with data type **ValueT | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -434,11 +453,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.between("AGE", 10, 50) ``` -## notBetween +### notBetween notBetween(field: string, low: ValueType, high: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value out of the specified range. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to match the data that is out of the specified range. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -454,7 +475,7 @@ Sets a **DataSharePredicates** object to match the field with data type **ValueT | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -463,11 +484,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.notBetween("AGE", 10, 50) ``` -## greaterThan +### greaterThan greaterThan(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value greater than the specified value. +Sets a **DataSharePredicates** object to match the data that is greater than the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -484,7 +505,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -493,11 +514,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.greaterThan("AGE", 10) ``` -## lessThan +### lessThan lessThan(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value less than the specified value. +Sets a **DataSharePredicates** object to match the data that is less than the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -514,7 +535,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -523,11 +544,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.lessThan("AGE", 50) ``` -## greaterThanOrEqualTo +### greaterThanOrEqualTo greaterThanOrEqualTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value greater than or equal to the specified value. +Sets a **DataSharePredicates** object to match the data that is greater than or equal to the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -544,7 +565,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -553,11 +574,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.greaterThanOrEqualTo("AGE", 10) ``` -## lessThanOrEqualTo +### lessThanOrEqualTo lessThanOrEqualTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value less than or equal to the specified value. +Sets a **DataSharePredicates** object to match the data that is less than or equal to the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -574,7 +595,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -583,11 +604,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.lessThanOrEqualTo("AGE", 50) ``` -## orderByAsc +### orderByAsc orderByAsc(field: string): DataSharePredicates -Sets a **DataSharePredicates** object that sorts the values in a column in ascending order. +Sets a **DataSharePredicates** object that sorts data in ascending order. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -603,7 +624,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -612,11 +633,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.orderByAsc("AGE") ``` -## orderByDesc +### orderByDesc orderByDesc(field: string): DataSharePredicates -Sets a **DataSharePredicates** object that sorts the values in a column in descending order. +Sets a **DataSharePredicates** object that sorts data in descending order. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -632,7 +653,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -641,11 +662,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.orderByDesc("AGE") ``` -## distinct +### distinct distinct(): DataSharePredicates -Sets a **DataSharePredicates** object to filter out duplicate records. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to filter out duplicate data records. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -653,7 +676,7 @@ Sets a **DataSharePredicates** object to filter out duplicate records. Currently | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -662,7 +685,7 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.equalTo("NAME", "Rose").distinct() ``` -## limit +### limit limit(total: number, offset: number): DataSharePredicates @@ -683,7 +706,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -692,11 +715,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.equalTo("NAME", "Rose").limit(10, 3) ``` -## groupBy +### groupBy groupBy(fields: Array<string>): DataSharePredicates -Sets a **DataSharePredicates** object to group the records according to the specified parameters. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object group the records according to the specified fields. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -704,13 +729,13 @@ Sets a **DataSharePredicates** object to group the records according to the spec | Name| Type | Mandatory| Description | | ------ | ------------- | ---- | -------------------- | -| fields | Array<string> | Yes | Names of the columns to group.| +| fields | Array<string> | Yes | Names of the columns by which the records are grouped.| **Return value** | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -719,11 +744,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.groupBy(["AGE", "NAME"]) ``` -## indexedBy +### indexedBy indexedBy(field: string): DataSharePredicates -Sets a **DataSharePredicates** object to specify the index column. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to list data by the specified index. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -737,7 +764,7 @@ Sets a **DataSharePredicates** object to specify the index column. Currently, on | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -746,11 +773,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.indexedBy("SALARY_INDEX") ``` -## in +### in in(field: string, value: Array<ValueType>): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **Array** and value within the specified range. +Sets a **DataSharePredicates** object to match the data that is within the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -761,13 +788,13 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | ---------------- | ---- | --------------------------------------- | | field | string | Yes| Column name in the database table. | -| value | Array<[ValueType](js-apis-data-ValuesBucket.md#valuetype)> | Yes | Array of **ValueType**s to match.| +| value | Array<[ValueType](js-apis-data-ValuesBucket.md#valuetype)> | Yes | Array of the values to match.| **Return value** | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -776,11 +803,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.in("AGE", [18, 20]) ``` -## notIn +### notIn notIn(field: string, value: Array<ValueType>): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **Array** and value out of the specified range. +Sets a **DataSharePredicates** object to match the data that is not in the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -791,13 +818,13 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | ---------------- | ---- | --------------------------------------- | | field | string | Yes | Column name in the database table. | -| value | Array<[ValueType](js-apis-data-ValuesBucket.md#valuetype)> | Yes | Array of **ValueType**s to match.| +| value | Array<[ValueType](js-apis-data-ValuesBucket.md#valuetype)> | Yes | Array of the values to match.| **Return value** | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -806,11 +833,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.notIn("NAME", ["Lisa", "Rose"]) ``` -## prefixKey +### prefixKey prefixKey(prefix: string): DataSharePredicates -Sets a **DataSharePredicates** object to match a field with the specified key prefix. Currently, only the KVDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to match the data with the specified key prefix. + +Currently, only the KVDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -824,7 +853,7 @@ Sets a **DataSharePredicates** object to match a field with the specified key pr | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -833,11 +862,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.prefixKey("NAME") ``` -## inKeys +### inKeys inKeys(keys: Array<string>): DataSharePredicates -Sets a **DataSharePredicates** object to match the fields whose keys are within the given range. Currently, only the KVDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to match the data whose keys are within the given range. + +Currently, only the KVDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -851,7 +882,7 @@ Sets a **DataSharePredicates** object to match the fields whose keys are within | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-display.md b/en/application-dev/reference/apis/js-apis-display.md index 25cf9ed242f66a0983303065dcea527989444223..372e6feb7c832d873bd98ed238d5cf474df10a5d 100644 --- a/en/application-dev/reference/apis/js-apis-display.md +++ b/en/application-dev/reference/apis/js-apis-display.md @@ -174,6 +174,42 @@ Obtains all display objects. This API uses a promise to return the result. }); ``` +## display.hasPrivateWindow9+ + +hasPrivateWindow(displayId: number): boolean + +Checks whether there is a visible privacy window on a display. The privacy window can be set by calling **[setPrivacyMode](js-apis-window.md#setprivacymode7)**. The content in the privacy window cannot be captured or recorded. + +This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------- | ---- |----------| +| id | number | Yes | ID of the display.| + +**Return value** + +| Type | Description | +| -------------------------------- |-----------------------------------------------------------------------| +|boolean | Whether there is a visible privacy window on the display.
The value **true** means that there is a visible privacy window on the display, and **false** means the opposite.
| + +**Example** + + ```js + var ret = display.hasPrivateWindow(displayClass.id); + if (ret == undefined) { + console.log("HasPrivateWindow undefined."); + } + if (ret) { + console.log("HasPrivateWindow."); + } else if (!ret) { + console.log("Don't HasPrivateWindow."); + } + ``` + ## display.on('add'|'remove'|'change') on(type: 'add'|'remove'|'change', callback: Callback<number>): void 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 7d094be2e3b6a425e1c8b0eea194cb1085fd3505..46b962bb7e0dfbb16ea2ef4ba6a0bf2ac37ec5e0 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-account.md +++ b/en/application-dev/reference/apis/js-apis-distributed-account.md @@ -19,8 +19,6 @@ getDistributedAccountAbility(): DistributedAccountAbility Obtains a **DistributedAccountAbility** instance. -**System capability**: SystemCapability.Account.OsAccount - - Return value | Type| Description| | -------- | -------- | @@ -43,7 +41,7 @@ Obtains distributed account information. This API uses an asynchronous callback **System capability**: SystemCapability.Account.OsAccount -**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC - Parameters | Name| Type| Mandatory| Description| @@ -68,7 +66,7 @@ Obtains distributed account information. This API uses a promise to return the r **System capability**: SystemCapability.Account.OsAccount -**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC - Return value | Type| Description| diff --git a/en/application-dev/reference/apis/js-apis-distributed-data .md b/en/application-dev/reference/apis/js-apis-distributed-data .md deleted file mode 100644 index 5682921badad9367817fd3e421b1afb823970425..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-distributed-data .md +++ /dev/null @@ -1,5671 +0,0 @@ -# Distributed Data Management - -The distributed data management module implements collaboration between databases of different devices for applications. The APIs provided by distributed data management can be used to save data to distributed databases and perform operations such as adding, deleting, modifying, querying, and synchronizing data in distributed databases. - -This module provides the following functions: - -- [KVManager](#kvmanager): provides a **KVManager** instance to manage key-value (KV) stores. -- [KvStoreResultSet8+](#kvstoreresultset8): provides methods to obtain the KV store result set and query or move the data read position. -- [Query8+](#query8): provides methods to query data from the database through a **Query** instance by using predicates. -- [KVStore](#kvstore): provides methods to add data, delete data, and observe data changes and data synchronization through a **KVStore** instance. -- [SingleKVStore](#singlekvstore): provides methods to query and synchronize data in a single KV store. This class inherits from [KVStore](#kvstore), and data is not distinguished by device. -- [DeviceKVStore8+ ](#devicekvstore8): provides methods to query and synchronize data in a device KV store. This class inherits from [KVStore](#kvstore), and data is distinguished by device. - ->**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 distributedData from '@ohos.data.distributedData'; -``` - - -## distributedData.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 | Configuration of the **KVManager** instance, including the bundle name and user information of the caller.| -| callback | AsyncCallback<[KVManager](#kvmanager)> | Yes | Callback invoked to return the **KVManager** instance created.| - -**Example** - -Stage model: -```ts -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', - userInfo: { - userId: '0', - userType: distributedData.UserType.SAME_USER_ID - } - } - distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.log("Failed to create KVManager: " + JSON.stringify(err)); - return; - } - console.log("Created KVManager"); - kvManager = manager; - }); - } -} -``` - -FA 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.getApplicationContext(), - bundleName: 'com.example.datamanagertest', - userInfo: { - userId: '0', - userType: distributedData.UserType.SAME_USER_ID - } - } - distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.log("Failed to create KVManager: " + JSON.stringify(err)); - return; - } - console.log("Created KVManager"); - kvManager = manager; - }); - } -} -``` - -## distributedData.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: -```ts -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', - userInfo: { - userId: '0', - userType: distributedData.UserType.SAME_USER_ID - } - } - distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.log("Failed to create KVManager: " + JSON.stringify(err)); - return; - } - console.log("Created KVManager"); - kvManager = manager; - }); - } -} -``` - -FA 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.getApplicationContext(), - bundleName: 'com.example.datamanagertest', - userInfo: { - userId: '0', - userType: distributedData.UserType.SAME_USER_ID - } - } - distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.log("Failed to create KVManager: " + JSON.stringify(err)); - return; - } - console.log("Created KVManager"); - kvManager = manager; - }); - } -} -``` - -## KVManagerConfig - -Provides configuration of the **KVManager** object, including the bundle name and user information of the caller. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name| Type| Mandatory| Description| -| ----- | ------ | ------ | ------ | -| context9+ | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| -| userInfo | [UserInfo](#userinfo) | Yes | User information.| -| bundleName | string | Yes | Bundle name.| - -## UserInfo - -Defines user information. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name| Type| Mandatory| Description| -| ----- | ------ | ------ | ------ | -| userId | string | Yes | User ID.| -| userType | [UserType](#usertype) | Yes | User type.| - - -## UserType - -Enumerates the user types. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name| Value| Description| -| ----- | ------ | ------ | -| SAME_USER_ID | 0 | User who logs in to different devices using the same account.| - - -## KVManager - -Creates a **KVManager** object to obtain KV store information. Before calling any method in **KVManager**, you must use [createKVManager](#distributeddatacreatekvmanager) to create a **KVManager** object. - -### getKVStore - -getKVStore<T extends KVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void - -Creates and obtains a 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.| -| callback | AsyncCallback<T> , <T extends [KVStore](#kvstore)>| Yes | Callback invoked to return the KV store created.| - -**Example** - -```js -let kvStore; -let kvManager; -try { - const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - securityLevel : distributedData.SecurityLevel.S2, - }; - kvManager.getKVStore('storeId', options, function (err, store) { - if (err) { - console.log("getKVStore err: " + JSON.stringify(err)); - return; - } - console.log("getKVStore success"); - kvStore = store; - }); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - - -### getKVStore - -getKVStore<T extends KVStore>(storeId: string, options: Options): Promise<T> - -Creates and obtains a 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 KV store.| - - -**Return value** - -| Type | Description | -| -------------------------------------- | ------------------------ | -| Promise<T>, <T extends [KVStore](#kvstore)> | Promise used to return the KV store created.| - -**Example** - -```js -let kvStore; -let kvManager; -try { - const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - securityLevel : distributedData.SecurityLevel.S2, - }; - kvManager.getKVStore('storeId', options).then((store) => { - console.log("getKVStore success"); - kvStore = store; - }).catch((err) => { - console.log("getKVStore err: " + JSON.stringify(err)); - }); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - -### closeKVStore8+ ### - -closeKVStore(appId: string, storeId: string, kvStore: KVStore, callback: AsyncCallback<void>): void - -Closes a 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).| -| kvStore | [KVStore](#kvstore) | Yes | KV store to close. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| - -**Example** - -```js -let kvStore; -let kvManager; -const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - schema : '', - securityLevel : distributedData.SecurityLevel.S2, - } - try { - kvManager.getKVStore('storeId', options, async function (err, store) { - console.log('getKVStore success'); - kvStore = store; - kvManager.closeKVStore('appId', 'storeId', kvStore, function (err, data) { - console.log('closeKVStore success'); - }); - }); -} catch (e) { - console.log('closeKVStore e ' + e); -} -``` - - -### closeKVStore8+ ### - -closeKVStore(appId: string, storeId: string, kvStore: KVStore): Promise<void> - -Closes a 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).| -| kvStore | [KVStore](#kvstore) | Yes | KV store to close. | - -**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 : distributedData.KVStoreType.SINGLE_VERSION, - schema : '', - securityLevel : distributedData.SecurityLevel.S2, -} - try { - kvManager.getKVStore('storeId', options).then(async (store) => { - console.log('getKVStore success'); - kvStore = store; - kvManager.closeKVStore('appId', 'storeId', kvStore).then(() => { - console.log('closeKVStore success'); - }).catch((err) => { - console.log('closeKVStore err ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('CloseKVStore getKVStore err ' + JSON.stringify(err)); - }); - } catch (e) { - console.log('closeKVStore e ' + e); -} -``` - - -### deleteKVStore8+ ### - -deleteKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): void - -Deletes a 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 used to return the result.| - -**Example** - -```js -let kvManager; -let kvStore; -const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - schema : '', - securityLevel : distributedData.SecurityLevel.S2, -} -try { - kvManager.getKVStore('store', options, async function (err, store) { - console.log('getKVStore success'); - kvStore = store; - kvManager.deleteKVStore('appId', 'storeId', function (err, data) { - console.log('deleteKVStore success'); - }); - }); -} catch (e) { - console.log('DeleteKVStore e ' + e); -} -``` - -### deleteKVStore8+ ### - -deleteKVStore(appId: string, storeId: string): Promise<void> - -Deletes a 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.| - -**Example** - -```js -let kvManager; -let kvStore; -const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - schema : '', - securityLevel : distributedData.SecurityLevel.S2, -} -try { - kvManager.getKVStore('storeId', options).then(async (store) => { - console.log('getKVStore success'); - kvStore = store; - kvManager.deleteKVStore('appId', 'storeId').then(() => { - console.log('deleteKVStore success'); - }).catch((err) => { - console.log('deleteKVStore err ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('getKVStore err ' + JSON.stringify(err)); - }); -} catch (e) { - console.log('deleteKVStore e ' + e); -} -``` - - -### getAllKVStoreId8+ ### - -getAllKVStoreId(appId: string, callback: AsyncCallback<string[]>): void - -Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore) and have not been deleted by [deleteKVStore()](#deletekvstore8). 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 used to return the KV store IDs obtained. | - -**Example** - -```js -let kvManager; -try { - kvManager.getAllKVStoreId('appId', function (err, data) { - console.log('GetAllKVStoreId success'); - console.log('GetAllKVStoreId size = ' + data.length); - }); -} catch (e) { - console.log('GetAllKVStoreId e ' + e); -} -``` - - -### getAllKVStoreId8+ ### - -getAllKVStoreId(appId: string): Promise<string[]> - -Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore) and have not been deleted by [deleteKVStore()](#deletekvstore8). 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 KV store IDs obtained.| - -**Example** - -```js -let kvManager; -try { - console.log('GetAllKVStoreId'); - kvManager.getAllKVStoreId('appId').then((data) => { - console.log('getAllKVStoreId success'); - console.log('size = ' + data.length); - }).catch((err) => { - console.log('getAllKVStoreId err ' + JSON.stringify(err)); - }); -} catch(e) { - console.log('getAllKVStoreId e ' + e); -} -``` - - -### on('distributedDataServiceDie')8+ ### - -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 service status changes.| -| deathCallback | Callback<void> | Yes | Callback invoked to return service status changes.| - -**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. Error:" + e); -} -``` - - -### off('distributedDataServiceDie')8+ ### - -off(event: 'distributedDataServiceDie', deathCallback?: Callback<void>): void - -Unsubscribes from the 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 service status changes.| -| deathCallback | Callback<void> | No | Callback used to return service status changes.| - - -**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. Error:" + e); -} - -``` - -## 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) | No|Security level of the KV store. By default, the security level is not set.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | -| schema8+ | [Schema](#schema8) | No| Schema used to define the values stored in a KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| - - -## KVStoreType - -Enumerates the KV store types. - - -| Name | Value| Description | -| --- | ---- | ----------------------- | -| DEVICE_COLLABORATION | 0 | Device KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | -| SINGLE_VERSION | 1 | Single KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| -| MULTI_VERSION | 2 | Multi-version KV store. This type is not supported currently.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| - - -## SecurityLevel - -Enumerates the KV store security levels. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name | Value| Description | -| --- | ---- | ----------------------- | -| NO_LEVEL | 0 | No security level is set for the KV store. | -| S0 | 1 | The KV store security level is public.| -| S1 | 2 | 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 | 3 | 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 | 5 | 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 | 6 | 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.| - - -## Constants - -Defines the KV store constants. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name | Value| Description | -| --- | ---- | ----------------------- | -| MAX_KEY_LENGTH | 1024 | Maximum length of a key in the KV store, in bytes. | -| MAX_VALUE_LENGTH | 4194303 | Maximum length of a value in the 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.| - -## Schema8+ ## - -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| Description | -| --- | ---- | ----------------------- | -| root8+ | [FieldNode](#fieldnode8) | JSON root object.| -| indexes8+ | Array\ | String array in JSON format. | -| mode8+ | number | Schema mode. | -| skip8+ | number | Size of a skip of the schema. | - -### constructor8+ ### - -constructor() - -A constructor used to create a **Schema** instance. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -## FieldNode8+ ## - -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| Description | -| --- | ---- | ----------------------- | -| nullable8+ | boolean | Whether the database field can be null. | -| default8+ | string | Default value of a **FieldNode**.| -| type8+ | number | Value of the data type corresponding to the specified node.| - -### constructor8+ ### - -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**.| - -### appendChild8+ ### - -appendChild(child: FieldNode): boolean - -Appends a child node to this **FieldNode**. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| child | [FieldNode](#fieldnode8) | 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.distributedData'; -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); -} -``` - - -## KvStoreResultSet8+ ## - -Provides methods to obtain the KV store result sets, and query and move the data read position. - -Before calling any method in **KvStoreResultSet**, you must use [getKVStore](#getkvstore) to obtain a **KVStore** object. - - -### getCount8+ ### - -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); -} -``` - -### getPosition8+ ### - -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('getResultSet succeeded.'); - 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); -} -``` - - -### moveToFirst8+ ### - -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); -} -``` - - -### moveToLast8+ ### - -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); -} -``` - - -### moveToNext8+ ### - -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); -} -``` - - -### moveToPrevious8+ ### - -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); -} -``` - - -### move8+ ### - -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('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const moved5 = resultSet.move(); - console.log("move succeed:" + moved5); -} catch (e) { - console.log("move failed: " + e); -} -``` - - -### moveToPosition8+ ### - -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('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const moved6 = resultSet.moveToPosition(); - console.log("moveToPosition succeed: " + moved6); -} catch (e) { - console.log("moveToPosition failed: " + e); -} -``` - - -### isFirst8+ ### - -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); -} -``` - - -### isLast8+ ### - -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); -} -``` - -### isBeforeFirst8+ ### - -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); -} -``` - - -### isAfterLast8+ ### - -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); -} -``` - - -### getEntry8+ ### - -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); -} -``` - - -## Query8+ ## - -Provides methods to create a **Query** object, which defines different data query criteria. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -### constructor8+ ### - -constructor() - -A constructor used to create a **Schema** instance. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - - -### reset8+ ### - -reset(): Query - -Resets the **Query** object. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object reset.| - -**Example** - -```js -try { - let query = new distributedData.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); -} -``` - - -### equalTo8+ ### - -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](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.equalTo("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### notEqualTo8+ ### - -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](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### greaterThan8+ ### - -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](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.greaterThan("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### lessThan8+ ### - -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\|boolean | Yes | Value specified.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.lessThan("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### greaterThanOrEqualTo8+ ### - -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\|boolean | Yes | Value specified.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.greaterThanOrEqualTo("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### lessThanOrEqualTo8+ ### - -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\|boolean | Yes | Value specified.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.lessThanOrEqualTo("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### isNull8+ ### - -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](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.isNull("field"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### inNumber8+ ### - -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](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.inNumber("field", [0, 1]); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### inString8+ ### - -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](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.inString("field", ['test1', 'test2']); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### notInNumber8+ ### - -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](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.notInNumber("field", [0, 1]); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### notInString8+ ### - -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](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.notInString("field", ['test1', 'test2']); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### like8+ ### - -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](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.like("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### unlike8+ ### - -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](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.unlike("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### and8+ ### - -and(): Query - -Creates a **Query** object with the AND condition. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object Created.| - -**Example** - -```js -try { - let query = new distributedData.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); -} -``` - - -### or8+ ### - -or(): Query - -Creates a **Query** object with the OR condition. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object Created.| - -**Example** - -```js -try { - let query = new distributedData.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); -} -``` - - -### orderByAsc8+ ### - -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](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value"); - query.orderByAsc("field"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### orderByDesc8+ ### - -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](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value"); - query.orderByDesc("field"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### limit8+ ### - -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](#query8) |**Query** object created.| - -**Example** - -```js -let total = 10; -let offset = 1; -try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value"); - query.limit(total, offset); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### isNotNull8+ ### - -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](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.isNotNull("field"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### beginGroup8+ ### - -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](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.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); -} -``` - - -### endGroup8+ ### - -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](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.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); -} -``` - - -### prefixKey8+ ### - -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](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.prefixKey("$.name"); - query.prefixKey("0"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### setSuggestIndex8+ ### - -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](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.setSuggestIndex("$.name"); - query.setSuggestIndex("0"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### deviceId8+ ### - -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](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.deviceId("deviceId"); - console.log("query is " + query.getSqlLike()); -} catch (e) { - console.log("should be ok on Method Chaining : " + e); -} -``` - - -### getSqlLike8+ ### - -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 distributedData.Query(); - let sql1 = query.getSqlLike(); - console.log("GetSqlLike sql=" + sql1); -} catch (e) { - console.log("duplicated calls should be ok : " + e); -} -``` - - -## KVStore - -Provides methods to manage data in a KV store, for example, adding or deleting data and subscribing to data changes or completion of data synchronization. - -Before calling any method in **KVStore**, you must use [getKVStore](#getkvstore) to obtain a **KVStore** object. - -### 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 used to return the result. | - -**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.log("put err: " + JSON.stringify(err)); - return; - } - console.log("put success"); - }); -}catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - - -### 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.| - -**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 success: " + JSON.stringify(data)); - }).catch((err) => { - console.log("put err: " + JSON.stringify(err)); - }); -}catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - -### 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 used to return the result. | - -**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.log("put err: " + JSON.stringify(err)); - return; - } - console.log("put success"); - kvStore.delete(KEY_TEST_STRING_ELEMENT, function (err,data) { - if (err != undefined) { - console.log("delete err: " + JSON.stringify(err)); - return; - } - console.log("delete success"); - }); - }); -}catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - -### 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.| - -**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 success: " + JSON.stringify(data)); - kvStore.delete(KEY_TEST_STRING_ELEMENT).then((data) => { - console.log("delete success"); - }).catch((err) => { - console.log("delete err: " + JSON.stringify(err)); - }); - }).catch((err) => { - console.log("put err: " + JSON.stringify(err)); - }); -}catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - -### delete9+ - -delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<void>) - -Deletes KV pairs that meet the specified predicates. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| -| callback | AsyncCallback<void> | Yes |Callback used to return the result. | - -**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('delete success'); - } else { - console.log('delete fail' + err); - } - }); -} catch (e) { - console.log('An unexpected error occurred. Error:' + e); -} -``` - -### delete9+ - -delete(predicates: dataSharePredicates.DataSharePredicates): Promise<void> - -Deletes KV pairs that meet the specified predicates. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| - - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise used to return the result.| - -**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 success' + JSON.stringify(data)); - kvStore.delete(predicates).then((data) => { - console.log('delete success'); - }).catch((err) => { - console.log('delete fail' + JSON.stringify(err)); - }); - }) .catch((err) => { - console.log(' put fail' + err); - }); -}catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} - -``` - -### on('dataChange') - -on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void - -Subscribes to data change notifications 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 data changes. | -| type |[SubscribeType](#subscribetype) | Yes |Type of data changes. | -| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the data changes.| - -**Example** - -```js -let kvStore; -kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { - console.log("dataChange callback call data: " + JSON.stringify(data)); -}); -``` - - -### on('syncComplete') - -on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void - -Subscribes to data 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 completion of a data synchronization. | -| syncCallback |Callback<Array<[string, number]>> | Yes |Callback used to return the data synchronization result. | - -**Example** - -```js -let kvStore; -kvStore.on('syncComplete', function (data) { - console.log("callback call data: " + data); -}); -``` - -### off('dataChange')8+ - -off(event:'dataChange', listener?: Callback<ChangeNotification>): void - -Unsubscribes from data change notifications. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. | -| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the data changes.| - -**Example** - -```js -let kvStore; -kvStore.on('dataChange', function (data) { - console.log("callback call data: " + data); -}); -kvStore.off('dataChange', function (data) { - console.log("callback call data: " + data); -}); -``` - -### off('syncComplete')9+ - -off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void - -Unsubscribes from data change events. This API uses a synchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates completion of a data synchronization. | -| syncCallback |Callback<Array<[string, number]>> | No |Callback used to return the synchronization result. | - -**Example** - -```js -let kvStore; -try { - const func = function (data) { - console.log('syncComplete ' + data) - }; - kvStore.on('syncComplete', func); - kvStore.off('syncComplete', func); -}catch(e) { - console.log('syncComplete e ' + e); -} -``` - - -### putBatch8+ - -putBatch(entries: Entry[], callback: AsyncCallback<void>): void - -Inserts KV pairs in batches 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 | -| ----- | ------ | ---- | ----------------------- | -| entries |[Entry](#entry)[] | Yes |KV pairs to insert in batches. | -| callback |Asyncallback<void> |Yes |Callback used to return the result.| - -**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 : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - kvStore.getEntries('batch_test_string_key', function (err,entries) { - console.log('getEntries success'); - console.log('entries.length: ' + entries.length); - console.log('entries[0]: ' + JSON.stringify(entries[0])); - }); - }); -}catch(e) { - console.log('PutBatch e ' + JSON.stringify(e)); -} -``` - - -### putBatch8+ - -putBatch(entries: Entry[]): Promise<void> - -Inserts KV pairs in batches to this 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.| - -**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 : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - kvStore.getEntries('batch_test_string_key').then((entries) => { - console.log('getEntries success'); - console.log('PutBatch ' + JSON.stringify(entries)); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('PutBatch e ' + JSON.stringify(e)); -} -``` - -### putBatch9+ - -putBatch(value: Array<ValuesBucket>, callback: AsyncCallback<void>): void - -Writes data 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 | -| ----- | ------ | ---- | ----------------------- | -| value |Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes |Data to write. | -| callback |Asyncallback<void> |Yes |Callback used to return the result.| - -**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) { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('putBatch e ' + JSON.stringify(e)); -} -``` - -### putBatch9+ - -putBatch(value: Array<ValuesBucket>): Promise<void> - -Writes data of the **valuesbucket** 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 | -| ----- | ------ | ---- | ----------------------- | -| value |Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes |Data to write. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise used to return the result.| - -**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 (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('PutBatch e ' + JSON.stringify(e)); -} - -``` - -### deleteBatch8+ - -deleteBatch(keys: string[], callback: AsyncCallback<void>): void - -Deletes KV pairs in batches 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 | -| ----- | ------ | ---- | ----------------------- | -| keys |string[] | Yes |KV pairs to delete in batches. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**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 : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - keys.push(key + i); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - kvStore.deleteBatch(keys, async function (err,data) { - console.log('deleteBatch success'); - }); - }); -}catch(e) { - console.log('DeleteBatch e ' + e); -} -``` - - -### deleteBatch8+ ### - -deleteBatch(keys: string[]): Promise<void> - -Deletes KV pairs in batches from this 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.| - -**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 : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - keys.push(key + i); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - kvStore.deleteBatch(keys).then((err) => { - console.log('deleteBatch success'); - }).catch((err) => { - console.log('deleteBatch fail ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('DeleteBatch e ' + e); -} -``` - - -### startTransaction8+ ### - -startTransaction(callback: AsyncCallback<void>): void - -Starts the transaction in 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<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -function putBatchString(len, prefix) { - let entries = []; - for (var i = 0; i < len; i++) { - var entry = { - key : prefix + i, - value : { - type : distributedData.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) { - console.log('startTransaction success'); - let entries = putBatchString(10, 'batch_test_string_key'); - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - }); - }); -}catch(e) { - console.log('startTransaction e ' + e); -} -``` - - -### startTransaction8+ ### - -startTransaction(): Promise<void> - -Starts the transaction in this 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.| - -**Example** - -```js -let kvStore; -try { - var count = 0; - kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { - console.log('startTransaction ' + JSON.stringify(data)); - count++; - }); - kvStore.startTransaction().then(async (err) => { - console.log('startTransaction success'); - }).catch((err) => { - console.log('startTransaction fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('startTransaction e ' + e); -} -``` - - -### commit8+ ### - -commit(callback: AsyncCallback<void>): void - -Commits the transaction in 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<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -try { - kvStore.commit(function (err,data) { - if (err == undefined) { - console.log('commit success'); - } else { - console.log('commit fail'); - } - }); -}catch(e) { - console.log('Commit e ' + e); -} -``` - - -### commit8+ ### - -commit(): Promise<void> - -Commits the transaction in this 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.| - -**Example** - -```js -let kvStore; -try { - kvStore.commit().then(async (err) => { - console.log('commit success'); - }).catch((err) => { - console.log('commit fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('Commit e ' + e); -} -``` - - -### rollback8+ ### - -rollback(callback: AsyncCallback<void>): void - -Rolls back the transaction in 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<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -try { - kvStore.rollback(function (err,data) { - if (err == undefined) { - console.log('commit success'); - } else { - console.log('commit fail'); - } - }); -}catch(e) { - console.log('Rollback e ' + e); -} -``` - - -### rollback8+ ### - -rollback(): Promise<void> - -Rolls back the transaction in this 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.| - -**Example** - -```js -let kvStore; -try { - kvStore.rollback().then(async (err) => { - console.log('rollback success'); - }).catch((err) => { - console.log('rollback fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('Rollback e ' + e); -} -``` - - -### enableSync8+ ### - -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 used to return the result. | - -**Example** - -```js -let kvStore; -try { - kvStore.enableSync(true, function (err,data) { - if (err == undefined) { - console.log('enableSync success'); - } else { - console.log('enableSync fail'); - } - }); -}catch(e) { - console.log('EnableSync e ' + e); -} -``` - - -### enableSync8+ ### - -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('enableSync success'); - }).catch((err) => { - console.log('enableSync fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('EnableSync e ' + e); -} -``` - - -### setSyncRange8+ ### - -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 used to return the result. | - -**Example** - -```js -let kvStore; -try { - const localLabels = ['A', 'B']; - const remoteSupportLabels = ['C', 'D']; - kvStore.setSyncRange(localLabels, remoteSupportLabels, function (err,data) { - console.log('SetSyncRange put success'); - }); -}catch(e) { - console.log('SetSyncRange e ' + e); -} -``` - - -### setSyncRange8+ ### - -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('setSyncRange success'); - }).catch((err) => { - console.log('delete fail ' + err); - }); -}catch(e) { - console.log('SetSyncRange e ' + e); -} -``` - - -## SubscribeType - -Enumerates the subscription types. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name | Value | Description | -| ----- | ------ | ----------------------- | -| SUBSCRIBE_TYPE_LOCAL |0 |Local data changes. | -| SUBSCRIBE_TYPE_REMOTE |1 |Remote data changes. | -| SUBSCRIBE_TYPE_ALL |2 |Local and remote data changes. | - -## ChangeNotification - -Defines the content of data change notifications, including inserted data, updated data, deleted data, and device ID. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name | Type |Readable |Writable | Description | -| ----- | ------- | -----| ------|------------------------ | -| insertEntries | [Entry](#entry)[] | Yes | Yes|Data inserted. | -| updateEntries | [Entry](#entry)[] | Yes | Yes|Data updated. | -| deleteEntries | [Entry](#entry)[] | Yes | Yes|Data deleted. | -| deviceId | string | Yes | Yes|UUID of the device. | - -## Entry - -Defines the KV pairs stored in the KV store. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name | Type |Readable |Writable | Description | -| ----- | ------- | -----| ------|------------------------ | -| key | string | Yes | Yes|Key of the KV pair stored in the KV store. | -| value | [Value](#value) | Yes | Yes|Value of the KV pair stored in the KV store. | - - -## Value - -Defines the **value** object in a KV store. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name | Type |Readable |Writable | Description | -| ----- | ------- | -----| ------|------------------------ | -| type | [ValueType](#value) | Yes | Yes|Type of the value. | -| value | Uint8Array \| string \| number \| boolean| Yes | Yes|Value of the KV pair stored in the KV store. | - -## ValueType - -Enumerates the data types. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name | Value | Description | -| ----- | ------ | ----------------------- | -| STRING |0 |String. | -| INTEGER |1 |Integer. | -| FLOAT |2 |Float (single-precision floating point). | -| BYTE_ARRAY |3 |Byte array. | -| BOOLEAN |4 |Boolean. | -| DOUBLE |5 |Double (double-precision floating point). | - -## SingleKVStore - -Provides methods to query and synchronize data in a single KV store. This class inherits from [KVStore](#kvstore). - -Data is not distinguished by device in a single KV store. The data written to different devices using the same key will be overwritten. For example, a single KV store can be used to synchronize a user's calendar and contact data between different devices. - -Before calling any method in **SingleKVStore**, you must use [getKVStore](#getkvstore) to obtain a **SingleKVStore** instance. - -### get - -get(key: string, callback: AsyncCallback<Uint8Array | string | boolean | number>): 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<Uint8Array \| string \| boolean \| number>) | Yes |Callback invoked to return the value obtained. | - -**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.log("put err: " + JSON.stringify(err)); - return; - } - console.log("put success"); - kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) { - console.log("get success data: " + data); - }); - }); -}catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - - -### get - -get(key: string): Promise<Uint8Array | string | boolean | number> - -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.| - -**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 success: " + JSON.stringify(data)); - kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { - console.log("get success data: " + data); - }).catch((err) => { - console.log("get err: " + JSON.stringify(err)); - }); - }).catch((err) => { - console.log("put err: " + JSON.stringify(err)); - }); -}catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - -### getEntries8+ ### - -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. | - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_number_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.INTEGER, - value : 222 - } - } - entries.push(entry); - } - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - kvStore.getEntries('batch_test_number_key', function (err,entries) { - console.log('getEntries success'); - console.log('entries.length: ' + entries.length); - console.log('entries[0]: ' + JSON.stringify(entries[0])); - }); - }); -}catch(e) { - console.log('PutBatch e ' + e); -} -``` - - -### getEntries8+ ### - -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.| - -**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 : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - console.log('entries: ' + entries); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - kvStore.getEntries('batch_test_string_key').then((entries) => { - console.log('getEntries success'); - console.log('entries.length: ' + entries.length); - console.log('entries[0]: ' + JSON.stringify(entries[0])); - console.log('entries[0].value: ' + JSON.stringify(entries[0].value)); - console.log('entries[0].value.value: ' + entries[0].value.value); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('PutBatch e ' + e); -} -``` - - -### getEntries8+ ### - -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](#query8) | Yes |Key prefix to match. | -| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. | - -**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 : distributedData.ValueType.BYTE_ARRAY, - value : arr - } - } - entries.push(entry); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getEntries(query, function (err,entries) { - console.log('getEntries success'); - console.log('entries.length: ' + entries.length); - console.log('entries[0]: ' + JSON.stringify(entries[0])); - }); - }); - console.log('GetEntries success'); -}catch(e) { - console.log('GetEntries e ' + e); -} -``` - - -### getEntries8+ ### - -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](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.| - -**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 : distributedData.ValueType.BYTE_ARRAY, - value : arr - } - } - entries.push(entry); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getEntries(query).then((entries) => { - console.log('getEntries success'); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('GetEntries putBatch fail ' + JSON.stringify(err)) - }); - console.log('GetEntries success'); -}catch(e) { - console.log('GetEntries e ' + e); -} -``` - - -### getResultSet8+ ### - -getResultSet(keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>): void - -Obtains the result set with the specified 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<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the result set obtained.| - -**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 : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries, async function (err, data) { - console.log('GetResultSet putBatch success'); - kvStore.getResultSet('batch_test_string_key', async function (err, result) { - console.log('GetResultSet getResultSet succeed.'); - resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { - console.log('GetResultSet closeResultSet success'); - }) - }); - }); -}catch(e) { - console.log('GetResultSet e ' + e); -} -``` - - -### getResultSet8+ ### - -getResultSet(keyPrefix: string): Promise<KvStoreResultSet> - -Obtains the result set with the specified 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<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the result set obtained.| - -**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 : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('PutBatch putBatch fail ' + JSON.stringify(err)); - }); - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('GetResult getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + JSON.stringify(err)); - }); - kvStore.closeResultSet(resultSet).then((err) => { - console.log('GetResult closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('GetResult e ' + e); -} -``` - - -### getResultSet8+ ### - -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](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.| - -**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 : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSet(query, async function (err, result) { - console.log('getResultSet succeed.'); - resultSet = result; - }); - }); -} catch(e) { - console.log('GetResultSet e ' + e); -} -``` - - -### getResultSet8+ ### - -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](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the **KvStoreResultSet** object obtained.| - -**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 : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSet(query).then((result) => { - console.log(' getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('GetResultSet e ' + e); -} -``` - -### getResultSet9+ ### - -getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KvStoreResultSet>): void - -Obtains a **KvStoreResultSet** object that matches the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |**DataSharePredicates** object to match. If this parameter is **null**, define the processing logic. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.| - -**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) { - console.log(' GetResultSet success'); - resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { - console.log(' closeResultSet success'); - }) - }); -}catch(e) { - console.log('An unexpected error occurred. Error:' + e); -} -``` -### getResultSet9+ ### - -getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KvStoreResultSet> - -Obtains a **KvStoreResultSet** object that matches the specified **DataSharePredicates** object. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| predicates |[DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |**DataSharePredicates** object to match. If this parameter is **null**, define the processing logic. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the **KvStoreResultSet** object obtained.| - -**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(' GetResultSet success'); - resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { - console.log(' closeResultSet success'); - }) - }); -}catch(e) { - console.log('An unexpected error occurred. Error:' + e); -} -``` -### closeResultSet8+ ### - -closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void - -Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| resultSet |[KvStoreResultSet](#kvstoreresultset8) | Yes |**KvStoreResultSet** object to close. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -try { - let resultSet = null; - kvStore.closeResultSet(resultSet, function (err, data) { - if (err == undefined) { - console.log('closeResultSet success'); - } else { - console.log('closeResultSet fail'); - } - }); -}catch(e) { - console.log('CloseResultSet e ' + e); -} -``` - - -### closeResultSet8+ ### - -closeResultSet(resultSet: KvStoreResultSet): Promise<void> - -Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| resultSet |[KvStoreResultSet](#kvstoreresultset8) | 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('closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('CloseResultSet e ' + e); -} -``` - - -### getResultSize8+ ### - -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](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<number> | Yes |Callback invoked to return the number of results obtained. | - -**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 : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSize(query, async function (err, resultSize) { - console.log('getResultSet succeed.'); - }); - }); -} catch(e) { - console.log('GetResultSize e ' + e); -} -``` - - -### getResultSize8+ ### - -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](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<number> |Promise used to return the number of results obtained.| - -**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 : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSize(query).then((resultSize) => { - console.log('getResultSet succeed.'); - }).catch((err) => { - console.log('getResultSet failed: ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('GetResultSize e ' + e); -} -``` - - -### removeDeviceData8+ ### - -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.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**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 success'); - const deviceid = 'no_exist_device_id'; - kvStore.removeDeviceData(deviceid, async function (err,data) { - if (err == undefined) { - console.log('removeDeviceData success'); - } else { - console.log('removeDeviceData fail'); - kvStore.get(KEY_TEST_STRING_ELEMENT, async function (err,data) { - console.log('RemoveDeviceData get success'); - }); - } - }); - }); -}catch(e) { - console.log('RemoveDeviceData e ' + e); -} -``` - - -### removeDeviceData8+ ### - -removeDeviceData(deviceId: string): Promise<void> - -Deletes data of a device. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<void> |Promise that returns no value.| - -**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('removeDeviceData put success'); - }).catch((err) => { - console.log('put fail ' + JSON.stringify(err)); - }); - const deviceid = 'no_exist_device_id'; - kvStore.removeDeviceData(deviceid).then((err) => { - console.log('removeDeviceData success'); - }).catch((err) => { - console.log('removeDeviceData fail ' + JSON.stringify(err)); - }); - kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { - console.log('get success data:' + data); - }).catch((err) => { - console.log('RemoveDeviceData get fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('RemoveDeviceData e ' + e); -} -``` - - -### on('syncComplete')8+ ### - -on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void - -Subscribes to the data 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 completion of a data synchronization. | -| syncCallback |Callback<Array<[string, number]>> | Yes |Callback called 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('syncComplete put success'); - }).catch((error) => { - console.log('syncComplete put fail ' + error); - }); -}catch(e) { - console.log('syncComplete put e ' + e); -} -``` - - -### off('syncComplete')8+ ### - -off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void - -Unsubscribes from the data 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 completion of a data synchronization. | -| syncCallback |Callback<Array<[string, number]>> | No |Callback used to return the synchronization result. | - -**Example** - -```js -let kvStore; -try { - const func = function (data) { - console.log('syncComplete ' + data) - }; - kvStore.on('syncComplete', func); - kvStore.off('syncComplete', func); -}catch(e) { - console.log('syncComplete e ' + e); -} -``` - -### on('dataChange')9+ ### - -on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void - -Subscribes to data changes of the specified type. This API returns the result synchronously. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates data changes. | -| type |[SubscribeType](#subscribetype) | Yes |Subscription type. | -| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the result.| - -**Example** - -```js -let kvStore; -kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { - console.log("dataChange callback call data: " + JSON.stringify(data)); -}); - -``` - -### off('dataChange')9+ ### - -off(event:'dataChange', listener?: Callback<ChangeNotification>): void - -Unsubscribes from the data change events. This API returns the result synchronously. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. | -| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the result.| - -**Example** - -```js -let kvStore; -kvStore.on('dataChange', function (data) { - console.log("callback call data: " + data); -}); -kvStore.off('dataChange', function (data) { - console.log("callback call data: " + data); -}); -``` -### sync7+ - - -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. | - -**Example** - -```js -let kvStore; -kvStore.sync('deviceIds', distributedData.SyncMode.PULL_ONLY, 1000); -``` - -### sync9+ -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](#query8) | Yes |**Query** object to match. | -| delayMs |number | No |Allowed synchronization delay time, in ms. | - -**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) { - console.log('Sync put success'); - const devices = ['deviceList']; - const mode = distributedData.SyncMode.PULL_ONLY; - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - kvStore.sync(devices, query, mode , 1000); - }); -}catch(e) { - console.log('Sync e' + e); -} -``` - -### setSyncParam8+ ### - -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 used to return the result. | - -**Example** - -```js -let kvStore; -try { - const defaultAllowedDelayMs = 500; - kvStore.setSyncParam(defaultAllowedDelayMs, function (err,data) { - console.log('SetSyncParam put success'); - }); -}catch(e) { - console.log('testSingleKvStoreSetSyncParam e ' + e); -} -``` - - -### setSyncParam8+ ### - -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('SetSyncParam put success'); - }).catch((err) => { - console.log('SetSyncParam put fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('SetSyncParam e ' + e); -} -``` - - -### getSecurityLevel8+ ### - -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. | - -**Example** - -```js -let kvStore; -try { - kvStore.getSecurityLevel(function (err,data) { - console.log('getSecurityLevel success'); - }); -}catch(e) { - console.log('GetSecurityLevel e ' + e); -} -``` - - -### getSecurityLevel8+ ### - -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.| - -**Example** - -```js -let kvStore; -try { - kvStore.getSecurityLevel().then((data) => { - console.log(' getSecurityLevel success'); - }).catch((err) => { - console.log('getSecurityLevel fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('GetSecurityLevel e ' + e); -} -``` - - -## DeviceKVStore8+ ## - -Provides methods to query and synchronize data in a device KV store. This class inherits from [KVStore](#kvstore). - -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. - -### get8+ ### - -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 used to return the value obtained. | - -**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 success'); - kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, function (err,data) { - console.log('get success'); - }); - }) -}catch(e) { - console.log('get e' + e); -} -``` - - -### get8+ ### - -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.| - -**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 success'); - kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { - console.log('get success'); - }).catch((err) => { - console.log('get fail ' + JSON.stringify(err)); - }); - }).catch((error) => { - console.log('put error' + error); - }); -} catch (e) { - console.log('Get e ' + e); -} -``` - - -### getEntries8+ ### - -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 used to return the KV pairs obtained. | - -**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 : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - console.log('entries: ' + entries); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err,entries) { - console.log('getEntries success'); - console.log('entries.length: ' + entries.length); - console.log('entries[0]: ' + JSON.stringify(entries[0])); - }); - }); -}catch(e) { - console.log('PutBatch e ' + e); -} -``` - - -### getEntries8+ ### - -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.| - -**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 : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - console.log('entries: ' + entries); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entries) => { - console.log('getEntries success'); - console.log('entries.length: ' + entries.length); - console.log('entries[0]: ' + JSON.stringify(entries[0])); - console.log('entries[0].value: ' + JSON.stringify(entries[0].value)); - console.log('entries[0].value.value: ' + entries[0].value.value); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('PutBatch e ' + e); -} -``` - - -### getEntries8+ ### - -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.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. | - -**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 : distributedData.ValueType.BYTE_ARRAY, - value : arr - } - } - entries.push(entry); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - kvStore.getEntries(query, function (err,entries) { - console.log('getEntries success'); - console.log('entries.length: ' + entries.length); - console.log('entries[0]: ' + JSON.stringify(entries[0])); - }); - }); - console.log('GetEntries success'); -}catch(e) { - console.log('GetEntries e ' + e); -} -``` - - -### getEntries8+ ### - -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.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.| - -**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 : distributedData.ValueType.BYTE_ARRAY, - value : arr - } - } - entries.push(entry); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getEntries(query).then((entries) => { - console.log('getEntries success'); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('GetEntries putBatch fail ' + JSON.stringify(err)) - }); - console.log('GetEntries success'); -}catch(e) { - console.log('GetEntries e ' + e); -} -``` - - -### getEntries8+ ### - -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](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback invoked to return the KV pairs obtained. | - -**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 : distributedData.ValueType.BYTE_ARRAY, - value : arr - } - } - entries.push(entry); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - var query = new distributedData.Query(); - query.deviceId('localDeviceId'); - query.prefixKey("batch_test"); - kvStore.getEntries('localDeviceId', query, function (err,entries) { - console.log('getEntries success'); - console.log('entries.length: ' + entries.length); - console.log('entries[0]: ' + JSON.stringify(entries[0])); - }) - }); - console.log('GetEntries success'); -}catch(e) { - console.log('GetEntries e ' + e); -} -``` - - -### getEntries8+ ### - -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](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.| - -**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 : distributedData.ValueType.BYTE_ARRAY, - value : arr - } - } - entries.push(entry); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - var query = new distributedData.Query(); - query.deviceId('localDeviceId'); - query.prefixKey("batch_test"); - kvStore.getEntries('localDeviceId', query).then((entries) => { - console.log('getEntries success'); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); - console.log('GetEntries success'); -}catch(e) { - console.log('GetEntries e ' + e); -} -``` - - -### getResultSet8+ ### - -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](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async function (err, result) { - console.log('getResultSet succeed.'); - resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { - console.log('closeResultSet success'); - }) - }); -}catch(e) { - console.log('GetResultSet e ' + e); -} -``` - - -### getResultSet8+ ### - -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](#kvstoreresultset8)[]> |Promise used to return the **KvStoreResultSet** object obtained.| - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('localDeviceId', 'batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + JSON.stringify(err)); - }); - kvStore.closeResultSet(resultSet).then((err) => { - console.log('closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('GetResultSet e ' + e); -} -``` - - -### getResultSet8+ ### - -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.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | - -**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 : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - kvStore.getResultSet(query, async function (err, result) { - console.log('getResultSet succeed.'); - resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { - console.log('closeResultSet success'); - }) - }); - }); -} catch(e) { - console.log('GetResultSet e ' + e); -} -``` - - -### getResultSet8+ ### - -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.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)[]> |Promise used to return the **KvStoreResultSet** object obtained.| - -**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 : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + err); - }); - const query = new distributedData.Query(); - query.deviceId('localDeviceId'); - query.prefixKey("batch_test"); - console.log("GetResultSet " + query.getSqlLike()); - kvStore.getResultSet(query).then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + JSON.stringify(err)); - }); - kvStore.closeResultSet(resultSet).then((err) => { - console.log('closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('GetResultSet e ' + e); -} -``` - - -### getResultSet8+ ### - -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 target device. | -| query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | - -**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 : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSet('localDeviceId', query, async function (err, result) { - console.log('getResultSet succeed.'); - resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { - console.log('closeResultSet success'); - }) - }); - }); -} catch(e) { - console.log('GetResultSet e ' + e); -} -``` - - -### getResultSet8+ ### - -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 target device. | -| query |[Query](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)[]> |Promise used to return the **KvStoreResultSet** object obtained.| - -**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 : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries).then(async (err) => { - console.log('GetResultSet putBatch success'); - }).catch((err) => { - console.log('PutBatch putBatch fail ' + JSON.stringify(err)); - }); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSet('localDeviceId', query).then((result) => { - console.log('GetResultSet getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('GetResultSet getResultSet failed: ' + JSON.stringify(err)); - }); - query.deviceId('localDeviceId'); - console.log("GetResultSet " + query.getSqlLike()); - kvStore.closeResultSet(resultSet).then((err) => { - console.log('GetResultSet closeResultSet success'); - }).catch((err) => { - console.log('GetResultSet closeResultSet fail ' + JSON.stringify(err)); - }); - -}catch(e) { - console.log('GetResultSet e ' + e); -} -``` - - -### closeResultSet8+ ### - -closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void - -Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| resultSet |[KvStoreResultSet](#getresultset8) | Yes |**KvStoreResultSet** object to close. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -try { - console.log('CloseResultSet success'); - let resultSet = null; - kvStore.closeResultSet(resultSet, function (err, data) { - if (err == undefined) { - console.log('closeResultSet success'); - } else { - console.log('closeResultSet fail'); - } - }); -}catch(e) { - console.log('CloseResultSet e ' + e); -} -``` - - -### closeResultSet8+ ### - -closeResultSet(resultSet: KvStoreResultSet): Promise<void> - -Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| resultSet |[KvStoreResultSet](#getresultset8) | Yes |**KvStoreResultSet** object to close. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -try { - console.log('CloseResultSet success'); - let resultSet = null; - kvStore.closeResultSet(resultSet).then(() => { - console.log('closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('CloseResultSet e ' + e); -} -``` - - -### getResultSize8+ ### - -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.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<number> | Yes |Callback invoked to return the number of results obtained. | - -**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 : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - kvStore.getResultSize(query, async function (err, resultSize) { - console.log('getResultSet succeed.'); - }); - }); -} catch(e) { - console.log('GetResultSize e ' + e); -} -``` - - -### getResultSize8+ ### - -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.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<number> |Promise used to return the number of results obtained.| - -**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 : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - kvStore.getResultSize(query).then((resultSize) => { - console.log('getResultSet succeed.'); - }).catch((err) => { - console.log('getResultSet failed: ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('GetResultSize e ' + e); -} -``` - - -### getResultSize8+ ### - -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 target device. | -| query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<number> | Yes |Callback invoked to return the number of results obtained. | - -**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 : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) { - console.log('getResultSet succeed.'); - }); - }); -} catch(e) { - console.log('GetResultSize e ' + e); -} -``` - - -### getResultSize8+ ### - -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 target device. | -| query |[Query](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<number> |Promise used to return the number of results obtained.| - -**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 : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); - var query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSize('localDeviceId', query).then((resultSize) => { - console.log('getResultSet succeed.'); - }).catch((err) => { - console.log('getResultSet failed: ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('GetResultSize e ' + e); -} -``` - - -### removeDeviceData8+ ### - -removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void - -Deletes data of the specified device from this KV store. 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 used to return the result. | - -**Example** - -```js -let kvStore; -const KEY_TEST_STRING_ELEMENT = 'key_test_string'; -const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; -try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { - console.log('RemoveDeviceData put success'); - const deviceid = 'no_exist_device_id'; - kvStore.removeDeviceData(deviceid, async function (err,data) { - if (err == undefined) { - console.log('removeDeviceData success'); - } else { - console.log('removeDeviceData fail'); - kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, async function (err,data) { - console.log('RemoveDeviceData get success'); - }); - } - }); - }); -}catch(e) { - console.log('RemoveDeviceData e ' + e); -} -``` - - -### removeDeviceData8+ ### - -removeDeviceData(deviceId: string): Promise<void> - -Deletes data of the specified device from this KV store. 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.| - -**Example** - -```js -let kvStore; -const KEY_TEST_STRING_ELEMENT = 'key_test_string'; -const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; -try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => { - console.log('RemoveDeviceData put success'); - }).catch((err) => { - console.log('RemoveDeviceData put fail ' + JSON.stringify(err)); - }); - const deviceid = 'no_exist_device_id'; - kvStore.removeDeviceData(deviceid).then((err) => { - console.log('removeDeviceData success'); - }).catch((err) => { - console.log('removeDeviceData fail ' + JSON.stringify(err)); - }); - kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { - console.log('RemoveDeviceData get success data:' + data); - }).catch((err) => { - console.log('RemoveDeviceData get fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('RemoveDeviceData e ' + e); -} -``` - - -### sync8+ ### - -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 |IDs of the devices to be synchronized.| -| mode |[SyncMode](#syncmode) | Yes |Synchronization mode. | -| delayMs |number | No |Allowed synchronization delay time, in ms. | - -**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) { - console.log('Sync put success'); - const devices = ['deviceList']; - const mode = distributedData.SyncMode.PULL_ONLY; - kvStore.sync(devices, mode); - }); -}catch(e) { - console.log('Sync e' + e); -} -``` - -### sync9+ ### - -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 |IDs of the devices to be synchronized.| -| query |[Query](#query8) | Yes | **Query** object to match.| -| delayMs |number | No |Allowed synchronization delay time, in ms. | - -**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) { - console.log('Sync put success'); - const devices = ['deviceList']; - const mode = distributedData.SyncMode.PULL_ONLY; - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - kvStore.sync(devices, query, 1000); - }); -}catch(e) { - console.log('Sync e' + e); -} -``` - -### on('syncComplete')8+ ### - -on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void - -Subscribes to the data 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 the data synchronization complete event.| -| syncCallback |Callback | 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('syncComplete put success'); - }).catch((error) => { - console.log('syncComplete put fail ' + error); - }); -}catch(e) { - console.log('syncComplete put e ' + e); -} -``` - - -### off('syncComplete')8+ ### - -off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void - -Unsubscribes from the synchronization complete events. This API returns the result synchronously. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates the data synchronization complete event.| -| syncCallback |Callback9+
### - -on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void - -Subscribes to data changes of the specified type. This API returns the result synchronously. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates data changes. | -| type |[SubscribeType](#subscribetype) | Yes |Subscription type. | -| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the result.| - -**Example** - -```js -let kvStore; -kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { - console.log("dataChange callback call data: " + JSON.stringify(data)); -}); -``` - - -### off('dataChange')9+ ### - -off(event:'dataChange', listener?: Callback<ChangeNotification>): void - -Unsubscribes from the data change events. This API returns the result synchronously. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. | -| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the result.| - -**Example** - -```js -let kvStore; -kvStore.on('dataChange', function (data) { - console.log("callback call data: " + data); -}); -kvStore.off('dataChange', function (data) { - console.log("callback call data: " + data); -}); -``` - -## SyncMode - -Enumerates the synchronization modes. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name | Value | Description | -| ----- | ------ | ----------------------- | -| PULL_ONLY |0 |Pull data from the peer end to the local end only.| -| PUSH_ONLY |1 |Push data from the local end to the peer end only.| -| PUSH_PULL |2 |Push data from the local end to the peer end and then pull data from the peer end to the local end.| - diff --git a/en/application-dev/reference/apis/js-apis-distributed-data.md b/en/application-dev/reference/apis/js-apis-distributed-data.md index bad85aee529e6f5b2bff68cd79fd4172c53e7969..5682921badad9367817fd3e421b1afb823970425 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-data.md +++ b/en/application-dev/reference/apis/js-apis-distributed-data.md @@ -39,26 +39,60 @@ Creates a **KVManager** instance to manage KV stores. This API uses an asynchron | callback | AsyncCallback<[KVManager](#kvmanager)> | Yes | Callback invoked to return the **KVManager** instance created.| **Example** + +Stage model: +```ts +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', + userInfo: { + userId: '0', + userType: distributedData.UserType.SAME_USER_ID + } + } + distributedData.createKVManager(kvManagerConfig, function (err, manager) { + if (err) { + console.log("Failed to create KVManager: " + JSON.stringify(err)); + return; + } + console.log("Created KVManager"); + kvManager = manager; + }); + } +} +``` + +FA model: ```js +import AbilityStage from '@ohos.application.Ability' let kvManager; -try { +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage onCreate") + let context = this.context const kvManagerConfig = { - bundleName : 'com.example.datamanagertest', - userInfo : { - userId : '0', - userType : distributedData.UserType.SAME_USER_ID - } + context: context.getApplicationContext(), + bundleName: 'com.example.datamanagertest', + userInfo: { + userId: '0', + userType: distributedData.UserType.SAME_USER_ID + } } distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.log("createKVManager err: " + JSON.stringify(err)); - return; - } - console.log("createKVManager success"); - kvManager = manager; + if (err) { + console.log("Failed to create KVManager: " + JSON.stringify(err)); + return; + } + console.log("Created KVManager"); + kvManager = manager; }); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); + } } ``` @@ -84,24 +118,59 @@ Creates a **KVManager** instance to manage KV stores. This API uses a promise to **Example** +Stage model: +```ts +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', + userInfo: { + userId: '0', + userType: distributedData.UserType.SAME_USER_ID + } + } + distributedData.createKVManager(kvManagerConfig, function (err, manager) { + if (err) { + console.log("Failed to create KVManager: " + JSON.stringify(err)); + return; + } + console.log("Created KVManager"); + kvManager = manager; + }); + } +} +``` + +FA model: ```js +import AbilityStage from '@ohos.application.Ability' let kvManager; -try { +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage onCreate") + let context = this.context const kvManagerConfig = { - bundleName : 'com.example.datamanagertest', - userInfo : { - userId : '0', - userType : distributedData.UserType.SAME_USER_ID - } + context: context.getApplicationContext(), + bundleName: 'com.example.datamanagertest', + userInfo: { + userId: '0', + userType: distributedData.UserType.SAME_USER_ID + } } - distributedData.createKVManager(kvManagerConfig).then((manager) => { - console.log("createKVManager success"); - kvManager = manager; - }).catch((err) => { - console.log("createKVManager err: " + JSON.stringify(err)); + distributedData.createKVManager(kvManagerConfig, function (err, manager) { + if (err) { + console.log("Failed to create KVManager: " + JSON.stringify(err)); + return; + } + console.log("Created KVManager"); + kvManager = manager; }); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); + } } ``` @@ -113,7 +182,7 @@ Provides configuration of the **KVManager** object, including the bundle name an | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | -| context | Context | Yes| Context of the application or function.
See [Context](js-apis-Context.md) for versions earlier than API version 9.
See [Context](js-apis-ability-context.md) for API version 9 or later.| +| context9+ | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| | userInfo | [UserInfo](#userinfo) | Yes | User information.| | bundleName | string | Yes | Bundle name.| @@ -572,9 +641,9 @@ 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 | +| 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) | No|Security level of the KV store. By default, the security level is not set.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | @@ -1238,7 +1307,7 @@ Creates a **Query** object to match the specified field whose value is equal to | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1273,7 +1342,7 @@ Creates a **Query** object to match the specified field whose value is not equal | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1308,7 +1377,7 @@ Creates a **Query** object to match the specified field whose value is greater t | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1343,7 +1412,7 @@ Creates a **Query** object to match the specified field whose value is less than | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1378,7 +1447,7 @@ Creates a **Query** object to match the specified field whose value is greater t | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1413,7 +1482,7 @@ Creates a **Query** object to match the specified field whose value is less than | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1447,7 +1516,7 @@ Creates a **Query** object to match the specified field whose value is **null**. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1483,7 +1552,7 @@ Creates a **Query** object to match the specified field whose value is within th | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1518,7 +1587,7 @@ Creates a **Query** object to match the specified field whose value is within th | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1553,7 +1622,7 @@ Creates a **Query** object to match the specified field whose value is not withi | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1588,7 +1657,7 @@ Creates a **Query** object to match the specified field whose value is not withi | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1623,7 +1692,7 @@ Creates a **Query** object to match the specified field whose value is similar t | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1658,7 +1727,7 @@ Creates a **Query** object to match the specified field whose value is not simil | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1752,7 +1821,7 @@ Creates a **Query** object to sort the query results in ascending order. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1787,7 +1856,7 @@ Creates a **Query** object to sort the query results in descending order. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1823,7 +1892,7 @@ Creates a **Query** object to specify the number of results and where to start. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1860,7 +1929,7 @@ Creates a **Query** object to match the specified field whose value is not **nul | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1888,7 +1957,7 @@ Creates a **Query** object for a query condition group with a left parenthesis. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1918,7 +1987,7 @@ Creates a **Query** object for a query condition group with a right parenthesis. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1954,7 +2023,7 @@ Creates a **Query** object with a specified key prefix. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1989,7 +2058,7 @@ Creates a **Query** object with an index preferentially used for query. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -2025,7 +2094,7 @@ Creates a **Query** object with the device ID as the key prefix. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -2232,7 +2301,7 @@ try { ### delete9+ -delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<void>): void +delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<void>) Deletes KV pairs that meet the specified predicates. This API uses an asynchronous callback to return the result. @@ -2242,13 +2311,13 @@ Deletes KV pairs that meet the specified predicates. This API uses an asynchrono | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| predicates | Predicates | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| | callback | AsyncCallback<void> | Yes |Callback used to return the result. | **Example** ```js -import dataSharePredicates from './@ohos.data.dataSharePredicates'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let kvStore; try { let predicates = new dataSharePredicates.DataSharePredicates(); @@ -2276,7 +2345,7 @@ Deletes KV pairs that meet the specified predicates. This API uses a promise to | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| predicates | Predicates | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| **Return value** @@ -2288,7 +2357,7 @@ Deletes KV pairs that meet the specified predicates. This API uses a promise to **Example** ```js -import dataSharePredicates from './@ohos.data.dataSharePredicates'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let kvStore; try { let predicates = new dataSharePredicates.DataSharePredicates(); @@ -2312,7 +2381,7 @@ try { ### on('dataChange') -on(event: 'dataChange', type: SubscribeType, observer: Callback<ChangeNotification>): void +on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void Subscribes to data change notifications of the specified type. @@ -2324,7 +2393,7 @@ Subscribes to data change notifications of the specified type. | ----- | ------ | ---- | ----------------------- | | event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates data changes. | | type |[SubscribeType](#subscribetype) | Yes |Type of data changes. | -| observer |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the data changes.| +| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the data changes.| **Example** @@ -2362,7 +2431,7 @@ kvStore.on('syncComplete', function (data) { ### off('dataChange')8+ -off(event:'dataChange', observer?: Callback<ChangeNotification>): void +off(event:'dataChange', listener?: Callback<ChangeNotification>): void Unsubscribes from data change notifications. @@ -2373,7 +2442,7 @@ Unsubscribes from data change notifications. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. | -| observer |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the data changes.| +| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the data changes.| **Example** @@ -2422,7 +2491,7 @@ try { putBatch(entries: Entry[], callback: AsyncCallback<void>): void -Inserts KV pairs to this KV store in batches. This API uses an asynchronous callback to return the result. +Inserts KV pairs in batches to this KV store. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2469,7 +2538,7 @@ try { putBatch(entries: Entry[]): Promise<void> -Inserts KV pairs to this KV store in batches. This API uses a promise to return the result. +Inserts KV pairs in batches to this KV store. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2523,7 +2592,7 @@ try { putBatch(value: Array<ValuesBucket>, callback: AsyncCallback<void>): void -Writes values to this KV store. This API uses an asynchronous callback to return the result. +Writes data to this KV store. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2531,7 +2600,7 @@ Writes values to this KV store. This API uses an asynchronous callback to return | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| value |Array[<ValuesBucket>]()[] | Yes |Values to write. | +| value |Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes |Data to write. | | callback |Asyncallback<void> |Yes |Callback used to return the result.| **Example** @@ -2562,7 +2631,7 @@ try { putBatch(value: Array<ValuesBucket>): Promise<void> -Writes values of the **valuesbucket** type to this KV store. This API uses a promise to return the result. +Writes data of the **valuesbucket** type to this KV store. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2570,7 +2639,7 @@ Writes values of the **valuesbucket** type to this KV store. This API uses a pro | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| value |Array<[ValuesBucket>](#)[] | Yes |Values to write. | +| value |Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes |Data to write. | **Return value** @@ -2607,7 +2676,7 @@ try { deleteBatch(keys: string[], callback: AsyncCallback<void>): void -Deletes KV pairs from this KV store in batches. This API uses an asynchronous callback to return the result. +Deletes KV pairs in batches from this KV store. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2654,7 +2723,7 @@ try { deleteBatch(keys: string[]): Promise<void> -Deletes KV pairs from this KV store in batches. This API uses a promise to return the result. +Deletes KV pairs in batches from this KV store. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2797,7 +2866,7 @@ try { commit(callback: AsyncCallback<void>): void -Submits the transaction in this KV store. This API uses an asynchronous callback to return the result. +Commits the transaction in this KV store. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2829,7 +2898,7 @@ try { commit(): Promise<void> -Submits the transaction in this KV store. This API uses a promise to return the result. +Commits the transaction in this KV store. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3104,7 +3173,7 @@ Defines the **value** object in a KV store. | Name | Type |Readable |Writable | Description | | ----- | ------- | -----| ------|------------------------ | | type | [ValueType](#value) | Yes | Yes|Type of the value. | -| value | Uint8Array \| string \| number \| boolean| Yes | Yes|Value. | +| value | Uint8Array \| string \| number \| boolean| Yes | Yes|Value of the KV pair stored in the KV store. | ## ValueType @@ -3121,7 +3190,6 @@ Enumerates the data types. | BOOLEAN |4 |Boolean. | | DOUBLE |5 |Double (double-precision floating point). | - ## SingleKVStore Provides methods to query and synchronize data in a single KV store. This class inherits from [KVStore](#kvstore). @@ -3641,7 +3709,7 @@ try { getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KvStoreResultSet>): void -Obtains a **KvStoreResultSet** object that matches the specified **Predicates** object. This API uses an asynchronous callback to return the result. +Obtains a **KvStoreResultSet** object that matches the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3649,13 +3717,13 @@ Obtains a **KvStoreResultSet** object that matches the specified **Predicates** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| predicates | Predicates | Yes |**Predicates** object to match. If this parameter is **null**, define the processing logic. | +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |**DataSharePredicates** object to match. If this parameter is **null**, define the processing logic. | | callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.| **Example** ```js -import dataSharePredicates from './@ohos.data.dataSharePredicates'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let kvStore; try { let resultSet; @@ -3676,7 +3744,7 @@ try { getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KvStoreResultSet> -Obtains a **KvStoreResultSet** object that matches the specified **Predicates** object. This API uses a promise to return the result. +Obtains a **KvStoreResultSet** object that matches the specified **DataSharePredicates** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3684,7 +3752,7 @@ Obtains a **KvStoreResultSet** object that matches the specified **Predicates** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| predicates |[Predicates](#) | Yes |**Predicates** object to match. If this parameter is **null**, define the processing logic. | +| predicates |[DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |**DataSharePredicates** object to match. If this parameter is **null**, define the processing logic. | **Return value** @@ -3695,7 +3763,7 @@ Obtains a **KvStoreResultSet** object that matches the specified **Predicates** **Example** ```js -import dataSharePredicates from './@ohos.data.dataSharePredicates'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let kvStore; try { let resultSet; @@ -3704,7 +3772,7 @@ try { kvStore.getResultSet(predicates) .then((result) => { console.log(' GetResultSet success'); resultSet = result; - kvStore.closeResultSet(resultSet, fun ction (err, data) { + kvStore.closeResultSet(resultSet, function (err, data) { console.log(' closeResultSet success'); }) }); @@ -3716,7 +3784,7 @@ try { closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void -Closes the **KvStoreResultSet** object returned by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses an asynchronous callback to return the result. +Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3750,7 +3818,7 @@ try { closeResultSet(resultSet: KvStoreResultSet): Promise<void> -Closes the **KvStoreResultSet** object returned by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses a promise to return the result. +Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3988,7 +4056,7 @@ Subscribes to the data synchronization complete events. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates completion of a data synchronization. | -| syncCallback |Callback<Array<[string, number]>> | Yes |Callback invoked to return the synchronization result. | +| syncCallback |Callback<Array<[string, number]>> | Yes |Callback called to return the synchronization result. | **Example** @@ -4045,7 +4113,7 @@ try { on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void -Subscribes to data changes of the specified type. This API uses a synchronous callback to return the result. +Subscribes to data changes of the specified type. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -4071,7 +4139,7 @@ kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, fun off(event:'dataChange', listener?: Callback<ChangeNotification>): void -Unsubscribes from the data change events. This API uses a synchronous callback to return the result. +Unsubscribes from the data change events. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -4096,7 +4164,7 @@ kvStore.off('dataChange', function (data) { ### sync7+ -sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void +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). @@ -4108,9 +4176,9 @@ Synchronizes the KV store manually. For details about the synchronization modes | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| deviceIdList |string[] | Yes |List of IDs of the devices in the same networking environment to be synchronized. | +| deviceIds |string[] | Yes |List of IDs of the devices in the same networking environment to be synchronized. | | mode |[SyncMode](#syncmode) | Yes |Synchronization mode. | -| allowedDelayMs |number | No |Allowed synchronization delay time, in ms. | +| delayMs |number | No |Allowed synchronization delay time, in ms. | **Example** @@ -4122,7 +4190,7 @@ kvStore.sync('deviceIds', distributedData.SyncMode.PULL_ONLY, 1000); ### sync9+ sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void -Synchronizes the KV store manually. This API uses a synchronous mode. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). +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 @@ -4140,7 +4208,7 @@ Synchronizes the KV store manually. This API uses a synchronous mode. For detail **Example** ```js -let kvstore; +let kvStore; const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; try { @@ -4154,7 +4222,7 @@ try { const query = new distributedData.Query(); query.prefixKey("batch_test"); query.deviceId('localDeviceId'); - kvStore.sync(devices, query, PULL_ONLY , 1000); + kvStore.sync(devices, query, mode , 1000); }); }catch(e) { console.log('Sync e' + e); @@ -5023,7 +5091,7 @@ try { closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void -Closes the **KvStoreResultSet** object returned by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses an asynchronous callback to return the result. +Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5058,7 +5126,7 @@ try { closeResultSet(resultSet: KvStoreResultSet): Promise<void> -Closes the **KvStoreResultSet** object returned by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses a promise to return the result. +Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5391,7 +5459,7 @@ try { ### sync8+ ### -sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void +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). @@ -5403,9 +5471,9 @@ Synchronizes the KV store manually. For details about the synchronization modes | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| deviceIdList |string[] | Yes |IDs of the devices to be synchronized.| +| deviceIds |string[] | Yes |IDs of the devices to be synchronized.| | mode |[SyncMode](#syncmode) | Yes |Synchronization mode. | -| allowedDelayMs |number | No |Allowed synchronization delay time, in ms. | +| delayMs |number | No |Allowed synchronization delay time, in ms. | **Example** @@ -5432,7 +5500,7 @@ try { sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void -Synchronizes the KV store manually. This API uses a synchronous mode. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). +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 @@ -5449,7 +5517,7 @@ Synchronizes the KV store manually. This API uses a synchronous mode. For detail **Example** ```js -let kvstore; +let kvStore; const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; try { @@ -5510,7 +5578,7 @@ try { off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from the synchronization complete events. This API uses a synchronous callback to return the result. +Unsubscribes from the synchronization complete events. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5540,7 +5608,7 @@ try { on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void -Subscribes to data changes of the specified type. This API uses a synchronous callback to return the result. +Subscribes to data changes of the specified type. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5566,7 +5634,7 @@ kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, fun off(event:'dataChange', listener?: Callback<ChangeNotification>): void -Unsubscribes from the data change events. This API uses a synchronous callback to return the result. +Unsubscribes from the data change events. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5600,3 +5668,4 @@ Enumerates the synchronization modes. | PULL_ONLY |0 |Pull data from the peer end to the local end only.| | PUSH_ONLY |1 |Push data from the local end to the peer end only.| | PUSH_PULL |2 |Push data from the local end to the peer end and then pull data from the peer end to the local end.| + diff --git a/en/application-dev/reference/apis/js-apis-enterprise-device-manager.md b/en/application-dev/reference/apis/js-apis-enterprise-device-manager.md index 25c0dbf964cc82eaddc85ff1114c440afbd00d2d..1849150107a5922136403a0c01cb24eb1152d675 100644 --- a/en/application-dev/reference/apis/js-apis-enterprise-device-manager.md +++ b/en/application-dev/reference/apis/js-apis-enterprise-device-manager.md @@ -1,57 +1,93 @@ # Enterprise Device Management -> **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. +The **enterpriseDeviceManager** module provides enterprise device management capabilities so that devices have the customization capabilities required in enterprise scenarios. +> **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 enterpriseDeviceManager from '@ohos.enterpriseDeviceManager'; ``` - ## enterpriseDeviceManager.enableAdmin -enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId?: number, callback: AsyncCallback\): void +enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, callback: AsyncCallback\): void Enables a device administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. -**Required permissions** +**Required permissions**: ohos.permission.MANAGE_ADMIN + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ----------------------------------- | ---- | ------------------ | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | +| type | [AdminType](#AdminType) | Yes | Type of the device administrator to enable. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", +}; +let enterpriseInfo = { + name: "enterprise name", + description: "enterprise description" +} +enterpriseDeviceManager.enableAdmin(wantTemp, enterpriseInfo, enterpriseDeviceManager.AdminType.ADMIN_TYPE_NORMAL, (error, result) => { + if (error != null) { + console.log("error occurs" + error); + return; + } + console.log("result is " + result); +}); +``` + +## enterpriseDeviceManager.enableAdmin + +enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId: number, callback: AsyncCallback\): void -ohos.permission.MANAGE_ADMIN +Enables a device administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. -**System capability** +**Required permissions**: ohos.permission.MANAGE_ADMIN -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | -------- | -------- | -| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | -| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | -| type | [AdminType](#AdminType) | Yes | Type of the device administrator to enable. | -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------------- | ----------------------------------- | ---- | ---------------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | +| type | [AdminType](#AdminType) | Yes | Type of the device administrator to enable. | +| userId | number | Yes | User ID The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -``` +```js let wantTemp = { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", }; let enterpriseInfo = { - name: "enterprise name", - description: "enterprise description" + name: "enterprise name", + description: "enterprise description" } enterpriseDeviceManager.enableAdmin(wantTemp, enterpriseInfo, enterpriseDeviceManager.AdminType.ADMIN_TYPE_NORMAL, 100, (error, result) => { if (error != null) { console.log("error occurs" + error); - return; + return; } - console.log(result); + console.log("result is " + result); }); ``` @@ -61,126 +97,145 @@ enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId Enables a device administrator application based on the specified bundle name and class name. This API uses a promise to return the result. -**Required permissions** - -ohos.permission.MANAGE_ADMIN +**Required permissions**: ohos.permission.MANAGE_ADMIN -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ---------------------------------------------- | ---- | ------------------------ | -| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | -| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | -| type | [AdminType](#AdminType) | Yes | Type of the device administrator to enable. | -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| Name | Type | Mandatory | Description | +| -------------- | ----------------------------------- | ---- | ---------------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | +| type | [AdminType](#AdminType) | Yes | Type of the device administrator to enable. | +| userId | number | No | User ID The default value is the user ID of the caller. The value must be greater than or equal to 0.| **Return value** - | Type | Description | - | ----------------- | --------------------------- | - | Promise\ | Promise used to return the result. | +| Type | Description | +| ----------------- | ----------------- | +| Promise\ | Promise used to return the result.| **Example** -``` +```js let wantTemp = { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", }; let enterpriseInfo = { - name: "enterprise name", - description: "enterprise description" + name: "enterprise name", + description: "enterprise description" } enterpriseDeviceManager.enableAdmin(wantTemp, enterpriseInfo, enterpriseDeviceManager.AdminType.ADMIN_TYPE_NORMAL, 100) .then((result) => { - console.log(result); + console.log("result is " + result); }).catch(error => { - console.log("error occurs" + error); + console.log("error occurs" + error); }); ``` ## enterpriseDeviceManager.disableAdmin -disableAdmin(admin: Want, userId?: number, callback: AsyncCallback\): void +disableAdmin(admin: Want, callback: AsyncCallback\): void Disables a device common administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. -**Required permissions** +**Required permissions**: ohos.permission.MANAGE_ADMIN + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | ------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +let wantTemp = { + bundleName: "bundleName", + abilityName: "abilityName", +}; +enterpriseDeviceManager.disableAdmin(wantTemp, (error, result) => { + if (error != null) { + console.log("error occurs" + error); + return; + } + console.log("result is " + result); +}); +``` + +## enterpriseDeviceManager.disableAdmin + +disableAdmin(admin: Want, userId: number, callback: AsyncCallback\): void -ohos.permission.MANAGE_ADMIN +Disables a device common administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. -**System capability** +**Required permissions**: ohos.permission.MANAGE_ADMIN -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------------- | ---- | ------------------------------ | -| admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. | -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | ---------------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. | +| userId | number | Yes | User ID The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -``` +```js let wantTemp = { - bundleName: elementName.bundleName, - abilityName: elementName.abilityName, + bundleName: "bundleName", + abilityName: "abilityName", }; enterpriseDeviceManager.disableAdmin(wantTemp, 100, (error, result) => { if (error != null) { console.log("error occurs" + error); - return; + return; } - console.log(result); + console.log("result is " + result); }); ``` - - ## enterpriseDeviceManager.disableAdmin disableAdmin(admin: Want, userId?: number): Promise\ Disables a device common administrator application based on the specified bundle name and class name. This API uses a promise to return the result. -**Required permissions** +**Required permissions**: ohos.permission.MANAGE_ADMIN -ohos.permission.MANAGE_ADMIN - -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ---------------------------------------------- | ---- | ------------------ | -| admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. | -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| Name | Type | Mandatory | Description | +| ------ | ----------------------------------- | ---- | ---------------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. | +| userId | number | No | User ID The default value is the user ID of the caller. The value must be greater than or equal to 0.| **Return value** - | Type | Description | - | ----------------- | --------------------------- | - | Promise\ | Promise used to return the result. | +| Type | Description | +| ----------------- | ----------------- | +| Promise\ | Promise used to return the result.| **Example** -``` +```js let wantTemp = { - bundleName: "bundleName", - abilityName: "abilityName", + bundleName: "bundleName", + abilityName: "abilityName", }; enterpriseDeviceManager.disableAdmin(wantTemp, 100).then((result) => { - console.log(result); + console.log("result is " + result); }).catch(error => { - console.log("error occurs" + error); + console.log("error occurs" + error); }); ``` @@ -190,27 +245,25 @@ disableSuperAdmin(bundleName: String, callback: AsyncCallback\): void Disables a device super administrator application based on the specified bundle name. This API uses an asynchronous callback to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | ---------- | ----------------------- | ---- | ------------------------------ | - | bundleName | String | Yes | Bundle name of a device super administrator application. | - | callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| ---------- | ----------------------- | ---- | ------------------- | +| bundleName | String | Yes | Bundle name of the device super administrator application. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** -``` +```js let bundleName = "com.example.myapplication"; enterpriseDeviceManager.disableSuperAdmin(bundleName, (error, result) => { if (error != null) { console.log("error occurs" + error); - return; + return; } - console.log(result); + console.log("result is " + result); }); ``` @@ -220,68 +273,93 @@ disableSuperAdmin(bundleName: String): Promise\ Disables a device super administrator application based on the specified bundle name. This API uses a promise to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | ---------- | ------ | ---- | ------------------------ | - | bundleName | String | Yes | Bundle name of a device super administrator application. | +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | ------------ | +| bundleName | String | Yes | Bundle name of the device super administrator application.| **Return value** - | Type | Description | - | ----------------- | --------------------------- | - | Promise\ | Promise used to return the result. | +| Type | Description | +| ----------------- | ----------------- | +| Promise\ | Promise used to return the result.| **Example** -``` +```js let bundleName = "com.example.myapplication"; enterpriseDeviceManager.disableSuperAdmin(bundleName).then((result) => { - console.log(result); + console.log("result is " + result); }).catch(error => { - console.log("error occurs" + error); + console.log("error occurs" + error); }); ``` ## enterpriseDeviceManager.isAdminEnabled -isAdminEnabled(admin: Want, userId?: number, callback: AsyncCallback\): void +isAdminEnabled(admin: Want, callback: AsyncCallback\): void Checks whether a device administrator application is enabled based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------------- | ---- | -------------------------------- | -| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | -------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** -``` +```js let wantTemp = { - bundleName: elementName.bundleName, - abilityName: elementName.abilityName, + bundleName: "bundleName", + abilityName: "abilityName", }; -enterpriseDeviceManager.isAdminEnabled(wantTemp, 100, (error, result) => { +enterpriseDeviceManager.isAdminEnabled(wantTemp, (error, result) => { if (error != null) { console.log("error occurs" + error); - return; + return; } - console.log(result); + console.log("result is " + result); }); ``` +## enterpriseDeviceManager.isAdminEnabled + +isAdminEnabled(admin: Want, userId: number, callback: AsyncCallback\): void + +Checks whether a device administrator application is enabled based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | ---------------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| userId | number | Yes | User ID The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Example** + +```js +let wantTemp = { + bundleName: "bundleName", + abilityName: "abilityName", +}; +enterpriseDeviceManager.isAdminEnabled(wantTemp, 100, (error, result) => { + if (error != null) { + console.log("error occurs" + error); + return; + } + console.log("result is " + result); +}); +``` ## enterpriseDeviceManager.isAdminEnabled @@ -289,34 +367,32 @@ isAdminEnabled(admin: Want, userId?: number): Promise\ Checks whether a device administrator application is enabled based on the specified bundle name and class name. This API uses a promise to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ---------------------------------------------- | ---- | -------------- | -| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| Name | Type | Mandatory | Description | +| ------ | ----------------------------------- | ---- | ---------------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| userId | number | No | User ID The default value is the user ID of the caller. The value must be greater than or equal to 0.| **Return value** - | Type | Description | - | ----------------- | ------------------------------- | - | Promise\ | Promise used to return the result. | +| Type | Description | +| ----------------- | ------------------- | +| Promise\ | Promise used to return the result.| **Example** -``` +```js let wantTemp = { - bundleName: "bundleName", - abilityName: "abilityName", + bundleName: "bundleName", + abilityName: "abilityName", }; enterpriseDeviceManager.isAdminEnabled(wantTemp, 100).then((result) => { - console.log(result); + console.log("result is " + result); }).catch(error => { - console.log("error occurs" + error); + console.log("error occurs" + error); }); ``` @@ -326,62 +402,56 @@ isSuperAdmin(bundleName: String, callback: AsyncCallback\): void Checks whether a device super administrator application is enabled based on the specified bundle name. This API uses an asynchronous callback to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | ---------- | ----------------------- | ---- | -------------------------------- | - | bundleName | String | Yes | Bundle name of a device super administrator application. | - | callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| ---------- | ----------------------- | ---- | -------------------- | +| bundleName | String | Yes | Device administrator application. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** -``` +```js let bundleName = "com.example.myapplication"; enterpriseDeviceManager.isSuperAdmin(bundleName, (error, result) => { if (error != null) { console.log("error occurs" + error); - return; + return; } - console.log(result); + console.log("result is " + result); }); ``` - - ## enterpriseDeviceManager.isSuperAdmin isSuperAdmin(bundleName: String): Promise\ Checks whether a device super administrator application is enabled based on the specified bundle name. This API uses a promise to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | ---------- | ------ | ---- | ------------------ | - | bundleName | String | Yes | Bundle name of a device super administrator application. | +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | --------- | +| bundleName | String | Yes | Device super administrator application.| **Return value** - | Type | Description | - | ----------------- | ------------------------------- | - | Promise\ | Promise used to return the result. | +| Type | Description | +| ----------------- | ------------------- | +| Promise\ | Promise used to return the result.| **Example** -``` +```js let bundleName = "com.example.myapplication"; enterpriseDeviceManager.isSuperAdmin(bundleName).then((result) => { - console.log(result); + console.log("result is " + result); }).catch(error => { - console.log("error occurs" + error); + console.log("error occurs" + error); }); ``` @@ -391,27 +461,25 @@ getDeviceSettingsManager(callback: AsyncCallback<DeviceSettingsManager>): Obtains a **DeviceSettingsManager** object. This API uses an asynchronous callback to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback { if (error != null) { console.log("error occurs" + error); - return; + return; } mgr.setDateTime(wantTemp, 1526003846000, (error, value) => { if (error != null) { @@ -423,31 +491,28 @@ enterpriseDeviceManager.getDeviceSettingsManager((error, mgr) => { }); ``` - ## enterpriseDeviceManager.getDeviceSettingsManager getDeviceSettingsManager(): Promise<DeviceSettingsManager> Obtains a **DeviceSettingsManager** object. This API uses a promise to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Return value** - | Type | Description | - | -------- | -------- | - | Promise<DeviceSettingsManager> | Promise used to return the **DeviceSettingsManager** object obtained. | +| Type | Description | +| ------------------------------------ | ---------------------------------- | +| Promise<DeviceSettingsManager> | Promise used to return the **DeviceSettingsManager** object obtained.| **Example** -``` +```js let wantTemp = { - bundleName: "bundleName", - abilityName: "abilityName", + bundleName: "bundleName", + abilityName: "abilityName", }; -mgr.getDeviceSettingsManager().then((mgr) => { +enterpriseDeviceManager.getDeviceSettingsManager().then((mgr) => { mgr.setDateTime(wantTemp, 1526003846000).then((value) => { console.log(value); }).catch((error) => { @@ -464,77 +529,72 @@ setEnterpriseInfo(admin: Want, enterpriseInfo: EnterpriseInfo, callback: AsyncCa Sets the enterprise information of a device administrator application. This API uses an asynchronous callback to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | -------------- | ---------------------------------------------- | ---- | ------------------------------------ | - | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | - | enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | - | callback | AsyncCallback\ { - console.log(result); + console.log("result is " + result); }).catch(error => { - console.log("error occurs" + error); + console.log("error occurs" + error); }); ``` - ## enterpriseDeviceManager.setEnterpriseInfo setEnterpriseInfo(admin: Want, enterpriseInfo: EnterpriseInfo): Promise<boolean> Sets the enterprise information of a device administrator application. This API uses a promise to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | -------------- | ---------------------------------------------- | ---- | ------------------------ | - | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | - | enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | +| Name | Type | Mandatory | Description | +| -------------- | ----------------------------------- | ---- | ------------ | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application.| **Return value** - | Type | Description | - | ------------------ | ----------------------------------- | - | Promise\; | Callback used to return the result. | +| Type | Description | +| ----------------- | --------------------- | +| Promise\ | Promise used to return the result.| **Example** -``` +```js let wantTemp = { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", }; let enterpriseInfo = { - name: "enterprise name", - description: "enterprise description" + name: "enterprise name", + description: "enterprise description" } enterpriseDeviceManager.setEnterpriseInfo(wantTemp, enterpriseInfo) .then((result) => { - console.log(result); + console.log("result is " + result); }).catch(error => { - console.log("error occurs" + error); + console.log("error occurs" + error); }); ``` @@ -544,69 +604,64 @@ getEnterpriseInfo(admin: Want, callback: AsyncCallback<EnterpriseInfo>): v Obtains the enterprise information of a device administrator application. This API uses an asynchronous callback to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | -------- | ------------------------------------------------------ | ---- | ---------------------------------------- | - | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | - | callback | AsyncCallback<[EnterpriseInfo](#EnterpriseInfo)> | Yes | Callback used to return the enterprise information of the device administrator application. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------ | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| callback | AsyncCallback<[EnterpriseInfo](#EnterpriseInfo)> | Yes | Callback used to return the enterprise information of the device administrator application.| **Example** -``` +```js let wantTemp = { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", }; enterpriseDeviceManager.getEnterpriseInfo(wantTemp, (error, result) => { if (error != null) { console.log("error occurs" + error); - return; + return; } console.log(result.name); - console.log(result.description); + console.log(result.description); }); ``` - ## enterpriseDeviceManager.getEnterpriseInfo getEnterpriseInfo(admin: Want): Promise<EnterpriseInfo> Obtains the enterprise information of a device administrator application. This API uses a promise to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | ------ | ---------------------------------------------- | ---- | -------------- | - | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| Name | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application.| **Return value** - | Type | Description | - | ------------------------------------------------ | ------------------------------------------- | - | Promise<[EnterpriseInfo](#EnterpriseInfo)> | Promise used to return the enterprise information of the device administrator application. | +| Type | Description | +| ---------------------------------------- | ------------------------- | +| Promise<[EnterpriseInfo](#EnterpriseInfo)> | Promise used to return the enterprise information of the device administrator application.| **Example** -``` +```js let wantTemp = { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", }; enterpriseDeviceManager.getEnterpriseInfo(wantTemp).then((result) => { - console.log(result.name); - console.log(result.description); + console.log(result.name); + console.log(result.description); }).catch(error => { - console.log("error occurs" + error); + console.log("error occurs" + error); }); ``` @@ -614,25 +669,20 @@ enterpriseDeviceManager.getEnterpriseInfo(wantTemp).then((result) => { Describes the enterprise information of a device administrator application. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager - - | Name | Readable/Writable | Type | Mandatory | Description | - | ----------- | -------- | ------ | ---- | ---------------------------------- | - | name | Read only | string | Yes | Name of the enterprise to which the device administrator application belongs. | - | description | Read only | string | Yes | Description of the enterprise to which the device administrator application belongs. | +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager +| Name | Readable/Writable| Type | Mandatory | Description | +| ----------- | ---- | ------ | ---- | ----------------- | +| name | Read only | string | Yes | Name of the enterprise to which the device administrator application belongs.| +| description | Read only | string | Yes | Description of the enterprise to which the device administrator application belongs.| ## AdminType Enumerates the administrator types of the device administrator application. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager - | Name | Default Value | Description | - | -------- | -------- | -------- | - | ADMIN_TYPE_NORMAL | 0x00 | Common administrator. | - | ADMIN_TYPE_SUPER | 0x01 | Super administrator. | +| Name | Default Value | Description | +| ----------------- | ---- | ----- | +| ADMIN_TYPE_NORMAL | 0x00 | Common administrator.| +| ADMIN_TYPE_SUPER | 0x01 | Super administrator.| diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md index 13701cecf67e947c876789d0f1f4acde7f62a601..efd8277b83ac1cbe39a19ebad0fbf49cdf020190 100644 --- a/en/application-dev/reference/apis/js-apis-image.md +++ b/en/application-dev/reference/apis/js-apis-image.md @@ -16,22 +16,23 @@ import image from '@ohos.multimedia.image'; createPixelMap(colors: ArrayBuffer, options: InitializationOptions): Promise\ -Creates a **PixelMap** object. This API uses a promise to return the result. +Creates a **PixelMap** object with the default BGRA_8888 format and pixel properties specified. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Image.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | -| colors | ArrayBuffer | Yes | Color array in BGRA_8888 format. | +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------ | ---- | ---------------------------------------------------------------- | +| colors | ArrayBuffer | Yes | Color array in BGRA_8888 format. | | options | [InitializationOptions](#initializationoptions8) | Yes | Pixel properties, including the alpha type, size, scale mode, pixel format, and editable.| **Return value** -| Type | Description | -| -------------------------------- | -------------- | -| Promise\<[PixelMap](#pixelmap7)> | Promise used to return the **PixelMap** object.| +| Type | Description | +| -------------------------------- | ----------------------------------------------------------------------- | +| Promise\<[PixelMap](#pixelmap7)> | Promise used to return the **PixelMap** object.
If the size of the created pixel map exceeds that of the original image, the pixel map size of the original image is returned.| + **Example** @@ -48,7 +49,7 @@ image.createPixelMap(color, opts) createPixelMap(colors: ArrayBuffer, options: InitializationOptions, callback: AsyncCallback\): void -Creates a **PixelMap** object. This API uses an asynchronous callback to return the result. +Creates a **PixelMap** object with the default BGRA_8888 format and pixel properties specified. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Image.Core @@ -91,7 +92,7 @@ Provides APIs to read or write image pixel map data and obtain image pixel map i readPixelsToBuffer(dst: ArrayBuffer): Promise\ -Reads image pixel map data and writes the data to an **ArrayBuffer**. This API uses a promise to return the result. +Reads image pixel map data and writes the data to an **ArrayBuffer**. This API uses a promise to return the result. If the pixel map is created in the BGRA_8888 format, the pixel map data read is the same as the original data. **System capability**: SystemCapability.Multimedia.Image.Core @@ -122,7 +123,7 @@ pixelmap.readPixelsToBuffer(readBuffer).then(() => { readPixelsToBuffer(dst: ArrayBuffer, callback: AsyncCallback\): void -Reads image pixel map data and writes the data to an **ArrayBuffer**. This API uses an asynchronous callback to return the result. +Reads image pixel map data and writes the data to an **ArrayBuffer**. This API uses an asynchronous callback to return the result. If the pixel map is created in the BGRA_8888 format, the pixel map data read is the same as the original data. **System capability**: SystemCapability.Multimedia.Image.Core @@ -1008,7 +1009,7 @@ const imageSourceApi = image.createImageSource(fd); createImageSource(buf: ArrayBuffer): ImageSource -Creates an **ImageSource** instance based on the buffer. +Creates an **ImageSource** instance based on the buffers. **System capability**: SystemCapability.Multimedia.Image.ImageSource @@ -1029,7 +1030,7 @@ const imageSourceApi = image.createImageSource(buf); createImageSource(buf: ArrayBuffer, options: SourceOptions): ImageSource -Creates an **ImageSource** instance based on the buffer. +Creates an **ImageSource** instance based on the buffers. **System capability**: SystemCapability.Multimedia.Image.ImageSource @@ -1057,7 +1058,7 @@ const imageSourceApi = image.createImageSource(data); CreateIncrementalSource(buf: ArrayBuffer): ImageSource -Creates an **ImageSource** instance in incremental mode based on the buffer. +Creates an **ImageSource** instance in incremental mode based on the buffers. **System capability**: SystemCapability.Multimedia.Image.ImageSource @@ -1084,7 +1085,7 @@ const imageSourceApi = image.CreateIncrementalSource(buf); CreateIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource -Creates an **ImageSource** instance in incremental mode based on the buffer. +Creates an **ImageSource** instance in incremental mode based on the buffers. **System capability**: SystemCapability.Multimedia.Image.ImageSource @@ -2246,7 +2247,7 @@ Describes image properties. ## PropertyKey7+ -Describes the exchangeable image file format (Exif) information of an image. +Describes the exchangeable image file format (EXIF) information of an image. **System capability**: SystemCapability.Multimedia.Image.Core @@ -2322,7 +2323,7 @@ Enumerates the response codes returned upon build errors. | ERR_IMAGE_CROP | 62980109 | An error occurs during image cropping. | | ERR_IMAGE_SOURCE_DATA | 62980110 | The image source data is incorrect. | | ERR_IMAGE_SOURCE_DATA_INCOMPLETE | 62980111 | The image source data is incomplete. | -| ERR_IMAGE_MISMATCHED_FORMAT | 62980112 | The image format does not match. | +| ERR_IMAGE_MISMATCHED_FORMAT | 62980112 | The image formats do not match. | | ERR_IMAGE_UNKNOWN_FORMAT | 62980113 | Unknown image format. | | ERR_IMAGE_SOURCE_UNRESOLVED | 62980114 | The image source is not parsed. | | ERR_IMAGE_INVALID_PARAMETER | 62980115 | Invalid image parameter. | @@ -2338,4 +2339,4 @@ Enumerates the response codes returned upon build errors. | ERR_IMAGE_READ_PIXELMAP_FAILED | 62980246 | Failed to read the pixel map. | | ERR_IMAGE_WRITE_PIXELMAP_FAILED | 62980247 | Failed to write the pixel map. | | ERR_IMAGE_PIXELMAP_NOT_ALLOW_MODIFY | 62980248 | Modification to the pixel map is not allowed. | -| ERR_IMAGE_CONFIG_FAILED | 62980259 | The software parameter setting is incorrect. | +| ERR_IMAGE_CONFIG_FAILED | 62980259 | The configuration is incorrect. | diff --git a/en/application-dev/reference/apis/js-apis-medialibrary.md b/en/application-dev/reference/apis/js-apis-medialibrary.md index 5589051694d6aa726df14d2c87b5425f314873da..b59e88a401cebca64a2be96b29de92dd375e893d 100644 --- a/en/application-dev/reference/apis/js-apis-medialibrary.md +++ b/en/application-dev/reference/apis/js-apis-medialibrary.md @@ -2278,7 +2278,7 @@ Describes options for fetching media files. | Name | Type | Readable| Writable| Mandatory| Description | | ----------------------- | ------------------- | ---- | ---- | ---- | ------------------------------------------------------------ | -| selections | string | Yes | Yes | Yes | Conditions for fetching files. The enumerated values in [FileKey](#filekey8) are used as the column names of the conditions. Example:
selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?',| +| selections | string | Yes | Yes | Yes | Conditions for fetching files. The enumerated values in [FileKey](#filekey8) are used as the column names of the conditions. Example:
selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR ' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?', | | selectionArgs | Array<string> | Yes | Yes | Yes | Value of the condition, which corresponds to the value of the condition column in **selections**.
Example:
selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], | | order | string | Yes | Yes | No | Sorting mode of the search results, which can be ascending or descending. The enumerated values in [FileKey](#filekey8) are used as the columns for sorting the search results. Example:
Ascending: order: mediaLibrary.FileKey.DATE_ADDED + " AESC"
Descending: order: mediaLibrary.FileKey.DATE_ADDED + " DESC"| | uri8+ | string | Yes | Yes | No | File URI. | diff --git a/en/application-dev/reference/apis/js-apis-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md index e1dbb5f4a54b3936dc4b52e76ab5ad0fc0a39265..58d29f74c3196918f08da1b8e12babc71efc5347 100644 --- a/en/application-dev/reference/apis/js-apis-osAccount.md +++ b/en/application-dev/reference/apis/js-apis-osAccount.md @@ -801,7 +801,7 @@ Obtains the OS account ID based on domain account information. This API uses an | Name | Type | Mandatory| Description | | ---------- | --------------------------------------- | ---- | -------------------------------------------- | -| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information. | +| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information. | | callback | AsyncCallback<number> | Yes | Callback used to return the ID of the OS account associated with the domain account.| **Example** @@ -829,7 +829,7 @@ Obtains the OS account ID based on domain account information. This API uses a p | Name | Type | Mandatory| Description | | ---------- | --------------------------------------- | ---- | ------------ | -| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information.| +| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information.| **Return value** @@ -1156,7 +1156,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | :--------- | ---------------------------------------------------- | ---- | ------------------------------------------ | | type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create. | -| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information. | +| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information. | | callback | AsyncCallback<[OsAccountInfo](#osaccountinfo)> | Yes | Callback used to return the OS account created.| **Example** @@ -1187,7 +1187,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | --------------------------------------- | ---- | ---------------------- | | type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create.| -| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information. | +| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information. | **Return value** @@ -1749,7 +1749,7 @@ This is a system API and cannot be called by third-party applications. getBundleIdFromUid(uid: number, callback: AsyncCallback<number>): void; -Obtains the bundle ID based on the UID. This API uses an asynchronous callback to return the result. +Obtains the bundle ID based on the UID. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1760,7 +1760,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | -------------------------- | ---- | ------------------------------------------------------------ | | uid | number | Yes | Process UID.| -| callback | AsyncCallback<number> | Yes | Callback used to return the bundle ID obtained. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the bundle ID obtained. | **Example** @@ -1854,7 +1854,7 @@ This is a system API and cannot be called by third-party applications. queryOsAccountConstraintSourceTypes(localId: number, constraint: string, callback: AsyncCallback<Array<ConstraintSourceTypeInfo>>): void; -Obtains the constraint source information of an OS account. +Obtains the constraint source information of an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1868,7 +1868,7 @@ This is a system API and cannot be called by third-party applications. | -------- | -------------------------- | ---- | ------------------------------------------------------------ | | localId | number | Yes | ID of the target OS account.| | constraint | string | Yes | Name of the [constraint](#constraints) to query.| -| callback | AsyncCallback<Array<[ConstraintSourceTypeInfo](#constraintsourcetypeinfo)>> | Yes | Callback used to return the source information about the specified [constraint] (#constraints). | +| callback | AsyncCallback<Array<[ConstraintSourceTypeInfo](#constraintsourcetypeinfo)>> | Yes | Callback invoked to return the source information about the specified [constraint](#constraints). | **Example** @@ -1902,7 +1902,7 @@ This is a system API and cannot be called by third-party applications. | Type | Description | | :-------------------- | :----------------------------------------------------------- | -| Promise<Array<[ConstraintSourceTypeInfo](#constraintsourcetypeinfo)>> | Promise used to return the source information about the specified [constraint] (#constraints).| +| Promise<Array<[ConstraintSourceTypeInfo](#constraintsourcetypeinfo)>> | Promise used to return the source information about the specified [constraint](#constraints).| **Example** @@ -1912,6 +1912,1289 @@ This is a system API and cannot be called by third-party applications. console.info("queryOsAccountConstraintSourceType sourceTypeInfos:" + JSON.stringify(sourceTypeInfos)); ``` +## UserAuth8+ + +Provides APIs for user authentication. + +### constructor8+ + +constructor() + +A constructor used to create an instance for user authentication. + +**System capability**: SystemCapability.Account.OsAccount + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + console.info('====>test for examples constructor success'); + ``` + + +### getVersion8+ + +getVersion(): number; + +Obtains version information. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Return value** + +| Type | Description | +| :----- | :----------- | +| number | Version information obtained.| + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + console.info('====>test for examples constructor success'); + var version = userAuth.getVersion(); + console.info('====>test for examples version is : ' + JSON.stringify(version)); + ``` + +### getAvailableStatus8+ + +getAvailableStatus(authType: AuthType, authTrustLevel: AuthTrustLevel): number; + +Checks whether the identity authentication function is available. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | -----------------------------------------------| ---- | ------------------------- | +| authType | [AuthType](#AuthType8+) | Yes | Authentication credential type. | +| authTrustLevel | [AuthTrustLevel](#AuthTrustLevel8+) | Yes | Trust level of the authentication result.| + +**Return value** + +| Type | Description | +| :----- | :---------------------------------------- | +| number | Result code(#ResultCode8+).| + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + let authType = osAccount.AuthType.PIN; + let authTrustLevel = osAccount.AuthTrustLevel.ATL1; + console.info('====>test for examples constructor success'); + let availableStatus = userAuth.getAvailableStatus(authType, authTrustLevel); + console.info('====>test for examples AvailabeStatus is : ' + JSON.stringify(availableStatus)); + ``` + +### getProperty8+ + +getProperty(request: GetPropertyRequest, callback: AsyncCallback<ExecutorProperty>): void; + +Obtains the executor property based on the request. This API uses an asynchronous callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------------------- | ---- | ---------------------------------- | +| request | [GetPropertyRequest](#GetPropertyRequest8+) | Yes | Request information, including the authentication credential type and property list.| +| callback | AsyncCallback<[ExecutorProperty](#ExecutorProperty8+)> | Yes | Callback invoked to return the executor property obtained. | + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + let authType = osAccount.AuthType.PIN; + let keys = new Array(); + keys[0] = osAccount.GetPropertyType.AUTH_SUB_TYPE; + keys[1] = osAccount.GetPropertyType.REMAIN_TIMES; + keys[2] = osAccount.GetPropertyType.FREEZING_TIME; + let getPropertyRequest = {authType, keys}; + userAuth.getProperty(getPropertyRequest,function (propReq) { + console.log("====>test for examples getallAuthInfo AsyncCallback = " + JSON.stringify(propReq)); + }) + ``` + +### getProperty8+ + +getProperty(request: GetPropertyRequest): Promise; + +Obtains the executor property based on the request. This API uses a promise to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------ | ---- | ---------------------------------- | +| request | [GetPropertyRequest](#GetPropertyRequest8+) | Yes | Request information, including the authentication credential type and property list.| + +**Return value** + +| Type | Description | +| :---------------------------------------------------------------- | :-------------------------------------------------- | +| Promise<[ExecutorProperty](#ExecutorProperty8+)> | Promise used to return the executor property obtained.| + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + let authType = osAccount.AuthType.PIN; + let keys = new Array(); + keys[0] = osAccount.GetPropertyType.AUTH_SUB_TYPE; + keys[1] = osAccount.GetPropertyType.REMAIN_TIMES; + keys[2] = osAccount.GetPropertyType.FREEZING_TIME; + let getPropertyRequest = {authType, keys}; + userAuth.getProperty(getPropertyRequest).then((propReq) => { + console.log("====>test for examples getallAuthInfo AsyncCallback = " + JSON.stringify(propReq)); + }); + ``` + +### setProperty8+ + +setProperty(request: SetPropertyRequest, callback: AsyncCallback): void; + +Sets the property for the initialization algorithm. This API uses an asynchronous callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | ---------------------------------------------------------------------- | +| request | [SetPropertyRequest](#SetPropertyRequest8+)| Yes | Request information, including the authentication credential type and key value to set. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the [result code](#ResultCode8+).| + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + let authType = osAccount.AuthType.PIN; + let key = osAccount.SetPropertyType.INIT_ALGORITHM; + let setInfo = new Uint8Array(); + let setPropertyRequest = {authType, key, setInfo}; + userAuth.setProperty(setPropertyRequest,function (setProp) { + console.log("====>test for examples setProperty AsyncCallback = " + JSON.stringify(setProp)); + }); + ``` + +### setProperty8+ + +setProperty(request: SetPropertyRequest): Promise; + +Sets the property for the initialization algorithm. This API uses a promise to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------ | ---- | ---------------------------------------- | +| request | [SetPropertyRequest](#SetPropertyRequest8+) | Yes | Request information, including the authentication credential type and the key value to set.| + +**Return value** + +| Type | Description | +| :-------------------- | :-------------------------------------------------------------------------------------------- | +| Promise<number> | Promise used to return the [result code](#ResultCode8+).| + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + let authType = osAccount.AuthType.PIN; + let key = osAccount.SetPropertyType.INIT_ALGORITHM; + let setInfo = new Uint8Array(); + let setPropertyRequest = {authType, key, setInfo}; + userAuth.setProperty(setPropertyRequest).then((setProp) => { + console.log("====>test for examples setProperty AsyncCallback = " + JSON.stringify(setProp)); + }); + ``` + +### auth8+ + +auth(challenge: Uint8Array, authType: AuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array; + +Performs authentication. This API uses a callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | ---------------------------------------------------- | --- | ------------------------------------ | +| challenge | Uint8Array | Yes | Challenge value, which is a random number used to improve security.| +| authType | [AuthType](#AuthType8+) | Yes | Authentication credential type. | +| authTrustLevel | [AuthTrustLevel](#AuthTrustLevel8+) | Yes | Trust level of the authentication result. | +| callback | [IUserAuthCallback](#IUserAuthCallback8+) | Yes | Callback invoked to return the authentication result and obtained information. | + + +**Return value** + +| Type | Description | +| :--------- | :----------------- | +| Uint8Array | ID of the context for canceling the authentication.| + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + let authType = osAccount.AuthType.PIN; + let challenge = 1; + let authTrustLevel = osAccount.AuthTrustLevel.ATL1; + let onresult = { + authresult: null, + authextr: null, + } + userAuth.auth(challenge, authType,authTrustLevel,{ + onResult: function(result,extraInfo){ + console.log("====>test for examples auth result = " + result); + onresult.authresult = result; + console.log("====>test for examples auth extraInfo = " + JSON.stringify(extraInfo)); + onresult.authextr = extraInfo; + console.info('====>test for examples auth onResult = ' + JSON.stringify(onresult)); + } + }); + ``` + +### authUser8+ + +authUser(userId: number, challenge: Uint8Array, authType: AuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array; + +Perform user authentication. This API uses a callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | ---------------------------------------------------- | --- | ------------------------------------ | +| userId | number | Yes | User ID. | +| challenge | Uint8Array | Yes | Challenge value, which is a random number used to improve security. | +| authType | [AuthType](#AuthType8+) | Yes | Authentication credential type. | +| authTrustLevel | [AuthTrustLevel](#AuthTrustLevel8+) | Yes | Trust level of the authentication result. | +| callback | [IUserAuthCallback](#IUserAuthCallback8+) | Yes | Callback invoked to return the authentication result and obtained information. | + + +**Return value** + +| Type | Description | +| :--------- | :----------------- | +| Uint8Array | ID of the context for canceling the authentication.| + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + let authType = osAccount.AuthType.PIN; + let challenge = 1; + let authTrustLevel = osAccount.AuthTrustLevel.ATL1; + let userID = 100; + let onresult = { + authresult: null, + authextr: null, + } + userAuth.authUser(userID, challenge, authType, authTrustLevel, { + onResult: function(result,extraInfo){ + console.log("====>test for examples authUser result = " + result); + onresult.authresult = result; + console.log("====>test for examples authUser extraInfo = " + JSON.stringify(extraInfo)); + onresult.authextr = extraInfo; + console.info('====>test for examples authUser onResult = ' + JSON.stringify(onresult)); + } + }); + ``` + +### cancelAuth8+ + +cancelAuth(contextID: Uint8Array): number; + +Cancels authentication. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------| ---------- | ---- | ------------------------------------------ | +| contextID | Uint8Array | Yes | ID of the authentication context. The context ID is dynamically generated.| + +**Return value** + +| Type | Description | +| :----- | :-------------------------------------------------------- | +| number | [Result code](#ResultCode8+).| + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + let contextID = null; + let cancelAuthresult = null; + cancelAuthresult = userAuth.cancelAuth(contextID); + console.log("====>test for examples cancelAuthresult result = " + JSON.stringify(cancelAuthresult)); + ``` + +## PINAuth8+ + +Provides methods for PIN authentication. + +### constructor8+ + +constructor() + +A constructor used to create an instance for PIN authentication. + +**System capability**: SystemCapability.Account.OsAccount + +**Example** + ```js + var pinAuth = new osAccount.PINAuth(); + console.info('====>test for examples constructor success'); + ``` + +### registerInputer + +registerInputer(inputer: IInputer): boolean; + +Registers an inputer. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_PIN_AUTH + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------| ----------------------------------- | --- | ------------------ | +| inputer | [IInputer](#IInputer8+) | Yes | Callback invoked to obtain the PIN.| + +**Return value** + +| Type | Description | +| :------ | :-------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + ```js + var pinAuth = new osAccount.PINAuth(); + var GetAuthSubType = 0; + var AuthSubType = osAccount.AuthSubType.PIN_SIX; + var Inputerdata = [0,1,3]; + var registerresult = pinAuth.registerInputer({ + onGetData: (GetAuthSubType, IInputData) => { + if (GetAuthSubType == 0) { + IInputData.onSetData(AuthSubType, Inputerdata) + } else { + IInputData.onSetData(GetAuthSubType, Inputerdata); + } + } + }) + console.log("====>test for examples RegisterInputer result is: " + registerresult); + ``` + +### unregisterInputer + +unregisterInputer(): void; + +Unregisters the inputer. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_PIN_AUTH + +**Example** + ```js + var pinAuth = new osAccount.PinAuth(); + pinAuth.unregisterInputer(); + ``` + +## UserIdentityManager8+ + +Provides methods for user identity management. + +### constructor8+ + +constructor() + +A constructor used to create an instance for user authentication. + +**System capability**: SystemCapability.Account.OsAccount + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + console.info('====>test for examples constructor success'); + ``` + +### openSession8+ + +openSession(callback: AsyncCallback<Uint8Array>): void; + +Opens a session to start identity management (IDM) so that a challenge value can be obtained. This API uses an asynchronous callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------- | ---- | -------------------------------- | +| callback | AsyncCallback<Uint8Array> | Yes | Callback invoked to return the result. If **0** is returned, the operation failed. If the operation is successful, the challenge value (a non-zero value) will be returned.| + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + var challenge; + userIDM.openSession(function(err, data){ + try{ + console.log("====>test for examples before get challenge"); + console.log("====>test for examples + " + data); + challenge = data; + console.log("====>test for examples end "); + console.log("====>test for examples after get challenge"); + } + catch(e) { + console.info('====>test for examples openSession error = ' + JSON.stringify(e)); + } + }); + ``` + +### openSession8+ + +openSession(): Promise<Uint8Array>; + +Opens a session to start IDM so that a challenge value can be obtained. This API uses a promise to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_USER_IDM + +**Return value** + +| Type | Description | +| :------------------------ | :------------------------------------------------------- | +| Promise<Uint8Array> | Promise used to return the result. If **0** is returned, the operation failed. If the operation is successful, the challenge value (a non-zero value) will be returned.| + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + var challenge; + userIDM.openSession().then((data) => { + try{ + console.log("====>test for examples before get challenge"); + console.log("====>test for examples + " + data); + challenge = data; + console.log("====>test for examples end "); + console.log("====>test for examples after get challenge"); + } + catch(err) { + console.info('====>test for examples faceDemo openSession error1 = ' + JSON.stringify(err)); + } + }) + .catch((err) => { + console.info('====>test for examples faceDemo openSession error2 = ' + JSON.stringify(err)); + }) + ``` + +### addCredential8+ + +addCredential(credentialInfo: CredentialInfo, callback: IIdmCallback): void; + +Adds credential information, which includes the authentication credential type, subtype, and token (if a non-PIN credential is added). This API uses a callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | ------------------------------------------------ | --- | -------------------------------- | +| credentialInfo | [CredentialInfo](#CredentialInfo8+) | Yes | Credential information to add. | +| callback | [IIdmCallback](#IIdmCallback8+) | Yes | Callback invoked to return the result and obtained information. | + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + let CredentialInfo = null; + let onresult = { + addCredresult: null, + credentialId: null, + } + userIDM.addCredential(CredentialInfo, { + onResult: function(result,extraInfo){ + console.info('====>test for examples aaaaaaaaaaaaa'); + console.info("====>test for examples addCredential result = " + result); + console.info("====>test for examples addCredential extraInfo = " + JSON.stringify(extraInfo)); + console.log(result) + onresult.addCredresult= result; + if(extraInfo != undefined) { + onresult.credentialId = extraInfo.credentialId + } else { + onresult.credentialId = null; + } + } + }) + ``` + +### updateCredential8+ + +updateCredential(credentialInfo: CredentialInfo, callback: IIdmCallback): void; + +Updates credential information. This API uses a callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | ------------------------------------------------- | --- | -------------------------------- | +| credentialInfo | [CredentialInfo](#CredentialInfo8+) | Yes | New credential information. | +| callback | [IIdmCallback](#IIdmCallback8+) | Yes | Callback invoked to return the result and obtained information. | + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + let CredentialInfo = null; + let onresult = { + addCredresult: null, + credentialId: null, + } + userIDM.updateCredential(CredentialInfo, { + onResult: function(result,extraInfo){ + console.log("====>test for examples faceDemo updateCredential result = " + result) + onresult.updateCredresult = result + console.log("====>test for examples faceDemo updateCredential credentialId = " + extraInfo.credentialId) + if(extraInfo != undefined) { + onresult.CredentialId = extraInfo.credentialId + } else { + onresult.CredentialId = null; + } + console.info('====>test for examples publicupdateCred updateCredential onResult = ' + JSON.stringify(onresult)); + } + }) + ``` + +### closeSession8+ + +closeSession(): void; + +Closes this session to terminate IDM. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_USER_IDM + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + userIDM.closeSession(); + ``` + +### cancel8+ + +cancel(challenge: Uint8Array): number; + +Cancels an entry based on the challenge value. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ----- | +| challenge | Uint8Array | Yes | Challenge value.| + +**Return value** + +| Type | Description | +| :----- | :-------------------------------------------------------- | +| number | [Result code](#ResultCode8+).| + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + let challenge = 1; + let cancelresult = userIDM.cancel(challenge); + ``` + +### delUser8+ + +delUser(token: Uint8Array, callback: IIdmCallback): void; + +Deletes a user based on the authentication token. The API uses a callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------ | --- | ------------------------- | +| token | Uint8Array | Yes | Authentication token. | +| callback | [IIdmCallback](#IIdmCallback8+) | Yes | Callback invoked to return the result.| + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + let onresult = { + delUserresult: null, + CredentialId: null, + } + let token = null; + userIDM.delUser(token, { + onResult: function(result,extraInfo){ + console.log("====>test for examples delUser result = " + result) + onresult.delUserresult = result + if(extraInfo != undefined) { + onresult.CredentialId = extraInfo.credentialId + } else { + onresult.CredentialId = null; + } + console.info('====>test for examples publicdelUser delUser = ' + JSON.stringify(onresult)); + } + }) + ``` + +### delCred8+ + +delCred(credentialId: Uint8Array, token: Uint8Array, callback: IIdmCallback): void; + +Deletes user credential information. The API uses a callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | ----------------------------------------------- | --- | ---------------------------| +| credentialId | Uint8Array | Yes | Credential ID. | +| token | Uint8Array | Yes | Authentication token. | +| callback | [IIdmCallback](#IIdmCallback8+) | Yes | Callback invoked to return the result.| + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + let onresult = { + delUserresult: null, + CredentialId: null, + } + let credentialId = 1; + let token = null; + userIDM.delCred(credentialId, token,{ + onResult: function(result,extraInfo){ + console.log("====>test for examples delCred result = " + result) + onresult.delCredresult = result + console.log("====>test for examples delCred extraInfo = " + extraInfo) + if(extraInfo != undefined) { + onresult.CredentialId = extraInfo.credentialId + } else { + onresult.CredentialId = null; + } + console.log("====>test for examples delCred onresult = " + JSON.stringify(onresult)); + } + }) + ``` + +### getAuthInfo8+ + +getAuthInfo(callback: AsyncCallback<Array<EnrolledCredInfo>>, authType?: AuthType): void; + +Obtains authentication information. This API uses asynchronous callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------------- | ---- | -------------------------------------------------- | +| callback | AsyncCallback<Array<[EnrolledCredInfo](#EnrolledCredInfo8+)>> | Yes | Callback invoked to return information about all enrolled credentials of the specified type of the user.| +| authType | [AuthType](#AuthType8+) | No | Authentication credential type. | + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + var authType = osAccount.AuthType.PIN; + userIDM.getAuthInfo(authType, function (authInfo) { + console.log("====>test for examples getAuthInfo AsyncCallback = " + JSON.stringify(authInfo)) + }) + ``` + +### getAuthInfo8+ + +getAuthInfo(authType?: AuthType): Promise<Array<EnrolledCredInfo>>; + +Obtains authentication information. This API uses a promise to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | -------- | +| authType | [AuthType](#AuthType8+) | No | Authentication credential type.| + +**Return value** + +| Type | Description | +| :------------------------------------------- | :------------------------------------------------------------------------ | +| Promise<Array<[EnrolledCredInfo](#EnrolledCredInfo8+)>> | Promise used to return information about all enrolled credentials of the specified type of the user.| + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + var authType = osAccount.AuthType.PIN; + userIDM.getAuthInfo(authType).then((authInfo) => { + console.log("====>test for examples getAuthInfo AsyncCallback = " + JSON.stringify(authInfo)) + }) + ``` + +## IInputData8+ + +Provides callbacks for PIN operations. + +### onSetData8+ + +onSetData: (pinSubType: AuthSubType, data: Uint8Array) => void; + +Called to set data. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------- | ---- | ----------------------------------------------- | +| pinSubType | [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** + ```js + console.log("====>test for examples onCreate start "); + var pinAuth = new osAccount.PINAuth(); + var GetAuthSubType = 0; + var AuthSubType = osAccount.AuthSubType.PIN_SIX; + console.log("====>test for examples GetAuthSubType " + GetAuthSubType); + console.log("====>test for examples AuthSubType " + AuthSubType); + var Inputerdata = [0,1,3]; + var registerresult = pinAuth.registerInputer({ + onGetData: (GetAuthSubType, IInputData) => { + console.log("====>test for examples by GetAuthSubType " +GetAuthSubType ); + if (GetAuthSubType == 0) { + console.log("====>test for examples GetAuthSubType == 0 "); + IInputData.onSetData(AuthSubType, Inputerdata) + } else { + console.log("====>test for examples GetAuthSubType == 1 "); + IInputData.onSetData(GetAuthSubType, Inputerdata); + } + } + }) + console.log("====>test for examples RegisterInputer result is: " + registerresult); + ``` + +## IInputer8+ + +Provides callbacks for the PIN input box. + +### onGetData8+ + +onGetData: (callback: IInputData) => void; + +Called to obtain data. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | --------------------------------------- | ---- | --------------- | +| callback | [IInputData](#IInputData8+) | Yes | Called to input the PIN.| + +**Example** + ```js + console.log("====>test for examples onCreate start "); + var pinAuth = new osAccount.PINAuth(); + var GetAuthSubType = 0; + var AuthSubType = osAccount.AuthSubType.PIN_SIX; + console.log("====>test for examples GetAuthSubType " + GetAuthSubType); + console.log("====>test for examples AuthSubType " + AuthSubType); + var Inputerdata = [0,1,3]; + var registerresult = pinAuth.registerInputer({ + onGetData: (GetAuthSubType, IInputData) => { + console.log("====>test for examples by GetAuthSubType " +GetAuthSubType ); + if (GetAuthSubType == 0) { + console.log("====>test for examples GetAuthSubType == 0 "); + IInputData.onSetData(AuthSubType, Inputerdata) + } else { + console.log("====>test for examples GetAuthSubType == 1 "); + IInputData.onSetData(GetAuthSubType, Inputerdata); + } + } + }) + console.log("====>test for examples RegisterInputer result is: " + registerresult); + ``` + +## IUserAuthCallback8+ + +Provides callbacks for user authentication. + +### onResult8+ + +onResult: (result: number, extraInfo: AuthResult) => void; + +Called to return the authentication result code. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------- | ---- | ------------------- | +| result | number | Yes | Authentication result code.| +| extraInfo | [AuthResult](#AuthResult8+) | Yes | Specific authentication result information. If the authentication is successful, the authentication token is returned in **extrainfo**. If the authentication fails, the remaining authentication time is returned. If the authentication executor is locked, the freezing time is returned.| + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + let authType = osAccount.AuthType.PIN; + let challenge = 1; + let authTrustLevel = osAccount.AuthTrustLevel.ATL1; + let onresult = { + authresult: null, + authextr: null, + } + userAuth.auth(challenge, authType,authTrustLevel,{ + onResult: function(result,extraInfo){ + console.log("====>test for examples auth result = " + result); + onresult.authresult = result; + console.log("====>test for examples auth extraInfo = " + JSON.stringify(extraInfo)); + onresult.authextr = extraInfo; + console.info('====>test for examples auth onResult = ' + JSON.stringify(onresult)); + } + }); + ``` + +### onAcquireInfo?8+ + +onAcquireInfo?: (module: number, acquire: number, extraInfo: any) => void; + +Called to return the **TipsCode** during the authentication process. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------- | ---- | ----------------------------- | +| module | number | Yes | Type of authentication executor. | +| acquire | number | Yes | Tip code of the authentication executor.| +| extraInfo | any | Yes | Reserved. | + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + let authType = osAccount.AuthType.PIN; + let challenge = 1; + let authTrustLevel = osAccount.AuthTrustLevel.ATL1; + let onresult = { + authresult: null, + authextr: null, + } + let onacquireinfo = { + authmodule : null, + authacquire : null, + authextr : null + } + userAuth.auth(challenge, authType,authTrustLevel,{ + onResult: function(result,extraInfo){ + console.log("====>test for examples auth result = " + result) + onresult.authresult = result + console.log("====>test for examples auth extraInfo = " + JSON.stringify(extraInfo)); + onresult.authextr = extraInfo; + console.info('====>test for examples auth onResult = ' + JSON.stringify(onresult)); + }, + onAcquireInfo:function (modulea,acquire,extr){ + console.info('====>test for examples publicauth auth onAcquireInfo in'); + onacquireinfo.authmodule = modulea; + onacquireinfo.authacquire = acquire; + onacquireinfo.authextr = extr; + console.log("====>test for examples auth module = " + JSON.stringify(modulea)); + console.info('====>test for examples publicauth auth onAcquireInfo = ' + JSON.stringify(onacquireinfo)); + } + }); + ``` + +## IIdmCallback8+ + +Provides callbacks for IDM. + +### onResult8+ + +onResult: (result: number, extraInfo: AuthResult) => void; + +Called to return the authentication result code. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------- | ---- | ----------------------- | +| result | number | Yes | Authentication result code. | +| extraInfo | [AuthResult](#AuthResult8+) | Yes | Specific information to be transferred.| + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + let CredentialInfo = null; + let onresult = { + addCredresult: null, + credentialId: null, + } + userIDM.updateCredential(CredentialInfo, { + onResult: function(result,extraInfo){ + console.log("====>test for examples updateCredential result = " + result) + onresult.updateCredresult = result + console.log("====>test for examples updateCredential credentialId = " + extraInfo.credentialId) + if(extraInfo != undefined) { + onresult.CredentialId = extraInfo.credentialId + } else { + onresult.CredentialId = null; + } + console.info('====>test for examples publicupdateCred updateCredential onResult = ' + JSON.stringify(onresult)); + } + }) + ``` + +### onAcquireInfo?8+ + +onAcquireInfo?: (module: number, acquire: number, extraInfo: any) => void; + +Called to return the **TipsCode** during the authentication process. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------- | ---- | ----------------------------- | +| module | number | Yes | Type of authentication executor. | +| acquire | number | Yes | Tip code of the authentication executor.| +| extraInfo | any | Yes | Reserved. | + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + let CredentialInfo = null; + let onresult = { + addCredresult: null, + credentialId: null, + } + let onacquireinfo = { + updateCredmodule : null, + updateCredacquire : null, + updateCredextr : null + } + userIDM.updateCredential(CredentialInfo, { + onResult: function(result,extraInfo){ + console.log("====>test for examples updateCredential result = " + result) + onresult.updateCredresult = result + console.log("====>test for examples updateCredential credentialId = " + extraInfo.credentialId) + if(extraInfo != undefined) { + onresult.CredentialId = extraInfo.credentialId + } else { + onresult.CredentialId = null; + } + console.info('====>test for examples publicupdateCred updateCredential onResult = ' + JSON.stringify(onresult)); + }, + onAcquireInfo:function (modulea,acquire,extr){ + console.info('====>test for examples publicupdateCred updateCredential onAcquireInfo in '); + onacquireinfo.updateCredmodule = modulea + onacquireinfo.updateCredacquire = acquire + onacquireinfo.updateCredextr = extr + console.info('====>test for examples updateCredential onacquireinfo = ' + JSON.stringify(onacquireinfo)); + console.log("====>test for examples updateCredential module = " + modulea) + } + }) + ``` + +## GetPropertyRequest8+ + +Defines the request for obtaining property information. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------- | ----- | ----------------------- | +| authType | [AuthType](#AuthType8+) | Yes | Authentication credential type. | +| keys | Array<[GetPropertyType](#GetPropertyType8+)> | Yes | An array of the types of the properties to obtain.| + +## SetPropertyRequest8+ + +Defines the request for setting property information. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------ | ----- | -------------------- | +| authType | [AuthType](#AuthType8+) | Yes | Authentication credential type. | +| keys | [SetPropertyType](#SetPropertyType8+) | Yes | Type of the property to be set.| +| setInfo | Uint8Array | Yes | Information to set. | + +## ExecutorProperty8+ + +Defines the executor property. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Type | Mandatory | Description | +| ------------ | ---------------------------------------- | ----- | ----------------- | +| result | number | Yes | Result. | +| authSubType | [AuthSubType](#AuthSubType8+) | Yes | Authentication credential subtype.| +| remainTimes | number | No | Remaining time. | +| freezingTime | number | No | Freezing time. | + +## AuthResult8+ + +Defines the authentication result information. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Type | Mandatory | Description | +| ------------ | ----------- | ----- | ----------------- | +| token | Uint8Array | No | Authentication token. | +| remainTimes | number | No | Remaining time. | +| freezingTime | number | No | Freezing time. | + +## CredentialInfo8+ + +Defines the credential information. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Type | Mandatory | Description | +| ------------ | ---------------------------------------- | ----- | ----------------- | +| credType | [AuthType](#AuthType8+) | Yes | Authentication credential type. | +| credSubType | [AuthSubType](#AuthSubType8+) | Yes | Credential subtype. | +| token | Uint8Array | Yes | Authentication token. | + +## RequestResult8+ + +Defines the request result information. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Type | Mandatory | Description | +| ------------ | ----------- | ----- | ----------------- | +| credentialId | Uint8Array | No | Credential ID. | + +## EnrolledCredInfo8+ + +Defines enrolled credential information. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Type | Mandatory | Description | +| ------------ | ---------------------------------------- | ----- | ------------------- | +| credentialId | Uint8Array | Yes | Credential ID. | +| authType | [AuthType](#AuthType8+) | Yes | Authentication credential type. | +| authSubType | [AuthSubType](#AuthSubType8+) | Yes | Credential subtype.| +| templateId | Uint8Array | Yes | Credential template ID. | + +## GetPropertyType8+ + +Enumerates the types of the properties to obtain. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| ------------- | ------ | --------- | +| AUTH_SUB_TYPE | 1 | Authentication subtype.| +| REMAIN_TIMES | 2 | Remaining time. | +| FREEZING_TIME | 3 | Freezing time. | + +## SetPropertyType8+ + +Enumerates the types of the properties to set. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| -------------- | ----- | ----------- | +| INIT_ALGORITHM | 1 | Initialization algorithm.| + +## AuthType8+ + +Enumerates the credential types. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| ----- | ----- | ---------------- | +| PIN | 1 | PIN authentication.| +| FACE | 2 | Facial authentication.| + +## AuthSubType8+ + +Enumerates the credential subtypes. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| ---------- | ----- | ------------------ | +| PIN_SIX | 10000 | Six-digit PIN. | +| PIN_NUMBER | 10001 | Custom PIN.| +| PIN_MIXED | 10002 | Custom mixed credential.| +| FACE_2D | 20000 | 2D face credential. | +| FACE_3D | 20001 | 3D face credential. | + +## AuthTrustLevel8+ + +Enumerates the trust levels of the authentication result. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| ---- | ------ | ----------- | +| ATL1 | 10000 | Trust level 1.| +| ATL2 | 20000 | Trust level 2.| +| ATL3 | 30000 | Trust level 3.| +| ATL4 | 40000 | Trust level 4.| + +## Module8+ + +Enumerates the modules from which information is obtained. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| --------- | ------ | ------------------------ | +| FACE_AUTH | 1 | Information obtained from the face authentication module.| + +## ResultCode8+ + +Enumerates the authentication result codes. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| ----------------------- | ----- | ---------------------------------------- | +| SUCCESS | 0 | The authentication is successful or the authentication function is supported. | +| FAIL | 1 | The authentication executor failed to identify the user. | +| GENERAL_ERROR | 2 | Other errors. | +| CANCELED | 3 | The authentication is canceled. | +| TIMEOUT | 4 | The authentication timed out. | +| TYPE_NOT_SUPPORT | 5 | The authentication credential type is not supported. | +| TRUST_LEVEL_NOT_SUPPORT | 6 | The authentication trust level is not supported. | +| BUSY | 7 | The authentication task is not available. Try again after a few seconds.| +| INVALID_PARAMETERS | 8 | Incorrect parameters are detected. | +| LOCKED | 9 | The authentication executor is locked. | +| NOT_ENROLLED | 10 | The authentication executor is not enrolled. | + +## FaceTipsCode8+ + +Enumerates the tip codes for facial authentication. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default 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. | +| FACE_AUTH_TIP_TOO_CLOSE | 3 | The face is too close to the device. | +| FACE_AUTH_TIP_TOO_FAR | 4 | The face is too far away from the device. | +| FACE_AUTH_TIP_TOO_HIGH | 5 | Only the upper part of the face is captured because the device is angled too high. | +| FACE_AUTH_TIP_TOO_LOW | 6 | Only the lower part of the face is captured because the device is angled too low. | +| FACE_AUTH_TIP_TOO_RIGHT | 7 | Only the right part of the face is captured because the device is angled too much to the right.| +| FACE_AUTH_TIP_TOO_LEFT | 8 | Only the left part of the face is captured because the device is angled too much to the left.| +| FACE_AUTH_TIP_TOO_MUCH_MOTION | 9 | The face moves too fast during facial information collection. | +| FACE_AUTH_TIP_POOR_GAZE | 10 | The face is not facing the device. | +| FACE_AUTH_TIP_NOT_DETECTED | 11 | No face is detected. | + +## ingerprintTips8+ + +Enumerates the tip codes for fingerprint authentication. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default 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.| +| FINGERPRINT_TIP_INSUFFICIENT | 2 | Failed to process the fingerprint image due to big noise. | +| FINGERPRINT_TIP_PARTIAL | 3 | Only part of the fingerprint image is detected. | +| FINGERPRINT_TIP_TOO_FAST | 4 | The fingerprint image is incomplete due to quick motion. | +| FINGERPRINT_TIP_TOO_SLOW | 5 | Failed to read the fingerprint image due to lack of motion. | + ## OsAccountInfo Defines information about an OS account. @@ -1932,7 +3215,7 @@ Defines information about an OS account. | isActived8+ | boolean | Yes | Whether the OS account is activated. | | isCreateCompleted8+ | boolean | Yes | Whether the OS account information is complete. | | distributedInfo | [distributedAccount.DistributedInfo](js-apis-distributed-account.md) | No | Distributed account information. | -| domainInfo8+ | [DomainAccountInfo](#domainaccountinfo) | No | Domain account information. | +| domainInfo8+ | [DomainAccountInfo](#domainaccountinfo8) | No | Domain account information. | ## DomainAccountInfo8+ @@ -2017,6 +3300,8 @@ Domain account information. Defines information about the source of a constraint. +This is a system API. + **System capability**: SystemCapability.Account.OsAccount | Name | Type | Mandatory| Description | @@ -2028,6 +3313,8 @@ Defines information about the source of a constraint. Enumerates the constraint sources. +This is a system API. + **System capability**: SystemCapability.Account.OsAccount | Name | Default Value| Description | diff --git a/en/application-dev/reference/apis/js-apis-prompt.md b/en/application-dev/reference/apis/js-apis-prompt.md index 3facc0146ebe2484672cffb3c9a45d0ac7d9f164..971b3408c9a9fdd616fe1133ca3cab3844ee7fd1 100644 --- a/en/application-dev/reference/apis/js-apis-prompt.md +++ b/en/application-dev/reference/apis/js-apis-prompt.md @@ -1,22 +1,22 @@ # Prompt +The **Prompt** module provides APIs for creating and showing toasts, dialog boxes, and action menus. + > **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 prompt from '@ohos.prompt' ``` -## Required Permissions - -None. ## prompt.showToast showToast(options: ShowToastOptions): void -Shows the toast. +Shows a toast. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -26,15 +26,11 @@ Shows the toast. | options | [ShowToastOptions](#showtoastoptions) | Yes | Toast options.| **Example** - ``` - export default { - showToast() { - prompt.showToast({ - message: 'Message Info', - duration: 2000, - }); - } - } + ```js +prompt.showToast({ + message: 'Message Info', + duration: 2000, +}); ``` ## ShowToastOptions @@ -42,11 +38,11 @@ Describes the options for showing the toast. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory | Description | -| -------- | -------------- | ---- | ---------------------------------------- | -| message | string | Yes | Text to display. | -| duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The recommended value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used.| -| bottom | <length> | No | Distance between the toast border and the bottom of the screen. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ------ | ---------------------------------------- | +| message | string\| [Resource](.../ui/ts-types.md#resource-type)9+| Yes | Text to display. | +| duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The recommended value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used.| +| bottom | string\| number | No | Distance between the toast border and the bottom of the screen. | ## prompt.showDialog @@ -69,38 +65,34 @@ Shows a dialog box. This API uses a promise to return the result synchronously. **Example** - ``` - export default { - showDialog() { - prompt.showDialog({ - title: 'Title Info', - message: 'Message Info', - buttons: [ - { - text: 'button1', - color: '#000000', - }, - { - text: 'button2', - color: '#000000', - } - ], - }) - .then(data => { - console.info('showDialog success, click button: ' + data.index); - }) - .catch(err => { - console.info('showDialog error: ' + err); - }) + ```js +prompt.showDialog({ + title: 'Title Info', + message: 'Message Info', + buttons: [ + { + text: 'button1', + color: '#000000', + }, + { + text: 'button2', + color: '#000000', } - } + ], +}) + .then(data => { + console.info('showDialog success, click button: ' + data.index); + }) + .catch(err => { + console.info('showDialog error: ' + err); + }) ``` ## prompt.showDialog showDialog(options: ShowDialogOptions, callback: AsyncCallback<ShowDialogSuccessResponse>):void -Shows a dialog box. This API uses a callback to return the result asynchronously. +Shows a dialog box. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -112,32 +104,27 @@ Shows a dialog box. This API uses a callback to return the result asynchronously | callback | AsyncCallback<[ShowDialogSuccessResponse](#showdialogsuccessresponse)> | Yes | Callback used to return the dialog box response result. | **Example** - ``` - export default { - callback(err, data) { - if(err) { - console.info('showDialog err: ' + err); - return; - } - console.info('showDialog success callback, click button: ' + data.index); + ```js +prompt.showDialog({ + title: 'showDialog Title Info', + message: 'Message Info', + buttons: [ + { + text: 'button1', + color: '#000000', }, - showDialog() { - prompt.showDialog({ - title: 'showDialog Title Info', - message: 'Message Info', - buttons: [ - { - text: 'button1', - color: '#000000', - }, - { - text: 'button2', - color: '#000000', - } - ] - }, this.callback); + { + text: 'button2', + color: '#000000', } + ] +}, (err, data) => { + if (err) { + console.info('showDialog err: ' + err); + return; } + console.info('showDialog success callback, click button: ' + data.index); +}); ``` ## ShowDialogOptions @@ -146,11 +133,11 @@ Describes the options for showing the dialog box. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory | Description | -| ------- | ------ | ---- | ---------------------------------------- | -| title | string | No | Title of the text to display. | -| message | string | No | Text body. | -| buttons | Array | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. One to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.| +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | ---------------------------------------- | +| title | string\| [Resource](.../ui/ts-types.md#resource-type)9+| No | Title of the dialog box. | +| message | string\| [Resource](.../ui/ts-types.md#resource-type)9+| No | Text body. | +| buttons | Array | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. Up to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.| ## ShowDialogSuccessResponse @@ -160,7 +147,7 @@ Describes the dialog box response result. | Name | Type | Description | | ----- | ------ | ------------------- | -| index | number | Index of the selected button in the array.| +| index | number | Index of the selected button in the **buttons** array.| ## prompt.showActionMenu @@ -179,36 +166,31 @@ Shows an action menu. This API uses a callback to return the result asynchronous **Example** - ``` - export default { - callback(err, data) { - if(err) { - console.info('showActionMenu err: ' + err); - return; - } - console.info('showActionMenu success callback, click button: ' + data.index); + ```js +prompt.showActionMenu({ + title: 'Title Info', + buttons: [ + { + text: 'item1', + color: '#666666', }, - showActionMenu() { - prompt.showActionMenu({ - title: 'Title Info', - buttons: [ - { - text: 'item1', - color: '#666666', - }, - { - text: 'item2', - color: '#000000', - }, - ] - }, this.callback) - } + { + text: 'item2', + color: '#000000', + }, + ] +}, (err, data) => { + if (err) { + console.info('showActionMenu err: ' + err); + return; } + console.info('showActionMenu success callback, click button: ' + data.index); +}) ``` ## prompt.showActionMenu -showActionMenu(options: ActionMenuOptions): Promise\ +showActionMenu(options: ActionMenuOptions): Promise<ActionMenuSuccessResponse> Shows an action menu. This API uses a promise to return the result synchronously. @@ -225,30 +207,26 @@ Shows an action menu. This API uses a promise to return the result synchronously | Promise<[ActionMenuSuccessResponse](#actionmenusuccessresponse)> | Promise used to return the action menu response result.| **Example** - ``` - export default { - showActionMenu() { - prompt.showActionMenu({ - title: 'showActionMenu Title Info', - buttons: [ - { - text: 'item1', - color: '#666666', - }, - { - text: 'item2', - color: '#000000', - }, - ] - }) - .then(data => { - console.info('showActionMenu success, click button: ' + data.index); - }) - .catch(err => { - console.info('showActionMenu error: ' + err); - }) - } - } + ```js +prompt.showActionMenu({ + title: 'showActionMenu Title Info', + buttons: [ + { + text: 'item1', + color: '#666666', + }, + { + text: 'item2', + color: '#000000', + }, + ] +}) + .then(data => { + console.info('showActionMenu success, click button: ' + data.index); + }) + .catch(err => { + console.info('showActionMenu error: ' + err); + }) ``` ## ActionMenuOptions @@ -256,10 +234,10 @@ Describes the options for showing the action menu. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory | Description | -| ------- | ------ | ---- | ---------------------------------------- | -| title | string | No | Title of the text to display. | -| buttons | Array | Yes | Array of menu items. The array structure is **{text:'button', color: '\#666666'}**. One to six items are supported. If there are more than six items, extra items will not be displayed.| +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | ---------------------------------------- | +| title | string\| [Resource](.../ui/ts-types.md#resource-type)9+| No | Title of the text to display. | +| buttons | Array<[Button](#button)> | Yes | Array of menu item buttons. The array structure is **{text:'button', color: '\#666666'}**. Up to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.| ## ActionMenuSuccessResponse @@ -269,4 +247,15 @@ Describes the action menu response result. | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ------------------------ | -| index | number | No | Index of the selected button in the array, starting from **0**.| +| index | number | No | Index of the selected button in the **buttons** array, starting from **0**.| + +## Button + +Describes the menu item button in the action menu. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ----- | ---------------------------------------- | ---- | ------- | +| text | string\| [Resource](.../ui/ts-types.md#resource-type)9+| Yes | Button text.| +| color | string\| [Resource](.../ui/ts-types.md#resource-type)9+| Yes | Text color of the button.| diff --git a/en/application-dev/reference/apis/js-apis-request.md b/en/application-dev/reference/apis/js-apis-request.md index b2ff6a8bc7ca45e255a57c9ebe414d12f87157e7..4f6da3208d7bef31f14e626a8fc09c57b5cb0423 100644 --- a/en/application-dev/reference/apis/js-apis-request.md +++ b/en/application-dev/reference/apis/js-apis-request.md @@ -874,7 +874,7 @@ Queries this download task. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Download **Parameters** - | Type| Description| + | Type| Description| | -------- | -------- | | Promise<[DownloadInfo](#downloadinfo7)> | Promise used to return the download task information.| @@ -1113,11 +1113,11 @@ Resumes this download task. This API uses an asynchronous callback to return the | -------- | -------- | -------- | -------- | | url | string | Yes| Resource URL.| | header | object | No| HTTP or HTTPS header added to a download request.| -| enableMetered | boolean | No| Download allowed in metered connections.| -| enableRoaming | boolean | No| Download allowed on a roaming network.| +| enableMetered | boolean | No| Whether download is allowed on a metered connection.
- **true**: yes
**false**: no| +| enableRoaming | boolean | No| Whether download is allowed on a roaming network.
- **true**: yes
**false**: no| | description | string | No| Description of the download session.| | filePath7+ | string | No| Download path. (The default path is **'internal://cache/'**.)
- filePath:'workspace/test.txt': The **workspace** directory is created in the default path to store files.
- filePath:'test.txt': Files are stored in the default path.
- filePath:'workspace/': The **workspace** directory is created in the default path to store files.| -| networkType | number | No| Network type allowed for download.| +| networkType | number | No| Network type allowed for download.
- NETWORK_MOBILE: 0x00000001
- NETWORK_WIFI: 0x00010000| | title | string | No| Title of the download session.| | background | boolean | No| Whether to enable the background task notification. When this parameter is enabled, the download status is displayed in the notification panel.| diff --git a/en/application-dev/reference/arkui-js/js-components-basic-picker.md b/en/application-dev/reference/arkui-js/js-components-basic-picker.md index a4f2af80b8fcd1c922fd021adef5cff0d8eb409d..b02f86a0da6ad041fac054cd5faf003c98755bbb 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-picker.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-picker.md @@ -1,722 +1,169 @@ -# picker +# picker -The **** component supports common, date, time, data and time, and multi-column text selectors. +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +The **\** component supports common, date, time, data and time, and multi-column text selectors. -None -## Child Component +## Required Permissions None -## Attributes - -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

type

-

string

-

-

-

No

-

Dynamic modification is not supported. Available values include:

-
  • text: text selector
  • data: date selector
  • time: time selector
  • datetime: date and time selector
  • multi-text: multi-column text selector
-
- -### Text Selector - -When **type** is set to **text**, a text selector is used. - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

range

-

Array

-

-

-

No

-

Value range of the common selector, for example, ["15", "20", "25"].

-
NOTE:

Use the data binding mode, for example, range = {{data}}. Declare the corresponding variable data: ["15", "20", "25"] in the JavaScript.

-
-

selected

-

string

-

0

-

No

-

Default value of the common selector. The value should be the index of range.

-

value

-

string

-

-

-

No

-

Value of the common selector.

-
- -### Date Selector - -When **type** is set to **date**, a date selector is used. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

start

-

<time>

-

1970-1-1

-

No

-

Start date of the date selector, in the format of YYYY-MM-DD.

-

end

-

<time>

-

2100-12-31

-

No

-

End date of the date selector, in the format of YYYY-MM-DD.

-

selected

-

string

-

Current date

-

No

-

Default value of the date selector, in format of YYYY-MM-DD.

-

value

-

string

-

-

-

Yes

-

Value of the date selector.

-

lunar5+

-

boolean

-

false

-

No

-

Whether the pop-up window displays the lunar calendar.

-

lunarswitch

-

boolean

-

false

-

No

-

Whether the date selector displays the lunar calendar switch, which is used to switch between the Gregorian calendar and lunar calendar. The value true means to display the lunar calendar switch for users to switch between the Gregorian calendar and lunar calendar. The value false means not to display the lunar calendar switch.

-
NOTE:

When both lunarswitch and lunar are set to true, the switch is selected.

-
-
- -### Time Selector - -When **type** is set to **time**, a time selector is used. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

containsecond

-

boolean

-

false

-

No

-

Whether seconds are contained.

-

selected

-

string

-

Current time

-

No

-

Default value of the time selector, in the format of HH:mm. If seconds are contained, the format is HH:mm:ss.

-

value

-

string

-

-

-

No

-

Value of the time selector.

-

hours

-

number

-

241-4

-

-5+

-

No

-

Time format used by the time selector. Available values include:

-
  • 12: displayed in 12-hour format and distinguished by a.m. and p.m.
  • 24: displayed in 24-hour format
    NOTE:

    The default value is the most commonly-used hour format in the current locale. 5+

    -
    -
-
- -### Date and Time Selector - -When **type** is set to **datetime**, a date and time selector is used. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

selected

-

string

-

Current date and time

-

No

-

Default value of the date and time selector. The value can be in either of the following formats:

-
  • MM-DD-HH-mm
  • YYYY-MM-DD-HH-mm
-

If the year is not set, the current year is used by default. The value you set is the date selected by default in the pop-up window.

-

value

-

string

-

-

-

Yes

-

Value of the date and time selector.

-

hours

-

number

-

241-4

-

-5+

-

No

-

Time format used by the date and time selector. Available values include:

-
  • 12: displayed in 12-hour format and distinguished by a.m. and p.m.
  • 24: displayed in 24-hour format
    NOTE:

    The default value is the most commonly-used hour format in the current locale. 5+

    -
    -
-

lunar5+

-

boolean

-

false

-

No

-

Whether the pop-up window displays the lunar calendar.

-

lunarswitch

-

boolean

-

false

-

No

-

Whether the date selector displays the lunar calendar switch, which is used to switch between the Gregorian calendar and lunar calendar. The value true means to display the lunar calendar switch for users to switch between the Gregorian calendar and lunar calendar. The value false means not to display the lunar calendar switch.

-
NOTE:

When both lunarswitch and lunar are set to true, the switch is selected.

-
-
- -### Multi-Column Text Selector - -When **type** is set to **multi-text**, a multi-column text selector is used. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

columns

-

number

-

-

-

Yes

-

Number of columns in the multi-column text selector.

-

range

-

Two-dimensional array

-

-

-

No

-

Items of the multi-column text selector. range is a two-dimensional array that indicates the number of columns. Each item in the array indicates the data of each column, for example, [["a","b"], ["c","d"]].

-
NOTE:

Use the data binding mode, for example, range = {{data}}. Declare the corresponding variable data: [["a","b"], ["c","d"]] in the JavaScript.

-
-

selected

-

Array

-

0,0,0,...

-

No

-

Default value of the multi-column text selector, which is an array consisting of the indexes of the selected items in each column.

-

value

-

Array

-

-

-

No

-

Value of the multi-column text selector, which is an array consisting of the values of the selected items in each column.

-
- -## Styles - -In addition to the styles in [Universal Styles](js-components-common-styles.md), the following styles are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

text-color

-

<color>

-

-

-

No

-

Text color of the selector.

-

font-size

-

<length>

-

-

-

No

-

Font size of the selector.

-

allow-scale

-

boolean

-

true

-

No

-

Whether the font size changes with the system's font size settings.

-
NOTE:

If the config-changes tag of fontSize is configured for abilities in the config.json file, the setting takes effect without application restart.

-
-

letter-spacing

-

<length>

-

0

-

No

-

Letter spacing of the selector. For details, see letter-spacing of the text component.

-

text-decoration

-

string

-

-

-

No

-

Text decoration of the selector. For details, see text-decoration of the text component.

-

font-style

-

string

-

normal

-

No

-

Font style of the selector. For details, see font-style of the text component.

-

font-weight

-

number | string

-

normal

-

No

-

Font weight of the selector. For details, see font-weight of the text component.

-

font-family

-

string

-

sans-serif

-

No

-

Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font that exists in the system or the font specified by Custom Font Styles in the family is selected as the font for the text.

-

line-height

-

<length>

-

0px

-

No

-

Text line height of the selector.

-

column-height5+

-

<length>

-

-

-

No

-

Height of the selector option list.

-
NOTE:

-
-
- -## Events - -In addition to the events in [Universal Events](js-components-common-events.md), the following events are supported. - -### Common Selector - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

change

-

{ newValue: newValue, newSelected: newSelected }

-

Triggered when a value is selected and the OK button is clicked in the displayed pop-up window. newSelected is the index.

-

cancel

-

-

-

Triggered when the cancel button is clicked.

-
- -### Date Selector - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

change

-

{ year: year, month: month, day: day }

-

Triggered when a value is selected and the OK button is clicked in the displayed pop-up window.

-
NOTE:

The value of month ranges from 0 (January) to 11 (December). 5+

-
-

cancel

-

-

-

Triggered when the cancel button is clicked.

-
- -### Date and Time Selector - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

change

-

{ year: year, month: month, day: day, hour: hour, minute: minute}

-

Triggered when a value is selected and the OK button is clicked in the displayed pop-up window.

-

cancel

-

-

-

Triggered when the cancel button is clicked.

-
- -### Time Selector - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

change

-

{ hour: hour, minute: minute, [second: second] }

-

Triggered when a value is selected and the OK button is clicked in the displayed pop-up window. If containsecond is set to true, value contains seconds.

-

cancel

-

-

-

Triggered when the cancel button is clicked.

-
- -### Multi-Column Text Selector - - - - - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

change

-

{ newValue: [newValue1, newValue2, newValue3, …], newSelected:[newSelected1, newSelected2, newSelected3, …] }

-

Triggered when an item is selected and the OK button is clicked in the displayed pop-up window.

-
  • newValue is an array consisting of the values of the selected items.
  • newSelected is an array consisting of the indexes of the selected items. The lengths of newValue and newSelected are the same as the length of range.
-

columnchange

-

{ column: column, newValue: newValue, newSelected: newSelected }

-

Triggered when the value of a column in the multi-column selector changes.

-
  • column indicates the column whose value has changed.
  • newValue indicates the selected value.
  • newSelected indicates the index of the selected value.
-

cancel

-

-

-

Triggered when the cancel button is clicked.

-
- -## Methods - -In addition to the methods in [Universal Methods](js-components-common-methods.md), the following events are supported. - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

show

-

-

-

Displays the picker.

-
- -## Example Code -``` +## Child Components + +Not supported + + +## Attributes + +In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. + +| Name | Type | Default Value | Mandatory | Description | +| ---- | ------ | ---- | ---- | ---------------------------------------- | +| type | string | - | No | Picker type. Dynamic modification is not supported. The options are as follows:
- **text**: text selector.
- **date**: date selector.
- **time**: time selector.
- **datetime**: date and time selector.
- **multi-text**: multi-column text selector.| + + +### Common Selector + +When **type** is set to **text**, a common selector is used. + +| Name | Type | Default Value | Mandatory | Description | +| -------- | ------ | ---- | ---- | ---------------------------------------- | +| range | Array | - | No | Value range of the common selector, for example, **["15", "20", "25"]**.
Use the data binding mode, for example, `range = {{data}}`. Declare the corresponding variable `data: ["15", "20", "25"]` in JavaScript.| +| selected | string | 0 | No | Default value of the common selector. The value should be the index of **range**.| +| value | string | - | No | Value of the common selector. | + + +### Date Selector + +When **type** is set to **date**, a date selector is used. + +| Name | Type | Default Value | Mandatory | Description | +| ------------------ | ------------ | ---------- | ---- | ---------------------------------------- | +| start | <time> | 1970-1-1 | No | Start date of the date selector, in the format of YYYY-MM-DD. | +| end | <time> | 2100-12-31 | No | End date of the date selector, in the format of YYYY-MM-DD. | +| selected | string | Current date | No | Default value of the date selector, in format of YYYY-MM-DD.| +| value | string | - | Yes | Value of the date selector. | +| lunar5+ | boolean | false | No | Whether the pop-up window displays the lunar calendar. | +| lunarswitch | boolean | false | No | Whether the date selector displays the lunar calendar switch, which is used to switch between the Gregorian calendar and lunar calendar. The value **true** means to display the lunar calendar switch for users to switch between the Gregorian calendar and lunar calendar. The value **false** means not to display the lunar calendar switch.
When both **lunarswitch** and **lunar** are set to **true**, the switch is selected.| + + +### Time Selector + +When **type** is set to **time**, a time selector is used. + +| Name | Type | Default Value | Mandatory | Description | +| ------------- | ------- | ----------------------------------- | ---- | ---------------------------------------- | +| containsecond | boolean | false | No | Whether seconds are contained. | +| selected | string | Current time | No | Default value of the time selector, in format of HH:mm. If seconds are contained, the format is HH:mm:ss. | +| value | string | - | No | Value of the time selector. | +| hours | number | 241-4
-5+ | No | Time format used by the time selector. Available values are as follows:
- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.
- **24**: displayed in 24-hour format.
Since API version 5, the default value is the most commonly-used hour format in the current locale.| + + +### Date and Time Selector + +When **type** is set to **datetime**, a date and time selector is used. + +| Name | Type | Default Value | Mandatory | Description | +| ------------------ | ------- | ----------------------------------- | ---- | ---------------------------------------- | +| selected | string | Current date and time | No | Default value of the date and time selector. The value can be in either of the following formats:
- MM-DD-HH-mm
- YYYY-MM-DD-HH-mm
If the year is not set, the current year is used by default. The value you set is the date selected by default in the pop-up window.| +| value | string | - | Yes | Value of the date and time selector. | +| hours | number | 241-4
-5+ | No | Time format used by the date and time selector. Available values are as follows:
- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.
- **24**: displayed in 24-hour format.
Since API version 5, the default value is the most commonly-used hour format in the current locale.| +| lunar5+ | boolean | false | No | Whether the pop-up window displays the lunar calendar. | +| lunarswitch | boolean | false | No | Whether the date selector displays the lunar calendar switch, which is used to switch between the Gregorian calendar and lunar calendar. The value **true** means to display the lunar calendar switch for users to switch between the Gregorian calendar and lunar calendar. The value **false** means not to display the lunar calendar switch.
When both **lunarswitch** and **lunar** are set to **true**, the switch is selected.| + + +### Multi-Column Text Selector + +When **type** is set to **multi-text**, a multi-column text selector is used. + +| Name | Type | Default Value | Mandatory | Description | +| -------- | ------- | --------- | ---- | ---------------------------------------- | +| columns | number | - | Yes | Number of columns in the multi-column text selector. | +| range | Two-dimensional array| - | No | Items of the multi-column text selector. **range** is a two-dimensional array that indicates the number of columns. Each item in the array indicates the data of each column, for example, **[["a", "b"], ["c", "d"]]**.
Use the data binding mode, for example, `range = {{data}}`. Declare the corresponding variable `data: ["15", "20", "25"]` in JavaScript.| +| selected | Array | [0,0,0, ...]| No | Default value of the multi-column text selector, which is an array consisting of the indexes of the selected items in each column.| +| value | Array | - | No | Value of the multi-column text selector, which is an array consisting of the values of the selected items in each column. | + + +## Styles + +In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. + +| Name | Type | Default Value | Mandatory | Description | +| -------------------------- | -------------------------- | ---------- | ---- | ---------------------------------------- | +| text-color | <color> | - | No | Text color of the selector. | +| font-size | <length> | - | No | Font size of the selector. | +| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| +| letter-spacing | <length> | 0 | No | Letter spacing of the selector. For details, see **letter-spacing** in the **[\](../arkui-js/js-components-basic-text.md#styles)** component.| +| text-decoration | string | - | No | Text decoration of the selector. For details, see **text-decoration** in the **[\](../arkui-js/js-components-basic-text.md#styles)** component.| +| font-style | string | normal | No | Font style of the selector. For details, see **font-style** in the **[\](../arkui-js/js-components-basic-text.md#styles)** component.| +| font-weight | number \| string | normal | No | Font weight of the selector. For details, see **font-weight** in the **[\](../arkui-js/js-components-basic-text.md#styles)** component.| +| font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.| +| line-height | <length> | 0px | No | Text line height of the selector. | +| column-height5+ | <length> | - | No | Height of the selector option list. | + + +## Events + +In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported. + + +### Common Selector + +| Name | Parameter | Description | +| ------ | ---------------------------------------- | ---------------------------------------- | +| change | { newValue: newValue, newSelected: newSelected } | Triggered when an item is selected and the OK button is clicked in the displayed pop-up window. **newSelected** is the index.| +| cancel | - | Triggered when the cancel button is clicked. | + + +### Date Selector + +| Name | Parameter | Description | +| ------ | ---------------------------------------- | ---------------------------------------- | +| change | { year: year, month: month, day: day } | Triggered when an item is selected and the OK button is clicked in the displayed pop-up window.
The value of **month** ranges from **0** (January) to **11** (December) since API version 5.| +| cancel | - | Triggered when the cancel button is clicked. | + + +### Date and Time Selector + +| Name | Parameter | Description | +| ------ | ---------------------------------------- | ---------------------------- | +| change | { year: year, month: month, day: day, hour: hour, minute: minute} | Triggered when an item is selected and the OK button is clicked in the displayed pop-up window.| +| cancel | - | Triggered when the cancel button is clicked. | + + +### Time Selector + +| Name | Parameter | Description | +| ------ | ---------------------------------------- | ---------------------------------------- | +| change | { hour: hour, minute: minute, [second: second] } | Triggered when an item is selected and the OK button is clicked in the displayed pop-up window. If **containsecond** is set to true, value contains seconds.| +| cancel | - | Triggered when the cancel button is clicked. | + + +### Multi-Column Text Selector + +| Name | Parameter | Description | +| ------------ | ---------------------------------------- | ---------------------------------------- | +| change | { newValue: [newValue1, newValue2, newValue3, …], newSelected:[newSelected1, newSelected2, newSelected3, …] } | Triggered when an item is selected and the OK button is clicked in the displayed pop-up window.
- **newValue** is an array consisting of the values of the selected items.
- **newSelected** is an array consisting of the indexes of the selected items. The lengths of **newValue** and **newSelected** are the same as the length of **range**.| +| columnchange | { column: column, newValue: newValue, newSelected: newSelected } | Triggered when the value of a column in the multi-column selector changes.
- **column**: column whose value has changed.
- **newValue**: selected value.
- **newSelected**: index of the selected value.| +| cancel | - | Triggered when the cancel button is clicked. | + + +## Methods + +In addition to the [universal methods](../arkui-js/js-components-common-methods.md), the following methods are supported. + +| Name | Parameter | Description | +| ---- | ---- | --------------- | +| show | - | Shows the picker.| + + +## Example + +```html