diff --git a/CODEOWNERS b/CODEOWNERS index a57ea8f6e10f53e073eb37e4fe33e1fffea8b84d..78ded76e8315733c6989c96058bc5826da9c68c0 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -276,6 +276,7 @@ zh-cn/application-dev/faqs/ @zengyawen zh-cn/application-dev/file-management/ @zengyawen zh-cn/application-dev/application-test/ @ningningW zh-cn/application-dev/device-usage-statistics/ @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 +zh-cn/application-dev/web/ @bigpumpkin @HelloCrease @litao33 @zhang-xinyue15 zh-cn/application-dev/reference/apis/js-apis-ability-context.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-ability-errorCode.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen diff --git a/en/application-dev/Readme-EN.md b/en/application-dev/Readme-EN.md index d22073221672cf6f8b01ce137acc6ccc6624beab..5147d8c5200157e6a2edc8091630bbf22a6b9fb6 100644 --- a/en/application-dev/Readme-EN.md +++ b/en/application-dev/Readme-EN.md @@ -46,19 +46,19 @@ - Custom Component - [Creating a Custom Component](quick-start/arkts-create-custom-components.md) - [Page and Custom Component Lifecycle](quick-start/arkts-page-custom-components-lifecycle.md) - - [\@Builder: Custom Builder Function](quick-start/arkts-builder.md) - - [\@BuilderParam: \@Builder Function Reference](quick-start/arkts-builderparam.md) - - [\@Styles: Definition of Resusable Styles](quick-start/arkts-style.md) - - [\@Extend: Extension of Built-in Components](quick-start/arkts-extend.md) + - [\@Builder Decorator: Custom Builder Function](quick-start/arkts-builder.md) + - [\@BuilderParam Decorator: \@Builder Function Reference](quick-start/arkts-builderparam.md) + - [\@Styles Decorator: Definition of Resusable Styles](quick-start/arkts-style.md) + - [\@Extend Decorator: Extension of Built-in Components](quick-start/arkts-extend.md) - [stateStyles: Polymorphic Style](quick-start/arkts-statestyles.md) - State Management - [State Management Overview](quick-start/arkts-state-management-overview.md) - Component State Management - - [\@State: State Owned by Component](quick-start/arkts-state.md) - - [\@Prop: One-Way Synchronization from Parent to Child Components](quick-start/arkts-prop.md) - - [\@Link: Two-Way Synchronization Between Parent and Child Components](quick-start/arkts-link.md) - - [\@Provide and \@Consume: Two-Way Synchronization with Descendant Components](quick-start/arkts-provide-and-consume.md) - - [\@Observed and \@ObjectLink: Observing Attribute Changes in Nested Class Objects](quick-start/arkts-observed-and-objectlink.md) + - [\@State Decorator: State Owned by Component](quick-start/arkts-state.md) + - [\@Prop Decorator: One-Way Synchronization from Parent to Child Components](quick-start/arkts-prop.md) + - [\@Link Decorator: Two-Way Synchronization Between Parent and Child Components](quick-start/arkts-link.md) + - [\@Provide and \@Consume Decorators: Two-Way Synchronization with Descendant Components](quick-start/arkts-provide-and-consume.md) + - [\@Observed and \@ObjectLink Decorators: Observing Attribute Changes in Nested Class Objects](quick-start/arkts-observed-and-objectlink.md) - Application State Management - [Application State Management Overview](quick-start/arkts-application-state-management-overview.md) - [LocalStorage: UI State Storage](quick-start/arkts-localstorage.md) @@ -67,7 +67,7 @@ - [Environment: Device Environment Query](quick-start/arkts-environment.md) - Other State Management Features - [Overview of Other State Management Features](quick-start/arkts-other-state-mgmt-functions-overview.md) - - [\@Watch: Getting Notified of State Variable Changes](quick-start/arkts-watch.md) + - [\@Watch Decorator: Getting Notified of State Variable Changes](quick-start/arkts-watch.md) - [$$ Syntax: Two-Way Synchronization of Built-in Components](quick-start/arkts-two-way-sync.md) - Rendering Control - [Overview of Rendering Control](quick-start/arkts-rendering-control-overview.md) @@ -106,12 +106,12 @@ - [SystemCapability List](reference/syscap-list.md) - [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md) - [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md) - - [JS Service Widget UI Components](reference/js-service-widget-ui/Readme-EN.md) - - APIs - - [ArkTS and JS APIs](reference/apis/Readme-EN.md) + - [JavaScript Service Widget UI Component Reference](reference/js-service-widget-ui/Readme-EN.md) + - API Reference + - [ArkTS and JavaScript APIs](reference/apis/Readme-EN.md) - [Error Codes](reference/errorcodes/Readme-EN.md) - - Native APIs - - [Native API Reference](reference/native-apis/Readme-EN.md) + - Native API Reference + - [Native APIs](reference/native-apis/Readme-EN.md) - [Standard Libraries](reference/native-lib/third_party_libc/musl.md) - [Node_API](reference/native-lib/third_party_napi/napi.md) - [FAQs](faqs/Readme-EN.md) diff --git a/en/application-dev/application-dev-guide-for-gitee.md b/en/application-dev/application-dev-guide-for-gitee.md index 1ad5989d2cf8258c46e219a239a2c8c5a1d1274c..f14f378053912496f84e4b34e9436d26f77f75eb 100644 --- a/en/application-dev/application-dev-guide-for-gitee.md +++ b/en/application-dev/application-dev-guide-for-gitee.md @@ -6,7 +6,7 @@ The documents are carefully organized as follows: ### Getting Started -[Here](quick-start/Readme-EN.md) you'll learn how to quickly get started with OpenHarmony application development. +[Here](quick-start/Readme-EN.md) you can learn how to better prepare yourself for application development. Browse the documents on the instructions for quickly building your first application and the basics about OpenHarmony applications. @@ -51,7 +51,7 @@ DevEco Studio is a high-performance integrated development environment (IDE) rec ### Hands-On Tutorials -To make you better understand how functions work together and jumpstart your application development projects, we provide stripped-down, real-world [samples](https://gitee.com/openharmony/applications_app_samples/blob/master/README.md) and [codelabs](https://gitee.com/openharmony/codelabs). +To make you better understand how functions work together and jumpstart your application development projects, we provide stripped-down, real-world [samples](https://gitee.com/openharmony/applications_app_samples/blob/master/README.md). ### API References @@ -61,16 +61,15 @@ They are organized as follows: - [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md) - [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md) -- [JS Service Widget UI Components](reference/js-service-widget-ui/Readme-EN.md) -- APIs - - [JS and TS APIs](reference/apis/Readme-EN.md) - - Native APIs - - [Standard Library](reference/native-lib/third_party_libc/musl.md) +- [JavaScript Service Widget UI Component Reference](reference/js-service-widget-ui/Readme-EN.md) +- API Reference + - [ArkTS and JavaScript APIs](reference/apis/Readme-EN.md) + - Native API Reference + - [Native APIs](reference/native-apis/Readme-EN.md) + - [Standard Libraries](reference/native-lib/third_party_libc/musl.md) - [Node_API](reference/native-lib/third_party_napi/napi.md) ### Readme For details about the principles and basic information of each subsystem, see the README file in [docs/en/readme](../readme). - - \ No newline at end of file diff --git a/en/application-dev/application-dev-guide.md b/en/application-dev/application-dev-guide.md index 8170d075cf08e8258b7c8b3731661f0e4959c6aa..bd8fab6646a66110314fb89cbf41ad833a378746 100644 --- a/en/application-dev/application-dev-guide.md +++ b/en/application-dev/application-dev-guide.md @@ -6,7 +6,7 @@ The documents are carefully organized as follows: ## Getting Started -[Here](quick-start/start-overview.md) you'll learn how to quickly get started with OpenHarmony application development. +[Here](quick-start/start-overview.md) you can learn how to better prepare yourself for application development. Browse the documents on the instructions for quickly building your first application and the basics about OpenHarmony applications. @@ -36,12 +36,12 @@ Then, equip yourself for developing the key features, with the following guideli - [Data Management](database/data-mgmt-overview.md) - [File Management](file-management/file-management-overview.md) - [Task Management](task-management/background-task-overview.md) -- [Device](device/usb-overview.md) +- [Device Management](device/usb-overview.md) - [Device Usage Statistics](device-usage-statistics/device-usage-statistics-overview.md) - [DFX](dfx/hiappevent-guidelines.md) - [Internationalization](internationalization/international-overview.md) - [Application Test](application-test/arkxtest-guidelines.md) -- [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md) +- [IDL Specifications and User Guide](IDL/idl-guidelines.md) - [Using Native APIs in Application Projects](napi/napi-guidelines.md) ## Tools @@ -51,7 +51,7 @@ DevEco Studio is a high-performance integrated development environment (IDE) rec ## Hands-On Tutorials -To make you better understand how functions work together and jumpstart your application development projects, we provide stripped-down, real-world [samples](https://gitee.com/openharmony/applications_app_samples/blob/master/README.md) and [codelabs](https://gitee.com/openharmony/codelabs). +To make you better understand how functions work together and jumpstart your application development projects, we provide stripped-down, real-world [samples](https://gitee.com/openharmony/applications_app_samples/blob/master/README.md). ## API References @@ -59,13 +59,12 @@ API references encompass all components and APIs available in OpenHarmony, helpi They are organized as follows: +- [ArkTS API Reference](reference/apis/development-intro.md) - [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/ts-components-summary.md) - [Component Reference (JavaScript-compatible Web-like Development Paradigm-ArkUI.Full)](reference/arkui-js/js-components-common-attributes.md) - [Component Reference (JavaScript-compatible Web-like Development Paradigm-ArkUI.Lite)](reference/arkui-js-lite/js-framework-file.md) -- [JS Service Widget UI Components](reference/js-service-widget-ui/js-service-widget-file.md) -- [JS and TS APIs](reference/apis/development-intro.md) -- Native APIs - - [Standard Library](reference/native-lib/third_party_libc/musl.md) +- [JavaScript Service Widget UI Component Reference](reference/js-service-widget-ui/js-service-widget-file.md) +- Native API Reference + - [Native APIs](reference/native-apis/_o_h___native_x_component.md) + - [Standard Libraries](reference/native-lib/third_party_libc/musl.md) - [Node_API](reference/native-lib/third_party_napi/napi.md) - - \ No newline at end of file diff --git a/en/application-dev/application-models/application-context-stage.md b/en/application-dev/application-models/application-context-stage.md index 8c26d7fbb70a19db0ab07ada99f4df8cc0b290df..17fe99577ab5cd782bcd4154274555bb8064da24 100644 --- a/en/application-dev/application-models/application-context-stage.md +++ b/en/application-dev/application-models/application-context-stage.md @@ -86,13 +86,13 @@ The application file paths obtained by the preceding contexts are different. | Name| Path| | -------- | -------- | - | bundleCodeDir | /el1/bundle/| - | cacheDir | //base/cache/| - | filesDir | //base/files/| - | preferencesDir | //base/preferences/| - | tempDir | //base/temp/| - | databaseDir | //database/| - | distributedFilesDir | /el2/distributedFiles/| + | bundleCodeDir | \/el1/bundle/| + | cacheDir | \/\/base/cache/| + | filesDir | \/\/base/files/| + | preferencesDir | \/\/base/preferences/| + | tempDir | \/\/base/temp/| + | databaseDir | \/\/database/| + | distributedFilesDir | \/el2/distributedFiles/| The sample code is as follows: @@ -118,13 +118,13 @@ The application file paths obtained by the preceding contexts are different. | Name| Path| | -------- | -------- | - | bundleCodeDir | /el1/bundle/| - | cacheDir | //base/**haps/\**/cache/| - | filesDir | //base/**haps/\**/files/| - | preferencesDir | //base/**haps/\**/preferences/| - | tempDir | //base/**haps/\**/temp/| - | databaseDir | //database/**\**/| - | distributedFilesDir | /el2/distributedFiles/**\**/| + | bundleCodeDir | \/el1/bundle/| + | cacheDir | \/\/base/**haps/\**/cache/| + | filesDir | \/\/base/**haps/\**/files/| + | preferencesDir | \/\/base/**haps/\**/preferences/| + | tempDir | \/\/base/**haps/\**/temp/| + | databaseDir | \/\/database/**\**/| + | distributedFilesDir | \/el2/distributedFiles/**\**/| The sample code is as follows: diff --git a/en/application-dev/application-models/arkts-ui-widget-event-overview.md b/en/application-dev/application-models/arkts-ui-widget-event-overview.md index ed029fc3017d00a7d4c2cf14e1b905139bd7eb49..299a279c9117dad71e6fea658bb8da3298ed8f05 100644 --- a/en/application-dev/application-models/arkts-ui-widget-event-overview.md +++ b/en/application-dev/application-models/arkts-ui-widget-event-overview.md @@ -1,6 +1,6 @@ # Widget Event Capability Overview -The ArkTS widget provides the **postCardAction()** API for interaction between the widget internal and the provider application. Currently, this API supports the router, message, and call events and can be called only in the widget. +The ArkTS widget provides the **postCardAction()** API for interaction between the widget internal and the widget provider. Currently, this API supports the router, message, and call events and can be called only in the widget. ![WidgetPostCardAction](figures/WidgetPostCardAction.png) @@ -8,26 +8,28 @@ The ArkTS widget provides the **postCardAction()** API for interaction between t **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| component | Object | Yes| Instance of the current custom component. Generally, **this** is transferred.| +| component | Object | Yes| Instance of the current custom component. Generally, **this** is passed in.| | action | Object | Yes| Action description. For details, see the following table.| **Description of the action parameter** + | Key | Value | Description| | -------- | -------- | -------- | -| "action" | string | Action type.
- **"router"**: redirection to the specified UIAbility of the widget provider.
- **"message"**: custom message. If this type of action is triggered, the [onFormEvent()](../reference/apis/js-apis-app-form-formExtensionAbility.md#onformevent) lifecycle callback of the provider FormExtensionAbility is called.
- **"call"**: launch of the widget provider in the background. If this type of action is triggered, the specified UIAbility of the widget provider is started in the background, but not displayed in the foreground. This action type requires that the widget provider should have the [ohos.permission.KEEP_BACKGROUND_RUNNING](../security/permission-list.md#ohospermissionkeep_background_running) permission.| +| "action" | string | Action type.
- **"router"**: redirection to the specified UIAbility of the widget provider.
- **"message"**: custom message. If this type of action is triggered, the [onFormEvent()](../reference/apis/js-apis-app-form-formExtensionAbility.md#onformevent) lifecycle callback of the provider FormExtensionAbility is called.
- **"call"**: launch of the widget provider in the background. If this type of action is triggered, the specified UIAbility (whose [launch type](uiability-launch-type.md) must be singleton) of the widget provider is started in the background, but not displayed in the foreground. This action type requires that the widget provider should have the [ohos.permission.KEEP_BACKGROUND_RUNNING](../security/permission-list.md#ohospermissionkeep_background_running) permission.| | "bundleName" | string | Name of the target bundle when **action** is **"router"** or **"call"**. This parameter is optional.| | "moduleName" | string | Name of the target module when **action** is **"router"** or **"call"**. This parameter is optional.| | "abilityName" | string | Name of the target UIAbility when **action** is **"router"** or **"call"**. This parameter is mandatory.| -| "params" | Object | Additional parameters carried in the current action. The value is a key-value pair in JSON format. For the **"call"** action type, the **method** parameter must be set and its value type must be string. This parameter is mandatory.| +| "params" | Object | Additional parameters carried in the current action. The value is a key-value pair in JSON format. For the **"call"** action type, the **method** parameter (mandatory) must be set and its value type must be string.| Sample code of the **postCardAction()** API: ```typescript -Button ('Jump') +Button ('Redirect') .width('40%') .height('20%') .onClick(() => { @@ -51,7 +53,7 @@ Button ('Start in Background') 'abilityName': 'EntryAbility', 'params': { 'method': 'fun', // Set the name of the method to call. It is mandatory. - 'message': 'testForcall' // Customize the message to send. + 'message': 'testForCall' // Customize the message to send. } }); }) diff --git a/en/application-dev/application-models/arkts-ui-widget-event-uiability.md b/en/application-dev/application-models/arkts-ui-widget-event-uiability.md index 392bdced7592e74f94eb2bf7d3445f5fa686a506..17a211188704609e5bc60dcbcf6b058a8a8a0dbe 100644 --- a/en/application-dev/application-models/arkts-ui-widget-event-uiability.md +++ b/en/application-dev/application-models/arkts-ui-widget-event-uiability.md @@ -16,7 +16,7 @@ On the widget page, the **postCardAction** API can be used to trigger a router o build() { Column() { - Button ('Jump') + Button ('Redirect') .margin('20%') .onClick(() => { console.info('postCardAction to EntryAbility'); diff --git a/en/application-dev/application-models/atomic-services-support-sharing.md b/en/application-dev/application-models/atomic-services-support-sharing.md index 99feea4719836f576762c3a43b0323c6bf2388cc..ba99573b28c4e25ef5ed2c8ca472e559a00f4713 100644 --- a/en/application-dev/application-models/atomic-services-support-sharing.md +++ b/en/application-dev/application-models/atomic-services-support-sharing.md @@ -1,27 +1,21 @@ # Setting Atomic Services to Support Sharing -By means of sharing, users can quickly access atomic services and use their features. - ## How to Develop -In the sharing scenario, there are two parties involved: a target application that shares data and an application that obtains the shared data. The two can be physically the same. The target application uses the **onShare()** lifecycle callback to set the data to share. After the target application is started, you can run the **hdc shell aa dump -a** command to check the started services and processes and find its mission ID. After the current application is started, call the **abilityManager.acquireShareData()** API with the mission ID passed in to obtain the shared data. -> **NOTE** -> -> The mission ID of the target application can also be obtained by calling [missionManager.getMissionInfos()](../reference/apis/js-apis-app-ability-missionManager.md#getmissioninfos). -1. The target application calls **UIAbility.onShare()** provided by the UIAbility component to set the data to share. **ohos.extra.param.key.contentTitle** indicates the title of the content to share in the sharing box, **ohos.extra.param.key.shareAbstract** provides an abstract description of the content, and **ohos.extra.param.key.shareUrl** indicates the online address of the service. You need to set these three items as objects, with the key set to **title**, **abstract**, and **url**, respectively. +1. An application calls [UIAbility.onShare()](../reference/apis/js-apis-app-ability-uiAbility.md#onshare), a lifecycle callback provided by the UIAbility component, to set the data to share. In this lifecycle callback, **ohos.extra.param.key.contentTitle** indicates the title of the content to share in the sharing box, **ohos.extra.param.key.shareAbstract** provides an abstract description of the content, and **ohos.extra.param.key.shareUrl** indicates the online address of the service. You need to set these three items as objects, with the key set to **title**, **abstract**, and **url**, respectively. ```ts import AbilityConstant from '@ohos.app.ability.AbilityConstant'; class MyUIAbility extends UIAbility { onShare(wantParams) { console.log('onShare'); - wantParams['ohos.extra.param.key.contentTitle'] = {title: "W3"}; - wantParams['ohos.extra.param.key.shareAbstract'] = {abstract: "communication for huawei employee"}; - wantParams['ohos.extra.param.key.shareUrl'] = {url: "w3.huawei.com"}; + wantParams['ohos.extra.param.key.contentTitle'] = {title: "OA"}; + wantParams['ohos.extra.param.key.shareAbstract'] = {abstract: "communication for company employee"}; + wantParams['ohos.extra.param.key.shareUrl'] = {url: "oa.example.com"}; } } ``` -2. The current application calls **abilityManager.acquireShareData()** to obtain the data shared by the target application. **missionId** indicates the target application's mission ID, which can be obtained by running the **hdc shell aa dump -a** command or calling the **missionManager.getMissionInfos()** API after the target application is started. **wantParam** indicates the data shared by the target application through the **UIAbility.onShare()** lifecycle callback. +2. A system dialog box calls [abilityManager.acquireShareData()](../reference/apis/js-apis-app-ability-abilityManager.md#acquiresharedata) to obtain data shared through atomic service sharing. Specifically, the system finds the UIAbility based on the mission ID and calls the **OnShare()** lifecycle of the UIAbility to obtain the shared data. ```ts import abilityManager from '@ohos.app.ability.abilityManager'; diff --git a/en/application-dev/application-models/common-event-static-subscription.md b/en/application-dev/application-models/common-event-static-subscription.md index 7005c86ae2e29eb7c635f55b5da05f658ccd8360..465fc236129d4c78967e6122c318132933043fb6 100644 --- a/en/application-dev/application-models/common-event-static-subscription.md +++ b/en/application-dev/application-models/common-event-static-subscription.md @@ -2,9 +2,7 @@ ## When to Use -A static subscriber is started once it receives a target event published by the system or application. At the same time, the [onReceiveEvent()](../reference/apis/js-apis-application-staticSubscriberExtensionAbility.md#staticsubscriberextensionabilityonreceiveevent) callback is triggered. - -You can implement the service logic in the [onReceiveEvent()](../reference/apis/js-apis-application-staticSubscriberExtensionAbility.md#staticsubscriberextensionabilityonreceiveevent) callback. For example, if an application needs to execute some initialization tasks during device power-on, the application can subscribe to the power-on event in static mode. After receiving the power-on event, the application is started to execute the initialization tasks. +A static subscriber is started once it receives a target event published by the system or application. At the same time, the [onReceiveEvent()](../reference/apis/js-apis-application-staticSubscriberExtensionAbility.md#staticsubscriberextensionabilityonreceiveevent) callback is triggered, in which you can implement the service logic. For example, if an application needs to execute some initialization tasks during device power-on, the application can subscribe to the power-on event in static mode. After receiving the power-on event, the application is started to execute the initialization tasks. Subscribing to a common event in static mode is achieved by configuring a declaration file and implementing a class that inherits from [StaticSubscriberExtensionAbility](../reference/apis/js-apis-application-staticSubscriberExtensionAbility.md). @@ -18,7 +16,7 @@ Subscribing to a common event in static mode is achieved by configuring a declar To declare a static subscriber, create an ExtensionAbility, which is derived from the **StaticSubscriberExtensionAbility** class, in the project. - You can implement service logic in the **onReceiveEvent()** callback. + You can implement service logic in the [**onReceiveEvent()**](../reference/apis/js-apis-application-staticSubscriberExtensionAbility.md#staticsubscriberextensionabilityonreceiveevent) callback. ```ts import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility' @@ -93,23 +91,24 @@ Subscribing to a common event in static mode is achieved by configuring a declar - **permission**: permission required for the publisher. If a publisher without the required permission attempts to publish an event, the event is regarded as invalid and will not be published. - **events**: list of target events to subscribe to. -4. Modify the [preset configuration file](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list_permissions.json) of the device, that is, the **/system/etc/app/install_list_permission.json** file on the device. When the device is started, this file is read. During application installation, the common event type specified by **allowCommonEvent** in the file is authorized. The **install_list_permission.json** file contains the following fields: +4. Modify the [preset configuration file](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list_capability.json) of the device, that is, the **/system/etc/app/install_list_capability.json** file on the device. When the device is started, this file is read. During application installation, the common event type specified by **allowCommonEvent** in the file is authorized. The **install_list_capability.json** file contains the following fields: - **bundleName**: bundle name of the application. - - **app_signature**: fingerprint information of the application. For details, see [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md#configuration-in-install_list_capabilityjson). + - **app_signature**: fingerprint information of the application. For details, see [Configuration in install_list_capability.json](../../device-dev/subsystems/subsys-app-privilege-config-guide.md#configuration-in-install_list_capabilityjson). - **allowCommonEvent**: type of common event that can be started by static broadcast. - > **NOTE** - > - > The **install_list_permissions.json** file is available only for preinstalled applications. - ```json [ + ... { - "bundleName": "com.example.myapplication", - "app_signature": ["****"], - "allowCommonEvent": ["usual.event.A", "usual.event.B"] + "bundleName": "com.example.myapplication", // Bundle name. + "app_signature": ["****"], // Fingerprint information. + "allowCommonEvent": ["usual.event.A", "usual.event.B"] // Type of common event that can be started by static broadcast. } ] ``` + + > **NOTE** + > + > The **install_list_capability.json** file is available only for preinstalled applications. diff --git a/en/application-dev/application-models/create-dataability.md b/en/application-dev/application-models/create-dataability.md index f7eceab4da4711b15bd94bb0d61ef99c62521286..9d148a7ba28ffe46484f32b07f7a7660ef49f72d 100644 --- a/en/application-dev/application-models/create-dataability.md +++ b/en/application-dev/application-models/create-dataability.md @@ -12,7 +12,7 @@ import dataAbility from '@ohos.data.dataAbility' import relationalStore from '@ohos.data.relationalStore' const TABLE_NAME = 'book' -const STORE_CONFIG = { name: 'book.db' } +const STORE_CONFIG = { name: 'book.db',securityLevel: 1 } const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS book(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, introduction TEXT NOT NULL)' let rdbStore: relationalStore.RdbStore = undefined diff --git a/en/application-dev/application-models/explicit-implicit-want-mappings.md b/en/application-dev/application-models/explicit-implicit-want-mappings.md index 454fc89d718fb4adfe84c0eab67ebc332117ed26..32482e090b41fa9497a8f385e2126e5b7152287b 100644 --- a/en/application-dev/application-models/explicit-implicit-want-mappings.md +++ b/en/application-dev/application-models/explicit-implicit-want-mappings.md @@ -63,8 +63,7 @@ The system matches the **action** attribute in the **want** parameter passed by - If **action** in the passed **want** parameter is specified, and **actions** under **skills** of an application component is specified but does not contain **action** in the passed **want** parameter, the matching fails. **Figure 1** Matching rules of action in the want parameter - - ![want-action](figures/want-action.png) +![want-action](figures/want-action.png) ### Matching Rules of entities in the want Parameter @@ -82,8 +81,7 @@ The system matches the **entities** attribute in the **want** parameter passed b - If **entities** in the passed **want** parameter is specified, and **entities** under **skills** of an application component is specified but does not contain **entities** in the passed **want** parameter, the matching fails. **Figure 2** Matching rules of entities in the want parameter - - ![want-entities](figures/want-entities.png) +![want-entities](figures/want-entities.png) ### Matching Rules of uri and type in the want Parameter @@ -100,6 +98,7 @@ There are four combinations of **uri** and **type** settings. The matching rules - Only **uri** is specified in the **want** parameter. - If the **uris** array under **skills** of an application component is unspecified, the matching fails. - If the **uris** array under **skills** of an application component contains an element whose [uri is matched](#matching-rules-of-uri) and **type** is unspecified, the matching is successful. Otherwise, the matching fails. + - If the matching fails for the preceding two scenarios and the input URI is a file path URI, the system obtains the MIME type of the file based on the file name extension. If the MIME type matches **type** configured under **skills**, the matching is successful. - Only **type** is specified in the **want** parameter. - If the **uris** array under **skills** of an application component is unspecified, the matching fails. @@ -112,8 +111,7 @@ There are four combinations of **uri** and **type** settings. The matching rules Leftmost URI matching: When only **scheme**, a combination of **scheme** and **host**, or a combination of **scheme**, **host**, and **port** is configured in the **uris** array under **skills** of the application component, the matching is successful only if the leftmost URI in the passed **want** parameter matches **scheme**, the combination of **scheme** and **host**, or the combination of **scheme**, **host**, and **port**. **Figure 3** Matching rules when uri and type are specified in the want parameter - -![want-uri-type1](figures/want-uri-type1.png) +![want-uri-type1](figures/want-uri-type1.png) To simplify the description: @@ -121,8 +119,7 @@ To simplify the description: - **type** in the **want** parameter passed in by the caller is called **w_type**; the type in the **uris** array under **skills** of the application component to match is called **s_type**. **Figure 4** Matching rules of uri and type in the want parameter - -![want-uri-type2](figures/want-uri-type2.png) +![want-uri-type2](figures/want-uri-type2.png) ### Matching Rules of uri diff --git a/en/application-dev/application-models/serviceextensionability.md b/en/application-dev/application-models/serviceextensionability.md index 08ce2d0a0490402494a0a8b5ee09f71f63712efe..b55c7830b5460d9fe93eb2c511079ab27f3b7e19 100644 --- a/en/application-dev/application-models/serviceextensionability.md +++ b/en/application-dev/application-models/serviceextensionability.md @@ -2,7 +2,7 @@ ## Overview -[ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) is an ExtensionAbility component of the service type that provides capabilities related to background services. It holds an internal [ServiceExtensionContext](../reference/apis/js-apis-inner-application-serviceExtensionContext.md), which provides a variety of APIs are provided for external systems. +[ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) is an ExtensionAbility component of the service type that provides capabilities related to background services. It holds an internal [ServiceExtensionContext](../reference/apis/js-apis-inner-application-serviceExtensionContext.md), which provides a variety of APIs for external systems. In this document, the started ServiceExtensionAbility is called the server, and the component that starts the ServiceExtensionAbility is called the client. @@ -28,7 +28,7 @@ Note the following: ## Lifecycle -The [ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) class provides the lifecycle callbacks **onCreate()**, **onRequest()**, **onConnect()**, **onDisconnect()**, and **onDestory()**. Override them as required. The following figure shows the ServiceExtensionAbility lifecycle. +The [ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) class provides the lifecycle callbacks **onCreate()**, **onRequest()**, **onConnect()**, **onDisconnect()**, and **onDestroy()**. Override them as required. The following figure shows the ServiceExtensionAbility lifecycle. **Figure 1** ServiceExtensionAbility lifecycle ![ServiceExtensionAbility-lifecycle](figures/ServiceExtensionAbility-lifecycle.png) @@ -249,7 +249,6 @@ A system application uses the [startServiceExtensionAbility()](../reference/apis > > - The background service calls the [terminateSelf()](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself) method to automatically stop itself. > - Another component calls the [stopServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstopserviceextensionability) method to stop the background service. -> ## Connecting to a Background Service @@ -382,7 +381,7 @@ When a ServiceExtensionAbility is used to provide sensitive services, the client - **Verifying the client identity based on callerUid** - Call the [getCallingUid()](../reference/apis/js-apis-rpc.md#getcallinguid) method to obtain the UID of the client, and then call the [getBundleNameByUid()](../reference/apis/js-apis-bundleManager.md#bundlemanagergetbundlenamebyuid) method to obtain the corresponding bundle name. In this way, the client identify is verified. Note that [getBundleNameByUid()](../reference/apis/js-apis-bundleManager.md#bundlemanagergetbundlenamebyuid) is asynchronous, and therefore the server cannot return the verification result to the client. This verification mode applies when the client sends an asynchronous task request to the server. The sample code is as follows: + Call the [getCallingUid()](../reference/apis/js-apis-rpc.md#getcallinguid) method to obtain the UID of the client, and then call the [getBundleNameByUid()](../reference/apis/js-apis-bundleManager.md#bundlemanagergetbundlenamebyuid) method to obtain the corresponding bundle name. In this way, the client identity is verified. Note that [getBundleNameByUid()](../reference/apis/js-apis-bundleManager.md#bundlemanagergetbundlenamebyuid) is asynchronous, and therefore the server cannot return the verification result to the client. This verification mode applies when the client sends an asynchronous task request to the server. The sample code is as follows: ```ts import rpc from '@ohos.rpc'; diff --git a/en/application-dev/device/vibrator-guidelines.md b/en/application-dev/device/vibrator-guidelines.md index c028f5be4890c476bab762cfc8b0f0d12d9fdda8..cfa6e7cd1d26d5781a850384aa4be148ebb247e2 100644 --- a/en/application-dev/device/vibrator-guidelines.md +++ b/en/application-dev/device/vibrator-guidelines.md @@ -18,8 +18,85 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md | ohos.vibrator | stopVibration(stopMode: VibratorStopMode, callback: AsyncCallback<void>): void | Stops vibration in the specified mode. This API uses an asynchronous callback to return the result. | | ohos.vibrator | stopVibration(): Promise<void> | Stops vibration in all modes. This API uses a promise to return the result. | | ohos.vibrator | stopVibration(callback: AsyncCallback<void>): void | Stops vibration in all modes. This API uses an asynchronous callback to return the result. | -| ohos.vibrator | isSupportEffect(effectId: string): Promise<boolean> | Checks whether the passed effect ID is supported. This API uses a promise to return the result. The value **true** means that the passed effect ID is supported, and **false** means the opposite. | -| ohos.vibrator | isSupportEffect(effectId: string, callback: AsyncCallback<boolean>): void | Checks whether the passed effect ID is supported. This API uses an asynchronous callback to return the result. The value **true** means that the passed effect ID is supported, and **false** means the opposite. | +| ohos.vibrator | isSupportEffect(effectId: string): Promise<boolean> | Checks whether the passed effect ID is supported. This API uses a promise to return the result. The value **true** means that the passed effect ID is supported, and **false** means the opposite.| +| ohos.vibrator | isSupportEffect(effectId: string, callback: AsyncCallback<boolean>): void | Checks whether the passed effect ID is supported. This API uses an asynchronous callback to return the result. The value **true** means that the passed effect ID is supported, and **false** means the opposite.| + + +## Custom Vibration Format + +Custom vibration enables you to design desired vibration effects by customizing a vibration configuration file and orchestrating vibration forms based on the corresponding rules. + +The custom vibration configuration file is in JSON format. An example file is as follows: + +```json +{ + "MetaData": { + "Create": "2023-01-09", + "Description": "a haptic case", + "Version": 1.0, + "ChannelNumber": 1 + }, + "Channels": [ + { + "Parameters": { + "Index": 1 + }, + "Pattern": [ + { + "Event": { + "Type": "transient", + "StartTime": 0, + "Parameters": { + "Intensity": 100, + "Frequency": 31 + } + } + }, + { + "Event": { + "Type": "continuous", + "StartTime": 100, + "Duration": 54, + "Parameters": { + "Intensity": 38, + "Frequency": 30 + } + } + } + ] + } + ] +} +``` + +This JSON file contains two attributes: **MetaData** and **Channels**. +- **MetaData** contains information about the file header. You can add the following attributes under **MetaData**: + - **Version**: version number of the file format, which is forward compatible. Currently, only version 1.0 is supported. This parameter is mandatory. + - **ChannelNumber**: number of channels for vibration. Currently, only one channel is supported, and the value is fixed at **1**. This parameter is mandatory. + - **Create**: time when the file was created. This parameter is optional. + - **Description**: additional information such as the vibration effect and creation information. This parameter is optional. +- **Channels** provides information about the vibration channel. It is a JSON array that holds information about each channel. It contains two attributes: **Parameters** and **Pattern**. +- **Parameters** provides parameters related to the channel. Under it, **Index** indicates the channel ID. The value is fixed at **1** for a single channel. This parameter is mandatory. + - **Pattern** indicates the vibration sequence. It is a JSON array. Under it, **Event** indicates a vibration event, which can be either of the following types: + - **transient**: short vibration + - **continuous**: long vibration + +The table below describes the parameters under **Event**. + +| Parameter| Description| Value or Value Range| +| --- | ------------------------ | ---| +| Type | Type of the vibration event. This parameter is mandatory.| **transient** or **continuous**| +| StartTime | Start time of the vibration. This parameter is mandatory.| [0, 1800 000], in ms, without overlapping| +| Duration | Duration of the vibration. This parameter is valid only when **Type** is **continuous**.| (10, 1600), in ms| +| Intensity | Intensity of the vibration. This parameter is mandatory.| [0, 100], a relative value that does not represent the actual vibration strength.| +| Frequency | Frequency of the vibration. This parameter is mandatory.| [0, 100], a relative value that does not represent the actual vibration frequency| + +The following requirements must be met: + +| Item| Description | +| -------- | ------------------------ | +| Number of vibration events| No more than 128| +| Length of the vibration configuration file| Not greater than 64 KB| ## How to Develop @@ -54,19 +131,19 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md ```js import vibrator from '@ohos.vibrator'; try { - // Stop vibration in VIBRATOR_STOP_MODE_TIME mode. To use stopVibration, you must configure the ohos.permission.VIBRATE permission. - vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, function (error) { - if (error) { - console.log('error.code' + error.code + 'error.message' + error.message); - return; - } - console.log('Callback returned to indicate successful.'); - }) + // Stop vibration in VIBRATOR_STOP_MODE_TIME mode. To use stopVibration, you must configure the ohos.permission.VIBRATE permission. + vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, function (error) { + if (error) { + console.log('error.code' + error.code + 'error.message' + error.message); + return; + } + console.log('Callback returned to indicate successful.'); + }) } catch (err) { - console.info('errCode: ' + err.code + ' ,msg: ' + err.message); + console.info('errCode: ' + err.code + ' ,msg: ' + err.message); } ``` - + 4. Stop vibration in all modes. ```js @@ -135,3 +212,63 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md console.error('Exception in, error:' + JSON.stringify(error)); } ``` + +6. Start and stop custom vibration. + + ```js + import vibrator from '@ohos.vibrator'; + import resourceManager from '@ohos.resourceManager'; + + const FILE_NAME = "xxx.json"; + + async function openResource(fileName) { + let fileDescriptor = undefined; + let mgr = await resourceManager.getResourceManager(); + await mgr.getRawFd(fileName).then(value => { + fileDescriptor = {fd: value.fd, offset: value.offset, length: value.length}; + console.log('openResource success fileName: ' + fileName); + }).catch(error => { + console.log('openResource err: ' + error); + }); + return fileDescriptor; + } + + async function closeResource(fileName) { + let mgr = await resourceManager.getResourceManager(); + await mgr.closeRawFd(fileName).then(()=> { + console.log('closeResource success fileName: ' + fileName); + }).catch(error => { + console.log('closeResource err: ' + error); + }); + } + + // Obtain the file descriptor of the vibration configuration file. + let rawFd = openResource(FILE_NAME); + // To use startVibration and stopVibration, you must configure the ohos.permission.VIBRATE permission. + try { + // Start custom vibration. + vibrator.startVibration({ + type: "file", + hapticFd: { fd: rawFd.fd, offset: rawFd.offset, length: rawFd.length } + }, { + usage: "alarm" + }).then(() => { + console.info('startVibration success'); + }, (error) => { + console.info('startVibration error'); + }); + // Stop vibration in all modes. + vibrator.stopVibration(function (error) { + if (error) { + console.log('error.code' + error.code + 'error.message' + error.message); + return; + } + console.log('Callback returned to indicate successful.'); + }) + } catch (error) { + console.info('errCode: ' + error.code + ' ,msg: ' + error.message); + } + // Close the vibration configuration file. + closeResource(FILE_NAME); + ``` + diff --git a/en/application-dev/dfx/hilog-guidelines.md b/en/application-dev/dfx/hilog-guidelines.md index a399a520ba96aa3a64eea8968ed359c05da5440b..25b4a7f9cc5c92d9f20ed6582299d5dd65b937d0 100644 --- a/en/application-dev/dfx/hilog-guidelines.md +++ b/en/application-dev/dfx/hilog-guidelines.md @@ -38,7 +38,7 @@ Log level. | Name | Value | Description | | ----- | ------ | ------------------------------------------------------------ | | DEBUG | 3 | Log level used to record more detailed process information than INFO logs to help developers analyze service processes and locate faults.| -| INFO | 4 | Log level used to record key service process nodes and exceptions that occur during service running,
Log level used to record information about unexpected exceptions, such as network signal loss and login failure.
These logs should be recorded by the dominant module in the service to avoid repeated logging conducted by multiple invoked modules or low-level functions.| +| INFO | 4 | Log level used to record key service process nodes and exceptions that occur during service running as well as information about unexpected exceptions, such as network signal loss and login failure.
These logs should be recorded by the dominant module in the service to avoid repeated logging conducted by multiple invoked modules or low-level functions.| | WARN | 5 | Log level used to record severe, unexpected faults that have little impact on users and can be rectified by the programs themselves or through simple operations.| | ERROR | 6 | Log level used to record program or functional errors that affect the normal running or use of the functionality and can be fixed at a high cost, for example, by resetting data.| | FATAL | 7 | Log level used to record program or functionality crashes that cannot be rectified. diff --git a/en/application-dev/file-management/app-sandbox-directory.md b/en/application-dev/file-management/app-sandbox-directory.md index 2da514469b80369d2660d14a0fd715e282e57adf..f9cfb0317c29bff58664ed894f585a5127943fa5 100644 --- a/en/application-dev/file-management/app-sandbox-directory.md +++ b/en/application-dev/file-management/app-sandbox-directory.md @@ -47,12 +47,12 @@ The following figure shows the application file directories. The path of a file 3. Level 3 directories **el1/** and **el2/**: indicate directories for files of different encryption levels (els). - **el1**: directory for the data that can be accessed once the device starts. This directory contains device-focused files. - **el2**: directory for the data that can be accessed only after at lease one successful unlocking operation (by PIN, fingerprint, or facial authentication, or password-free sign-in) upon the start of the device. This directory contains user-focused files.
- Unless otherwise required, application data is placed in the **el2** directory for security purposes. However, the data that needs to be accessed before the screen is unlocked (such as the clock, alarm, and wallpaper data) can be placed in the **el1** directory. For details about how to switch to and modify the **el** directories, see [Obtaining and Modifying el Directories](../application-models/application-context-stage.md#obtaining-and-modifying-encryption-areas). + Unless otherwise required, application data is placed in the **el2** directory for security purposes. However, the data that needs to be accessed before the screen is unlocked (such as the clock, alarm, and wallpaper data) can be placed in the **el1** directory. For details about how to switch to and modify the **el** directories, see [Obtaining and Modifying el Directories](../application-models/application-context-stage.md#obtaining-and-modifying-encryption-levels). 4. Level 4 and level 5 directories: The application's global data is stored in the **files**, **cache**, **preferences**, **temp**, and **distributedfiles** folders in **base**. You can use **ApplicationContext** to obtain the application file paths of these folders. - You can use **UIAbilityContext**, **AbilityStageContext**, and **ExtensionContext** to obtain application file paths related to the OpenHarmoy Ability Package (HAP). When the HAP is uninstalled, the files stored in these directories are automatically deleted, without affecting the files in app-level directories. An application in the development state contains one or more HAPs. For details, see [Application Package Structure in Stage Mode](../quick-start/application-package-structure-stage.md). + You can use **UIAbilityContext**, **AbilityStageContext**, and **ExtensionContext** to obtain application file paths related to the OpenHarmony Ability Package (HAP). When the HAP is uninstalled, the files stored in these directories are automatically deleted, without affecting the files in app-level directories. An application in the development state contains one or more HAPs. For details, see [Application Package Structure in Stage Mode](../quick-start/application-package-structure-stage.md). For details about how to obtain the context and application file paths, see [Context (Stage Model)](../application-models/application-context-stage.md). diff --git a/en/application-dev/media/camera-device-input.md b/en/application-dev/media/camera-device-input.md index 3702e16760c002010c50da236d4ef9c2af079e5e..2d9acf3df47fe1926f6588671c85092431a41b02 100644 --- a/en/application-dev/media/camera-device-input.md +++ b/en/application-dev/media/camera-device-input.md @@ -75,7 +75,7 @@ During camera application development, you can listen for the camera status, inc Register the 'cameraStatus' event and return the listening result through a callback, which carries the **CameraStatusInfo** parameter. For details about the parameter, see [CameraStatusInfo](../reference/apis/js-apis-camera.md#camerastatusinfo). ```ts -cameraManager.on('cameraStatus', (cameraStatusInfo) => { +cameraManager.on('cameraStatus', (err, cameraStatusInfo) => { console.info(`camera: ${cameraStatusInfo.camera.cameraId}`); console.info(`status: ${cameraStatusInfo.status}`); }) diff --git a/en/application-dev/media/camera-metadata.md b/en/application-dev/media/camera-metadata.md index 8fdeff1df08f624374f2a2a5cee32b99b2c41e03..67fb374517393a8d85f072245109b3a86b2d4b17 100644 --- a/en/application-dev/media/camera-metadata.md +++ b/en/application-dev/media/camera-metadata.md @@ -48,7 +48,7 @@ During camera application development, you can listen for the status of metadata - Register the 'metadataObjectsAvailable' event to listen for metadata objects that are available. When a valid metadata object is detected, the callback function returns the metadata. This event can be registered when a **MetadataOutput** object is created. ```ts - metadataOutput.on('metadataObjectsAvailable', (metadataObjectArr) => { + metadataOutput.on('metadataObjectsAvailable', (err, metadataObjectArr) => { console.info(`metadata output metadataObjectsAvailable`); }) ``` diff --git a/en/application-dev/media/camera-recording-case.md b/en/application-dev/media/camera-recording-case.md index 7aedbf5688812c47542ee627329b137325f17bbc..e92b8d80d5289071b507f59dcee1389733c498bb 100644 --- a/en/application-dev/media/camera-recording-case.md +++ b/en/application-dev/media/camera-recording-case.md @@ -22,7 +22,7 @@ if (!cameraManager) { } // Listen for camera status changes. -cameraManager.on('cameraStatus', (cameraStatusInfo) => { +cameraManager.on('cameraStatus', (err, cameraStatusInfo) => { console.log(`camera : ${cameraStatusInfo.camera.cameraId}`); console.log(`status: ${cameraStatusInfo.status}`); }) diff --git a/en/application-dev/media/camera-shooting-case.md b/en/application-dev/media/camera-shooting-case.md index da2588b10b844fd2a9432da909d1d387b8193d9f..bf1da09913b897c3aa4d80a91c721f84a25d9f0e 100644 --- a/en/application-dev/media/camera-shooting-case.md +++ b/en/application-dev/media/camera-shooting-case.md @@ -21,7 +21,7 @@ if (!cameraManager) { return; } // Listen for camera status changes. -cameraManager.on('cameraStatus', (cameraStatusInfo) => { +cameraManager.on('cameraStatus', (err, cameraStatusInfo) => { console.info(`camera : ${cameraStatusInfo.camera.cameraId}`); console.info(`status: ${cameraStatusInfo.status}`); }) diff --git a/en/application-dev/media/camera-shooting.md b/en/application-dev/media/camera-shooting.md index 9026267ebc0a6950ced6b5092ce88e8ed31d2e24..9748b389d9f1211ebeec58e828ba5e93f6dfbfe8 100644 --- a/en/application-dev/media/camera-shooting.md +++ b/en/application-dev/media/camera-shooting.md @@ -136,7 +136,7 @@ During camera application development, you can listen for the status of the phot - Register the 'captureStart' event to listen for photographing start events. This event can be registered when a **PhotoOutput** object is created and is triggered when the bottom layer starts exposure for photographing for the first time. The capture ID is returned. ```ts - photoOutput.on('captureStart', (captureId) => { + photoOutput.on('captureStart', (err, captureId) => { console.info(`photo capture stated, captureId : ${captureId}`); }) ``` @@ -144,7 +144,7 @@ During camera application development, you can listen for the status of the phot - Register the 'captureEnd' event to listen for photographing end events. This event can be registered when a **PhotoOutput** object is created and is triggered when the photographing is complete. [CaptureEndInfo](../reference/apis/js-apis-camera.md#captureendinfo) is returned. ```ts - photoOutput.on('captureEnd', (captureEndInfo) => { + photoOutput.on('captureEnd', (err, captureEndInfo) => { console.info(`photo capture end, captureId : ${captureEndInfo.captureId}`); console.info(`frameCount : ${captureEndInfo.frameCount}`); }) diff --git a/en/application-dev/media/image-transformation-native.md b/en/application-dev/media/image-transformation-native.md index 06d342d8092744d7c565d02d0e62c13b71cc12d2..fbe7bed8cac71bdae20b90f9781a5329da3d0dcf 100644 --- a/en/application-dev/media/image-transformation-native.md +++ b/en/application-dev/media/image-transformation-native.md @@ -1,6 +1,6 @@ # Image Transformation (Native) -You will learn how to use native image APIs to process images, including cropping, rotating, scaling, flipping, translating, and opacity setting. +You will learn how to use native image APIs to process images. ## How to Develop @@ -22,9 +22,9 @@ Open the **src/main/cpp/hello.cpp** file and add the following API mappings to t static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor desc[] = { - { "createPixelMap", nullptr, CreatePixelMap, nullptr, nullptr, nullptr, napi_default, nullptr }, - { "createAlphaPixelMap", nullptr, CreateAlphaPixelMap, nullptr, nullptr, nullptr, napi_default, nullptr }, - { "transform", nullptr, Transform, nullptr, nullptr, nullptr, napi_default, nullptr } + { "testGetImageInfo", nullptr, TestGetImageInfo, nullptr, nullptr, nullptr, napi_default, nullptr }, + { "testAccessPixels", nullptr, TestAccessPixels, nullptr, nullptr, nullptr, napi_default, nullptr }, + { "testUnAccessPixels", nullptr, TestUnAccessPixels, nullptr, nullptr, nullptr, napi_default, nullptr }, }; napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); @@ -40,159 +40,56 @@ For details about the APIs, see [Image API Reference](../reference/native-apis/i Obtain the JS resource object from the **hello.cpp** file and convert it to a native resource object. Then you can call native APIs. The sample code is as follows: -1. Create a **PixelMap** object based on a pixel array. - - ```c++ - // Create a PixelMap object. - napi_value CreatePixelMap(napi_env env, napi_callback_info info) +1. Obtain the **PixelMap** information and store the information to the **OhosPixelMapInfo** struct. + ```c++ + static napi_value TestGetImageInfo(napi_env env, napi_callback_info info) { - napi_value udfVar = nullptr; - napi_value thisVar = nullptr; - napi_value argValue[2] = {0}; - size_t argCount = 2; + napi_value result = nullptr; + napi_get_undefined(env, &result); - void* buffer = nullptr; - size_t bufferSize = 0; - struct OhosPixelMapCreateOps createOps; - napi_value pixelmap = nullptr; + napi_value thisVar = nullptr; + napi_value argValue[1] = {0}; + size_t argCount = 1; - napi_get_undefined(env, &udfVar); napi_get_cb_info(env, info, &argCount, argValue, &thisVar, nullptr); - if (napi_get_arraybuffer_info(env, argValue[0], &buffer, &bufferSize) != napi_ok || - buffer == nullptr || bufferSize == 0) { - return udfVar; - } - - createOps.width = 4; - createOps.height = 6; - createOps.pixelFormat = 4; - createOps.alphaType = 0; - int32_t res = OH_PixelMap_CreatePixelMap(env, createOps, (uint8_t *)buffer, bufferSize, &pixelmap); - if (res != OHOS_IMAGE_RESULT_SUCCESS || pixelmap == nullptr) { - return udfVar; - } - return pixelmap; + + OHOS::Media::OhosPixelMapInfo pixelMapInfo; + OHOS::Media::OH_GetImageInfo(env, argValue[0], &pixelMapInfo); + return result; } - - // Create a PixelMap object that contains only the alpha channel. - napi_value CreateAlphaPixelMap(napi_env env, napi_callback_info info) + ``` +2. Obtain the memory address of a **PixelMap** object and lock the memory. + ```c++ + static napi_value TestAccessPixels(napi_env env, napi_callback_info info) { - napi_value udfVar = nullptr; + napi_value result = nullptr; + napi_get_undefined(env, &result); + napi_value thisVar = nullptr; napi_value argValue[1] = {0}; size_t argCount = 1; - napi_value alphaPixelmap = nullptr; - - napi_get_undefined(env, &udfVar); + napi_get_cb_info(env, info, &argCount, argValue, &thisVar, nullptr); - if (napi_get_cb_info(env, info, &argCount, argValue, &thisVar, nullptr) != napi_ok || - argCount < 1 || argValue[0] == nullptr) { - return udfVar; - } - int32_t res = OH_PixelMap_CreateAlphaPixelMap(env, argValue[0], &alphaPixelmap); - if (res != OHOS_IMAGE_RESULT_SUCCESS || alphaPixelmap == nullptr) { - return udfVar; - } - return alphaPixelmap; + void* addrPtr = nullptr; + OHOS::Media::OH_AccessPixels(env, argValue[0], &addrPtr); + return result; } ``` - -2. Perform image transformation. For details about the operation, read the comments in the sample code below. - +3. Unlock the memory of the **PixelMap** object. ```c++ - napi_value Transform(napi_env env, napi_callback_info info) + static napi_value TestUnAccessPixels(napi_env env, napi_callback_info info) { - napi_value thisVar = nullptr; - napi_value argValue[1] = {0}; - size_t argCount = 1; - - if (napi_get_cb_info(env, info, &argCount, argValue, &thisVar, nullptr) != napi_ok || - argCount < 1 || argValue[0] == nullptr) { - return nullptr; - } napi_value result = nullptr; napi_get_undefined(env, &result); - NativePixelMap* native = OH_PixelMap_InitNativePixelMap(env, argValue[0]); - if (native == nullptr) { - return result; - } + napi_value thisVar = nullptr; + napi_value argValue[1] = {0}; + size_t argCount = 1; - // Obtain image information. - struct OhosPixelMapInfo pixelmapInfo; - OH_PixelMap_GetImageInfo(native, &pixelmapInfo); - - // Obtain the number of bytes per row of the PixelMap object. - int32_t rowBytes; - OH_PixelMap_GetBytesNumberPerRow(native, &rowBytes); - - // Check whether the PixelMap object is editable. - int32_t editable = 0; - OH_PixelMap_GetIsEditable(native, &editable); - - // Check whether the PixelMap object supports alpha channels. - int32_t supportAlpha = 0; - OH_PixelMap_IsSupportAlpha(native, &supportAlpha); - - // Set an alpha channel for the PixelMap object. - int32_t alphaAble = 0; - OH_PixelMap_SetAlphaAble(native, alphaAble); - - // Obtain the pixel density of the PixelMap object. - int32_t densityG; - OH_PixelMap_GetDensity(native, &densityG); - - // Set the pixel density for the PixelMap object. - int32_t densityS = 100; - OH_PixelMap_SetDensity(native, densityS); - - // Set the opacity for the PixelMap object. - float opacity = 0.5; - OH_PixelMap_SetOpacity(native, opacity); - - // Scale the image. - // scaleX: The width of the image after scaling is 0.5 of the original width. - // scaleY: The height of the image after scaling is 0.5 of the original height. - float scaleX = 0.5; - float scaleY = 0.5; - OH_PixelMap_Scale(native, scaleX, scaleY); - - // Translate the image. - // translateX: Translate the image by 50 units downwards. - // translateY: Translate the image by 50 units rightwards. - float translateX = 50; - float translateY = 50; - OH_PixelMap_Translate(native, translateX, translateY); - - // Rate the image clockwise by 90°. - float angle = 90; - OH_PixelMap_Rotate(native, angle); - - // Flip the image. - // flipX: whether to flip the image horizontally. The value 1 means to flip the image and 0 means the opposite. - // flipY: whether to flip the image vertically. The value 1 means to flip the image and 0 means the opposite. - int32_t flipX = 0; - int32_t flipY = 1; - OH_PixelMap_Flip(native, flipX, flipY); - - // Crop the image. - // cropX: x-axis coordinate of the start point for cropping (0). - // cropY: y-axis coordinate of the start point for cropping (0). - // cropH: height after cropping (10), cropping from top to bottom. - // cropW: width after cropping (10), cropping from left to right. - int32_t cropX = 1; - int32_t cropY = 1; - int32_t cropW = 10; - int32_t cropH = 10; - OH_PixelMap_Crop(native, cropX, cropY, cropW, cropH); - - uint8_t* pixelAddr = nullptr; - // Obtain the memory address of the PixelMap object and lock the memory. - OH_PixelMap_AccessPixels(native, &pixelAddr); - // Unlock the memory of the PixelMap object. - OH_PixelMap_UnAccessPixels(native); + napi_get_cb_info(env, info, &argCount, argValue, &thisVar, nullptr); + OHOS::Media::OH_UnAccessPixels(env, argValue[0]); return result; } ``` @@ -205,37 +102,41 @@ Obtain the JS resource object from the **hello.cpp** file and convert it to a na ```js import testNapi from 'libentry.so' - import image from '@ohos.multimedia.image' + import image from '@ohos.multimedia.image'; @Entry @Component struct Index { - @State _pixelMap: image.PixelMap = undefined; - build() { - Row() { - Column() { - Button("PixelMap") - .width(100) - .height(100) - .onClick(() => { - const color = new ArrayBuffer(96); - var bufferArr = new Uint8Array(color); - for (var i = 0; i < bufferArr.length; i++) { - bufferArr[i] = 0x80; - } - - this._pixelMap = testNapi.createPixelMap(color); - testNapi.transform(this._pixelMap); + @State message: string = 'IMAGE' + @State _PixelMap: image.PixelMap = undefined + + build() { + Row() { + Column() { + Button(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(() => { + const color = new ArrayBuffer(96); + let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { height: 4, width: 6 } } + image.createPixelMap(color, opts) + .then( pixelmap => { + this._PixelMap = pixelmap; }) - Image(this._pixelMap) - .width(500) - .height(500) - .objectFit(ImageFit.Cover) - } - .width('100%') - } - .height('100%') + testNapi.testGetImageInfo(this._PixelMap); + console.info("Test GetImageInfo success"); + + testNapi.testAccessPixels(this._PixelMap); + console.info("Test AccessPixels success"); + + testNapi.testUnAccessPixels(this._PixelMap); + console.info("Test UnAccessPixels success"); + }) } + .width('100%') + } + .height('100%') + } } ``` diff --git a/en/application-dev/napi/Readme-EN.md b/en/application-dev/napi/Readme-EN.md index 5148a2b5ce3cf73bbd68e96ba2d15449f86a0990..162a07f752491d75d2bf17a3c90520155fd3672f 100644 --- a/en/application-dev/napi/Readme-EN.md +++ b/en/application-dev/napi/Readme-EN.md @@ -5,5 +5,6 @@ - [Raw File Development](rawfile-guidelines.md) - [Native Window Development](native-window-guidelines.md) - [Using MindSpore Lite for Model Inference](mindspore-lite-guidelines.md) +- [Using MindSpore Lite for Offline Model Conversion and Inference](mindspore-lite-offline-model-guidelines.md) - [Connecting the Neural Network Runtime to an AI Inference Framework](neural-network-runtime-guidelines.md) - [Purgeable Memory Development](purgeable-memory-guidelines.md) diff --git a/en/application-dev/napi/mindspore-lite-offline-model-guidelines.md b/en/application-dev/napi/mindspore-lite-offline-model-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..0f149d197cd7ec4f22bb715d75994c09d7577497 --- /dev/null +++ b/en/application-dev/napi/mindspore-lite-offline-model-guidelines.md @@ -0,0 +1,112 @@ +# Using MindSpore Lite for Offline Model Conversion and Inference + +## Basic Concepts + +- MindSpore Lite: a built-in AI inference engine of OpenHarmony that provides inference deployment for deep learning models. + +- Neural Network Runtime (NNRt): a bridge that connects the upper-layer AI inference framework to the bottom-layer acceleration chip to implement cross-chip inference and computing of AI models. + +- Offline model: a model obtained using the offline model conversion tool of the AI hardware vendor. The hardware vendor is responsible for parsing and inference of AI models. + +## When to Use + +The common process for MindSpore Lite AI model deployment is as follows: +- Use the MindSpore Lite model conversion tool to convert third-party models (such as ONNX and CAFFE) to `.ms` models. +- Call APIs of the MindSpore Lite inference engine to perform model inference. By specifying NNRt as the inference device, you can then use the AI hardware in the system to accelerate inference. + +When MindSpore Lite + NNRt inference is used, dynamic image composition in the initial phase will introduce a certain model loading delay. + +If you want to reduce the loading delay to meet the requirements of the deployment scenario, you can use offline model-based inference as an alternative. The operation procedure is as follows: +- Use the offline model conversion tool provided by the AI hardware vendor to compile an offline model in advance. +- Use the MindSpore Lite conversion tool to encapsulate the offline model as a black box into the `.ms` model. +- Pass the `.ms` model to MindSpore Lite for inference. + +During inference, MindSpore Lite directly sends the offline model to the AI hardware connected to NNRt. This way, the model can be loaded without the need for online image composition, greatly reducing the model loading delay. In addition, MindSpore Lite can provide additional hardware-specific information to assist the AI hardware in model inference. + +The following sections describe the offline model inference and conversion process in detail. + +## Constraints + +- Offline model inference can only be implemented at the NNRt backend. The AI hardware needs to connect to NNRt and supports offline model inference. + +## Offline Model Conversion + + +### 1. Building the MindSpore Lite Release Package + +Obtain the [MindSpore Lite source code](https://gitee.com/openharmony/third_party_mindspore). The source code is managed in "compressed package + patch" mode. Run the following commands to decompress the source code package and install the patch: +```bash +cd mindspore +python3 build_helper.py --in_zip_path=./mindspore-v1.8.1.zip --patch_dir=./patches/ --out_src_path=./mindspore-src +``` +If the command execution is successful, the complete MindSpore Lite source code is generated in `mindspore-src/source/`. + +Run the following commands to start building: +```bash +cd mindspore-src/source/ +bash build.sh -I x86_64 -j 8 +``` + +After the building is complete, you can obtain the MindSpore Lite release package from the `output/` directory in the root directory of the source code. + + +### 2. Writing Extended Configuration File of the Conversion Tool + +The offline model comes as a black box and cannot be parsed by the conversion tool to obtain its input and output tensor information. Therefore, you need to manually configure the tensor information in the extended configuration file of the conversion tool. Based on the extended configuration, the conversion tool can then generate the `.ms` model file for encapsulating the offline model. + +An example of the extended configuration is as follows: +- `[third_party_model]` in the first line is a fixed keyword that indicates the section of offline model configuration. +- The following lines exhibit the name, data type, shape, and memory format of the input and output tensors of the model respectively. Each field occupies a line and is expressed in the key-value pair format. The sequence of fields is not limited. +- Among the fields, data type and shape are mandatory, and other parameters are optional. +- Extended parameters are also provided. They are used to encapsulate custom configuration of the offline model into an `.ms` file in the the key-value pair format. The `.ms` file is passed to the AI hardware by NNRt during inference. + +```text +[third_party_model] +input_names=in_0;in_1 +input_dtypes=float32;float32 +input_shapes=8,256,256;8,256,256,3 +input_formats=NCHW;NCHW +output_names=out_0 +output_dtypes=float32 +output_shapes=8,64 +output_formats=NCHW +extended_parameters=key_foo:value_foo;key_bar:value_bar +``` + +The related fields are described as follows: + +- `input_names` (optional): model input name, which is in the string format. If multiple names are specified, use a semicolon (`;`) to separate them. +- `input_dtypes` (mandatory): model input data type, which is in the type format. If multiple data types are specified, use a semicolon (`;`) to separate them. +- `input_shapes` (mandatory): model input shape, which is in the integer array format. If multiple input shapes are specified, use a semicolon (`;`) to separate them. +- `input_formats` (optional): model input memory format, which is in the string format. If multiple formats are specified, use a semicolon (`;`) to separate them. The default value is `NHWC`. +- `output_names` (optional): model output name, which is in the string format. If multiple names are specified, use a semicolon (`;`) to separate them. +- `output_dtypes` (mandatory): model output data type, which is in the type format. If multiple data types are specified, use a semicolon (`;`) to separate them. +- `output_shapes` (mandatory): model output shape, which is in the integer array format. If multiple output shapes are specified, use a semicolon (`;`) to separate them. +- `output_formats` (optional): model output memory format, which is in the string format. If multiple formats are specified, use a semicolon (`;`) to separate them. The default value is `NHWC`. +- `extended_parameters` (optional): custom configuration of the inference hardware, which is in the key-value pair format. It is passed to the AI hardware through the NNRt backend during inference. + +### 3. Converting an Offline Model + +Decompress the MindSpore Lite release package obtained in step 1. Go to the directory where the conversion tool is located (that is, `tools/converter/converter/`), and run the following commands: + +```bash +export LD_LIBRARY_PATH=${PWD}/../lib +./converter_lite --fmk=THIRDPARTY --modelFile=/path/to/your_model --configFile=/path/to/your_config --outputFile=/path/to/output_model +``` +The offline model conversion is complete. + +The related parameters are described as follows: +- `--fmk`: original format of the input model. `THIRDPARTY` indicates an offline model. +- `--modelFile`: path of the input model. +- `--configFile`: path of the extended configuration file. The file is used to configure offline model information. +- `--outputFile`: path of the output model. You do not need to add the file name extension. The `.ms` suffix is generated automatically. + +> **NOTE** +> +> If `fmk` is set to `THIRDPARTY`, offline model conversion is performed. In this case, only the preceding four parameters and the extended configuration file take effect. + +## Offline Model Inference + +Offline model inference is the same as common MindSpore Lite model inference except that only NNRt devices can be added to the inference context. + +For details about the MindSpore Lite model inference process, see [Using MindSpore Lite for Model Inference](./mindspore-lite-guidelines.md). diff --git a/en/application-dev/napi/purgeable-memory-guidelines.md b/en/application-dev/napi/purgeable-memory-guidelines.md index ffc2ff72ddd045d61da55c41f07434a8d4e31c28..706786d429b492f79f86c4c108cf8e3e63940def 100644 --- a/en/application-dev/napi/purgeable-memory-guidelines.md +++ b/en/application-dev/napi/purgeable-memory-guidelines.md @@ -12,12 +12,12 @@ The following scenarios are common for native purgeable memory development: ## Available APIs -| API| Description| +| API| Description| | -------- | -------- | -| OH_PurgeableMemory \*OH_PurgeableMemory_Create(size_t size, OH_PurgeableMemory_ModifyFunc func, void \*funcPara) | Creates a **PurgeableMemory** object. A new **PurgeableMemory** object is generated each time this API is called.| -| bool OH_PurgeableMemory_Destroy(OH_PurgeableMemory \*purgObj) | Destroys a **PurgeableMemory** object.| -| bool OH_PurgeableMemory_BeginRead(OH_PurgeableMemory \*purgObj) | Begins a read operation on a **PurgeableMemory** object.| -| void OH_PurgeableMemory_EndRead(OH_PurgeableMemory \*purgObj) | Ends a read operation on a **PurgeableMemory** object and decreases the reference count of the object by 1. When the reference count reaches 0, the object can be reclaimed by the system.| +| OH_PurgeableMemory \*OH_PurgeableMemory_Create(size_t size, OH_PurgeableMemory_ModifyFunc func, void \*funcPara) | Creates a **PurgeableMemory** object. A new **PurgeableMemory** object is generated each time this API is called.| +| bool OH_PurgeableMemory_Destroy(OH_PurgeableMemory \*purgObj) | Destroys a **PurgeableMemory** object.| +| bool OH_PurgeableMemory_BeginRead(OH_PurgeableMemory \*purgObj) | Begins a read operation on a **PurgeableMemory** object.| +| void OH_PurgeableMemory_EndRead(OH_PurgeableMemory \*purgObj) | Ends a read operation on a **PurgeableMemory** object and decreases the reference count of the object by 1. When the reference count reaches 0, the object can be reclaimed by the system.| |bool OH_PurgeableMemory_BeginWrite(OH_PurgeableMemory \*purgObj) | Begins a write operation on a **PurgeableMemory** object.| |void OH_PurgeableMemory_EndWrite(OH_PurgeableMemory \*purgObj)|Ends a write operation on a **PurgeableMemory** object and decreases the reference count of the object by 1. When the reference count reaches 0, the object can be reclaimed by the system.| |void \*OH_PurgeableMemory_GetContent(OH_PurgeableMemory \*purgObj)|Obtains the memory data of a **PurgeableMemory** object.| @@ -35,34 +35,32 @@ The following steps describe how to use the native purgeable memory APIs to appl struct ParaData{ int start; int end; - } + }; // Declare a function for modifying the object. bool FactorialFunc(void* data, size_t size, void* param){ - bool ret = true; - int oriData = *(int*)(data); - int i = param->start; - while(iend){ - oriData *= i; - } - *data = oriData; - if(oriData < 0) - ret = false; - return ret; + bool ret = true; + ParaData *pdata = (ParaData*) param; + int* oriData = (int*)data; + int i = pdata->start; + while(iend){ + *oriData *= i; + } + return ret; } // Declare the parameters of the extended function for modifying the object. struct AppendParaData{ int newPara; - } + }; // Declare the extended function for modifying the object. bool AddFunc(void* data, size_t size, void* param){ - bool ret = true; - int oriData = *(int*)(data); - oriData += param->newPara; - *data = oriData; - return ret; + bool ret = true; + int *oriDatap = (int*) data; + AppendParaData* apData = (AppendParaData*)param; + *oriDatap += apData->newPara; + return ret; } ``` 2. Create a **PurgeableMemory** object. @@ -74,11 +72,14 @@ The following steps describe how to use the native purgeable memory APIs to appl struct ParaData pdata = {1,2}; // Create a PurgeableMemory object. - OH_PurgableMmory* pPurgmem = OH_PurgableMmory_Create(DATASIZE, FactorialFunc, &pdata); + OH_PurgeableMemory* pPurgmem = OH_PurgeableMemory_Create(DATASIZE, FactorialFunc, &pdata); ``` 3. Perfrom a read operation on the **PurgeableMemory** object. ```c++ + // Define an object type based on the service requirements. + class ReqObj; + // Begin a read operation on the object. OH_PurgeableMemory_BeginRead(pPurgmem); @@ -94,8 +95,11 @@ The following steps describe how to use the native purgeable memory APIs to appl 4. Perform a write operation on the **PurgeableMemory** object. ```c++ + // Define an object type based on the service requirements. + class ReqObj; + // Begin a write operation on the object. - OH_PurgeableMemory_BeginWrite(pPurgmem) + OH_PurgeableMemory_BeginWrite(pPurgmem); // Obtain the object data. ReqObj* pReqObj = (ReqObj*) OH_PurgeableMemory_GetContent(pPurgmem); diff --git a/en/application-dev/quick-start/Readme-EN.md b/en/application-dev/quick-start/Readme-EN.md index 1f6a86ab9fbdda2a9742a19879e3ae372658b6d2..89b5ef119fe4e296a158c26a6407f2eb752c0b49 100644 --- a/en/application-dev/quick-start/Readme-EN.md +++ b/en/application-dev/quick-start/Readme-EN.md @@ -47,19 +47,19 @@ - Custom Component - [Creating a Custom Component](arkts-create-custom-components.md) - [Page and Custom Component Lifecycle](arkts-page-custom-components-lifecycle.md) - - [\@Builder: Custom Builder Function](arkts-builder.md) - - [\@BuilderParam: @Builder Function Reference](arkts-builderparam.md) - - [\@Styles: Definition of Resusable Styles](arkts-style.md) - - [\@Extend: Extension of Built-in Components](arkts-extend.md) - - [stateStyles: Polymorphic Style](arkts-statestyles.md) + - [\@Builder Decorator: Custom Builder Function](arkts-builder.md) + - [\@BuilderParam Decorator: @Builder Function Reference](arkts-builderparam.md) + - [\@Styles Decorator: Definition of Resusable Styles](arkts-style.md) + - [\@Extend Decorator: Extension of Built-in Components](arkts-extend.md) + - [stateStyles Decorator: Polymorphic Style](arkts-statestyles.md) - State Management - [State Management Overview](arkts-state-management-overview.md) - Component State Management - - [\@State: State Owned by Component](arkts-state.md) - - [\@Prop: One-Way Synchronization from Parent to Child Components](arkts-prop.md) - - [\@Link: Two-Way Synchronization Between Parent and Child Components](arkts-link.md) - - [\@Provide and \@Consume: Two-Way Synchronization with Descendant Components](arkts-provide-and-consume.md) - - [\@Observed and \@ObjectLink: Observing Attribute Changes in Nested Class Objects](arkts-observed-and-objectlink.md) + - [\@State Decorator: State Owned by Component](arkts-state.md) + - [\@Prop Decorator: One-Way Synchronization from Parent to Child Components](arkts-prop.md) + - [\@Link Decorator: Two-Way Synchronization Between Parent and Child Components](arkts-link.md) + - [\@Provide and \@Consume Decorators: Two-Way Synchronization with Descendant Components](arkts-provide-and-consume.md) + - [\@Observed and \@ObjectLink Decorators: Observing Attribute Changes in Nested Class Objects](arkts-observed-and-objectlink.md) - Application State Management - [Application State Management Overview](arkts-application-state-management-overview.md) - [LocalStorage: UI State Storage](arkts-localstorage.md) diff --git a/en/application-dev/quick-start/arkts-builder.md b/en/application-dev/quick-start/arkts-builder.md index 9efe5b95238ad1b73f8fbb5689b630387ac18d4f..80a262fcd97a0dcf6808bf8cdb84bf78849cb0e1 100644 --- a/en/application-dev/quick-start/arkts-builder.md +++ b/en/application-dev/quick-start/arkts-builder.md @@ -1,4 +1,4 @@ -# \@Builder: Custom Builder Function +# \@Builder Decorator: Custom Builder Function As previously described, you can reuse UI elements by creating a custom component, which comes with a fixed internal UI structure and allows for data transfer only with its caller. ArkUI also provides a more lightweight mechanism for reusing UI elements: \@Builder. An \@Builder decorated function is a special function that serves similar purpose as the build function. The \@Builder function body follows the same syntax rules as the **build** function. You can abstract reusable UI elements into a method and call the method in **build**. diff --git a/en/application-dev/quick-start/arkts-builderparam.md b/en/application-dev/quick-start/arkts-builderparam.md index 26f25044c2968a5417fdc73fd355bd24997d14df..66647f094bfa5e5e090dba5cb5b1f0af27850d5f 100644 --- a/en/application-dev/quick-start/arkts-builderparam.md +++ b/en/application-dev/quick-start/arkts-builderparam.md @@ -1,4 +1,4 @@ -# \@BuilderParam: @Builder Function Reference +# \@BuilderParam Decorator: @Builder Function Reference In certain circumstances, you may need to add a specific function, such as a click-to-jump action, to a custom component. However, embedding an event method directly inside of the component will add the function to all places where the component is imported. This is where the \@BuilderParam decorator comes into the picture. \@BuilderParam is used to decorate a custom component member variable of type reference to an \@Builder method. When initializing a custom component, you can assign a value to the variable, thereby adding the specific function to the custom component. This decorator can be used to declare an element of any UI description, similar to a slot placeholder. diff --git a/en/application-dev/quick-start/arkts-extend.md b/en/application-dev/quick-start/arkts-extend.md index 0867e7b3cece4d2d7928ac401b38851dadcf6669..fba84d8154592ba5c61b2106ab130b4ff92991ce 100644 --- a/en/application-dev/quick-start/arkts-extend.md +++ b/en/application-dev/quick-start/arkts-extend.md @@ -1,4 +1,4 @@ -# \@Extend: Extension of Built-in Components +# \@Extend Decorator: Extension of Built-in Components Apart from\@Styles used to extend styles, AkrUI also provides \@Extend, which allows you to add a new attribute feature to a built-in component. diff --git a/en/application-dev/quick-start/arkts-link.md b/en/application-dev/quick-start/arkts-link.md index 0147645b6e0c964528df98edfd8e692b15b7d994..81db9ef3e2f4ce2df8cec8a1c793712ca79374d8 100644 --- a/en/application-dev/quick-start/arkts-link.md +++ b/en/application-dev/quick-start/arkts-link.md @@ -1,4 +1,4 @@ -# \@Link: Two-Way Synchronization Between Parent and Child Components +# \@Link Decorator: Two-Way Synchronization Between Parent and Child Components An \@Link decorated variable can create two-way synchronization with a variable of its parent component. diff --git a/en/application-dev/quick-start/arkts-observed-and-objectlink.md b/en/application-dev/quick-start/arkts-observed-and-objectlink.md index 1282545cc1d65a1acdc90da3ac5a2828cf611ca9..808e522540be970004aab0a2bcd2009af3916df0 100644 --- a/en/application-dev/quick-start/arkts-observed-and-objectlink.md +++ b/en/application-dev/quick-start/arkts-observed-and-objectlink.md @@ -1,4 +1,4 @@ -# \@Observed and \@ObjectLink: Observing Attribute Changes in Nested Class Objects +# \@Observed and \@ObjectLink Decorators: Observing Attribute Changes in Nested Class Objects The decorators described above can observe only the changes of the first layer. However, in real-world application development, the application may encapsulate its own data model based on development requirements. In the case of multi-layer nesting, for example, a two-dimensional array, an array item class, or a class insider another class as an attribute, the attribute changes at the second layer cannot be observed. This is where the \@Observed and \@ObjectLink decorators come in handy. diff --git a/en/application-dev/quick-start/arkts-persiststorage.md b/en/application-dev/quick-start/arkts-persiststorage.md index cff8f9aa3bc83f9e1f34be3c50652c925ecd0437..303402ac5a2dffe2537fa4b252a21fcfe31631ad 100644 --- a/en/application-dev/quick-start/arkts-persiststorage.md +++ b/en/application-dev/quick-start/arkts-persiststorage.md @@ -24,6 +24,7 @@ Persistence of data is a relatively slow operation. Applications should avoid th The preceding situations may overload the change process of persisted data. As a result, the PersistentStorage implementation may limit the change frequency of persisted attributes. +PersistentStorage is associated with UIContext and can be called to persist data only when [UIContext](../reference/apis/js-apis-arkui-UIContext.md#uicontext) is specified. The context can be identified in [runScopedTask](../reference/apis/js-apis-arkui-UIContext.md#runscopedtask). ## Application Scenarios @@ -77,7 +78,7 @@ struct Index { ``` - First running after fresh application installation: - 1. **PersistProp** is called to initialize PersistentStorage. A search for the **aProp** attribute on the PersistentStorage disk returns no result, because the application has just been installed. + 1. **PersistProp** is called to initialize PersistentStorage. A search for the **aProp** attribute on the PersistentStorage disk returns no result, because the application has just been installed. 2. A search for the attribute **aProp** in AppStorage still returns no result. 3. Create the **aProp** attribute of the number type in AppStorge and initialize it with the value 47. 4. PersistentStorage writes the **aProp** attribute and its value **47** to the disk. The value of **aProp** in AppStorage and its subsequent changes are persisted. diff --git a/en/application-dev/quick-start/arkts-prop.md b/en/application-dev/quick-start/arkts-prop.md index ca1ac8c34cdd8fb1f783cdadac3a219bfcc05548..1e962f469695d8d942847469dbebec1fcbf30ade 100644 --- a/en/application-dev/quick-start/arkts-prop.md +++ b/en/application-dev/quick-start/arkts-prop.md @@ -1,4 +1,4 @@ -# \@Prop: One-Way Synchronization from Parent to Child Components +# \@Prop Decorator: One-Way Synchronization from Parent to Child Components An \@Prop decorated variable can create one-way synchronization with a variable of its parent component. \@Prop decorated variables are mutable, but changes are not synchronized to the parent component. diff --git a/en/application-dev/quick-start/arkts-provide-and-consume.md b/en/application-dev/quick-start/arkts-provide-and-consume.md index d8dc8f5b41748c06982e6d339a88e0b2261dbd69..427e2f79d0d2f04b62c8d31f7633f10ab449d8eb 100644 --- a/en/application-dev/quick-start/arkts-provide-and-consume.md +++ b/en/application-dev/quick-start/arkts-provide-and-consume.md @@ -1,4 +1,4 @@ -# \@Provide and \@Consume: Two-Way Synchronization with Descendant Components +# \@Provide and \@Consume Decorators: Two-Way Synchronization with Descendant Components \@Provide and \@Consume are used for two-way data synchronization with descendant components in scenarios where state data needs to be transferred between multiple levels. They do not involve passing a variable from component to component multiple times. diff --git a/en/application-dev/quick-start/arkts-state.md b/en/application-dev/quick-start/arkts-state.md index 6ac35e388df8471d78245fd52fa82aa8a5a7f580..be3260d6855bdb72a8e38fbaea31307117ec091b 100644 --- a/en/application-dev/quick-start/arkts-state.md +++ b/en/application-dev/quick-start/arkts-state.md @@ -1,4 +1,4 @@ -# \@State: State Owned by Component +# \@State Decorator: State Owned by Component An \@State decorated variable, also called a state variable, is a variable that holds the state property and is used to render the owning custom component. When it changes, the UI is re-rendered accordingly. diff --git a/en/application-dev/quick-start/arkts-statestyles.md b/en/application-dev/quick-start/arkts-statestyles.md index fd0ac67bdba9603d82d385658c89ffbc40d931db..c712d74e8bacdda40235efe0798e6092df03ec63 100644 --- a/en/application-dev/quick-start/arkts-statestyles.md +++ b/en/application-dev/quick-start/arkts-statestyles.md @@ -1,4 +1,4 @@ -# stateStyles: Polymorphic Style +# stateStyles Decorator: Polymorphic Style Unlike \@Styles and \@Extend, which are used to reuse styles only on static pages, stateStyles enables you to set state-specific styles. diff --git a/en/application-dev/quick-start/arkts-style.md b/en/application-dev/quick-start/arkts-style.md index 64f03c11e337bd4932c5bb7fbece4ac59499364c..a380964f5893e963e6ce3c62c64d1255f37a8042 100644 --- a/en/application-dev/quick-start/arkts-style.md +++ b/en/application-dev/quick-start/arkts-style.md @@ -1,4 +1,4 @@ -# \@Styles: Definition of Resusable Styles +# \@Styles Decorator: Definition of Resusable Styles If the style of each component needs to be set separately, this will result in a large amount of repeated code during development. Though copy and paste is available, it is inefficient and error-prone. To maximize code efficiency and maintainability, the \@Styles decorator is introduced. diff --git a/en/application-dev/quick-start/figures/changeToAPI10.png b/en/application-dev/quick-start/figures/changeToAPI10.png new file mode 100644 index 0000000000000000000000000000000000000000..32c7660ccf7dbd05c206b7753a2dfdb72cca5d0e Binary files /dev/null and b/en/application-dev/quick-start/figures/changeToAPI10.png differ diff --git a/en/application-dev/quick-start/figures/chooseStageModel.png b/en/application-dev/quick-start/figures/chooseStageModel.png index 3125c8ba0591ce0c53344f35fb780eb956601624..b7dd96b6b7c5d2afd241e0c6fd9ee91977692115 100644 Binary files a/en/application-dev/quick-start/figures/chooseStageModel.png and b/en/application-dev/quick-start/figures/chooseStageModel.png differ diff --git a/en/application-dev/quick-start/figures/createProject.png b/en/application-dev/quick-start/figures/createProject.png index 7a56a44e0e7f80671b86c521792352db625ccad7..6c884853a1afcb2dbb72f1e5f7914ab063908299 100644 Binary files a/en/application-dev/quick-start/figures/createProject.png and b/en/application-dev/quick-start/figures/createProject.png differ diff --git a/en/application-dev/quick-start/figures/deleteRuntimeOS.png b/en/application-dev/quick-start/figures/deleteRuntimeOS.png new file mode 100644 index 0000000000000000000000000000000000000000..8087b03be057d646ae6e3348abae73c1e840b781 Binary files /dev/null and b/en/application-dev/quick-start/figures/deleteRuntimeOS.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001609333677.png b/en/application-dev/quick-start/figures/en-us_image_0000001609333677.png new file mode 100644 index 0000000000000000000000000000000000000000..88e2fede373b6b369375bc2d8e58b2dba0770da6 Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001609333677.png differ diff --git a/en/application-dev/quick-start/figures/targetSdkVersion.png b/en/application-dev/quick-start/figures/targetSdkVersion.png new file mode 100644 index 0000000000000000000000000000000000000000..e3846adab2a4b644e09dd00c7e66c79db94cbb18 Binary files /dev/null and b/en/application-dev/quick-start/figures/targetSdkVersion.png differ diff --git a/en/application-dev/quick-start/module-configuration-file.md b/en/application-dev/quick-start/module-configuration-file.md index cca1cb058c358aff32c7b8e635af01a58f7aadfd..3320ab86ce4ff0c6527b06390459551a853df8da 100644 --- a/en/application-dev/quick-start/module-configuration-file.md +++ b/en/application-dev/quick-start/module-configuration-file.md @@ -61,8 +61,7 @@ This topic gives an overview of the **module.json5** configuration file. To star ] }, "targetModuleName": "feature", - "targetPriority": 50, - "isolationMode": "nonisolationFirst" + "targetPriority": 50 } ``` @@ -74,7 +73,7 @@ As shown above, the **module.json5** file contains several tags. | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | -| name | Name of the module. The value is a string with a maximum of 31 bytes and must be unique in the entire application. | String| No| +| name | Name of the module. The value is a string with a maximum of 31 bytes and must be unique in the entire application. During application upgrade, this name can be changed. If it is changed, migration of module-related directories is required for the application. You can use the [file operation API](../reference/apis/js-apis-file-fs.md#fscopydir10) for migration.| String| No| | type | Type of the module. The options are as follows:
- **entry**: main module of the application.
- **feature**: dynamic feature module of the application.
- **har**: static shared module.
- **shared**: dynamic shared module.| String| No| | srcEntry | Code path corresponding to the module. The value is a string with a maximum of 127 bytes.| String| Yes (initial value: left empty)| | description | Description of the module. The value is a string with a maximum of 255 bytes or a string resource index.| String| Yes (initial value: left empty)| @@ -94,9 +93,11 @@ As shown above, the **module.json5** file contains several tags. | [dependencies](#dependencies)| List of shared libraries on which the current module depends during running.| Object array| Yes (initial value: left empty) | | targetModuleName | Target module of the bundle. The value is a string with a maximum of 31 bytes. It must be unique in the entire application.|String|Yes (if the initial value is used, the target module is not a module with the overlay feature)| | targetPriority | Priority of the module. When **targetModuleName** is set, the module is a module with the overlay feature. The value ranges from 1 to 100.|Number|Yes (initial value: **1**)| -| [proxyDatas](#proxydatas) | List of data proxies provided by the module.| Object array| Yes (initial value: left empty)| +| [proxyDatas(deprecated)](#proxydatasdeprecated) | This API is deprecated since API version 10. You are advised to use **proxydata** instead. List of data proxies provided by the module.| Object array| Yes (initial value: left empty)| +| [proxyData](#proxydata) | List of data proxies provided by the module.| Object array| Yes (initial value: left empty)| | isolationMode | Multi-process configuration of the module. The options are as follows:
- **nonisolationFirst**: The module preferentially runs in a non-independent process.
- **isolationFirst**: The module preferentially runs in an independent process.
- **isolationOnly**: The module runs only in an independent process.
- **nonisolationOnly**: The module runs only in non-independent processes.|String|Yes (initial value: **nonisolationFirst**)| -| generateBuildHash |Whether the hash value of the HAP or HSP file is generated by the packaging tool. The hash value (if any) is used to determine whether the application needs to be updated when the system is updated in OTA mode but the **versionCode** value of the application remains unchanged.
This tag is enabled only when the **generateBuildHash** tag in the [app.json5](./app-configuration-file.md) file is **false**.
**NOTE**
This tag applies only to system applications.|Boolean|Yes (initial value: **false**)| +| generateBuildHash |Whether the hash value of the HAP or HSP file is generated by the packaging tool. The hash value (if any) is used to determine whether the application needs to be updated when the system is updated in OTA mode but the **versionCode** value of the application remains unchanged.
This tag is enabled only when the **generateBuildHash** tag in the [app.json5](./app-configuration-file.md) file is **false**.**
**NOTE**
This tag applies only to system applications.**|Boolean|Yes (initial value: **false**)| +| compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed.
- **true**: The **libs** libraries are packaged in the HAP file after being compressed.
- **false**: The **libs** libraries are stored without being compressed and will be directly loaded during the installation of the HAP file.| Boolean| Yes (initial value: **true**)| ## deviceTypes @@ -256,7 +257,7 @@ The **abilities** tag represents the UIAbility configuration of the module, whic | minWindowWidth | Minimum window width supported by the UIAbility component, in vp. The minimum value is 0, and the value cannot be less than the minimum window width allowed by the platform or greater than the value of **maxWindowWidth**. For details about the window size, see [Constraints](../windowmanager/window-overview.md#constraints).| Number| Yes (initial value: minimum window width supported by the platform)| | maxWindowHeight | Maximum window height supported by the UIAbility component, in vp. The minimum value is 0, and the value cannot be less than the value of **minWindowHeight** or greater than the maximum window height allowed by the platform. For details about the window size, see [Constraints](../windowmanager/window-overview.md#constraints).| Number| Yes (initial value: maximum window height supported by the platform)| | minWindowHeight | Minimum window height supported by the UIAbility component, in vp. The minimum value is 0, and the value cannot be less than the minimum window height allowed by the platform or greater than the value of **maxWindowHeight**. For details about the window size, see [Constraints](../windowmanager/window-overview.md#constraints).| Number| Yes (initial value: minimum window height supported by the platform)| -| excludeFromMissions | Whether the UIAbility component is displayed in the recent task list.
- **true**: displayed in the recent task list.
- **false**: not displayed in the recent task list.
**NOTE**
This attribute applies only to system applications and does not take effect for third-party applications.| Boolean| Yes (initial value: **false**)| +| excludeFromMissions | Whether the UIAbility component is displayed in the recent task list.
- **true**: displayed in the recent task list.
- **false**: not displayed in the recent task list.
**NOTE**
This attribute applies only to system applications and requires the **AllowAbilityExcludeFromMissions** privilege. Learn [Application Privilege Configuration](../../device-dev/subsystems/subsys-app-privilege-config-guide.md).| Boolean| Yes (initial value: **false**)| | recoverable | Whether the application can be recovered to its previous state in case of a detected fault.
- **true**: The application can be recovered to its previous state in case of a detected fault.
- **false**: The application cannot be recovered to its previous state in case of a detected fault.| Boolean| Yes (initial value: **false**)| | unclearableMission | Whether the UIAbility component is unclearable in the recent tasks list.
- **true**: The UIAbility component is unclearable in the recent tasks list.
- **false**: The UIAbility component is clearable in the recent tasks list.
**NOTE**
This attribute works only after the [AllowMissionNotCleared](../../device-dev/subsystems/subsys-app-privilege-config-guide.md) privilege is obtained.| Boolean| Yes (initial value: **false**)| @@ -379,7 +380,7 @@ The **extensionAbilities** tag represents the configuration of extensionAbilitie | type | Type of the ExtensionAbility component. The options are as follows:
- **form**: ExtensionAbility of a widget.
- **workScheduler**: ExtensionAbility of a Work Scheduler task.
- **inputMethod**: ExtensionAbility of an input method.
- **service**: service component running in the background.
- **accessibility**: ExtensionAbility of an accessibility feature.
- **dataShare**: ExtensionAbility for data sharing.
- **fileShare**: ExtensionAbility for file sharing.
- **staticSubscriber**: ExtensionAbility for static broadcast.
- **wallpaper**: ExtensionAbility of the wallpaper.
- **backup**: ExtensionAbility for data backup.
- **window**: ExtensionAbility of a window. This type of ExtensionAbility creates a window during startup for which you can develop the GUI. The window is then combined with other application windows through **abilityComponent**.
- **thumbnail**: ExtensionAbility for obtaining file thumbnails. You can provide thumbnails for files of customized file types.
- **preview**: ExtensionAbility for preview. This type of ExtensionAbility can parse the file and display it in a window. You can combine the window with other application windows.
- **print**: ExtensionAbility for the print framework.
- **push**: ExtensionAbility to be pushed.
- **driver**: ExtensionAbility for the driver framework.
**NOTE**
The **service** and **dataShare** types apply only to system applications and do not take effect for third-party applications.| String| No| | permissions | Permissions required for another application to access the ExtensionAbility component.
The value is generally in the reverse domain name notation and contains a maximum of 255 bytes. It is an array of permission names predefined by the system or customized. The name of a customized permission must be the same as the **name** value of a permission defined in the **defPermissions** attribute.| String array| Yes (initial value: left empty)| | uri | Data URI provided by the ExtensionAbility component. The value is a string with a maximum of 255 bytes, in the reverse domain name notation.
**NOTE**
This attribute is mandatory when the type of the ExtensionAbility component is set to **dataShare**.| String| Yes (initial value: left empty)| -|skills | Feature set of [wants](../application-models/want-overview.md) that can be received by the ExtensionAbility component.
Configuration rule: In an entry package, you can configure multiple **skills** attributes with the entry capability. (A **skills** attribute with the entry capability is the one that has **ohos.want.action.home** and **entity.system.home** configured.) The **label** and **icon** in the first ExtensionAbility that has **skills** configured are used as the **label** and **icon** of the entire OpenHarmony service/application.
**NOTE**
The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application, but not for an OpenHarmony service.| Array| Yes (initial value: left empty)| +|skills | Feature set of [wants](../application-models/want-overview.md) that can be received by the ExtensionAbility component.
Configuration rule: In an entry package, you can configure multiple **skills** attributes with the entry capability. (A **skills** attribute with the entry capability is the one that has **ohos.want.action.home** and **entity.system.home** configured.) The **label** and **icon** in the first ExtensionAbility that has **skills** configured are used as the **label** and **icon** of the entire OpenHarmony service/application.
**NOTE**
The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application,
but not for an OpenHarmony service.| Array| Yes (initial value: left empty)| | [metadata](#metadata)| Metadata of the ExtensionAbility component.| Object| Yes (initial value: left empty)| | exported | Whether the ExtensionAbility component can be called by other applications.
- **true**: The ExtensionAbility component can be called by other applications.
- **false**: The ExtensionAbility component cannot be called by other applications.| Boolean| Yes (initial value: **false**)| @@ -737,7 +738,9 @@ Example of the **dependencies** structure: } ``` -## proxyDatas +## proxyDatas(deprecated) + +>This API is supported since API version 10 and deprecated since API version 10. You are advised to use [proxyData](#proxydata) instead. The **proxyDatas** tag provides the list of data proxies provided by the module. It can be configured only for entry and feature modules. @@ -768,3 +771,35 @@ Example of the **proxyDatas** structure: } } ``` + +## proxyData + +The **proxyDatas** tag provides the list of data proxies provided by the module. It can be configured only for entry and feature modules. + +**Table 21** proxyData +| Name | Description | Data Type| Initial Value Allowed| +| ----------- | ------------------------------ | -------- | ---------- | +| uri | URI of the data proxy. The URIs configured for different data proxies must be unique and must be in the *datashareproxy://Current application package name/xxx* format. | String | No| +| requiredReadPermission | Permission required for reading data from the data proxy. For non-system applications, this field is mandatory, and the permission level must be system_basic or system_core. For system applications, this field is optional, and the permission level is not limited. For details about the permission level, see [Application Permission List](../security/permission-list.md).| String | Yes (initial value: left empty)| +| requiredWritePermission | Permission required for writing data to the data proxy. For non-system applications, this field is mandatory, and the permission level must be system_basic or system_core. For system applications, this field is optional, and the permission level is not limited. For details about the permission level, see [Application Permission List](../security/permission-list.md).| String | Yes (initial value: left empty)| +| [metadata](#metadata)| Metadata of the data proxy. Only the **name** and **resource** fields can be configured.| Object| Yes (initial value: left empty)| + +Example of the **proxyData** structure: + +```json +{ + "module": { + "proxyData": [ + { + "uri":"datashareproxy://com.ohos.datashare/event/Meeting", + "requiredReadPermission": "ohos.permission.GET_BUNDLE_INFO", + "requiredWritePermission": "ohos.permission.GET_BUNDLE_INFO", + "metadata": { + "name": "datashare_metadata", + "resource": "$profile:datashare" + } + } + ] + } +} +``` diff --git a/en/application-dev/quick-start/start-overview.md b/en/application-dev/quick-start/start-overview.md index deb8f8029bc24a78a362f0babdaf5e85c2e000f3..2bc53666dce570f5c9c5c9c5a0b8c48e353422d2 100644 --- a/en/application-dev/quick-start/start-overview.md +++ b/en/application-dev/quick-start/start-overview.md @@ -29,8 +29,9 @@ The application model is the abstraction of capabilities required by OpenHarmony Along its evolution, OpenHarmony has provided two application models: -- Feature Ability (FA) model. This model is supported by OpenHarmony API version 7 and 8. It is no longer recommended. For details about development based on the FA model, see [FA Model Development Overview](../application-models/fa-model-development-overview.md). -- Stage model. This model is supported since OpenHarmony API version 9. It is recommended and will evolve for a long time. In this model, classes such as **AbilityStage** and **WindowStage** are provided as the stage of application components and windows. That's why it is named stage model. For details about development based on the stage model, see [Stage Model Development Overview](../application-models/fa-model-development-overview.md). +- **Stage model**: This model is supported since API version 9. It is recommended. In this model, classes such as **AbilityStage** and **WindowStage** are provided as the stage of application components and windows. That's why it is named stage model. For details about development based on the stage model, see [Stage Model Development Overview](../application-models/stage-model-development-overview.md). The examples in this document are all based on the stage model. + +- **Feature Ability (FA) model**: This model is supported since API version 7. It is no longer recommended. For details about development based on the FA model, see [FA Model Development Overview](../application-models/fa-model-development-overview.md). For details about the differences between the FA model and stage model, see [Interpretation of the Application Model](../application-models/application-model-description.md). @@ -39,8 +40,8 @@ To help you better understand the preceding basic concepts and application devel ## Tool Preparation -1. Download the latest version of [DevEco Studio](https://developer.harmonyos.com/cn/develop/deveco-studio). +1. Download the latest version of [DevEco Studio](../../release-notes/OpenHarmony-v4.0-beta1.md#version-mapping). 2. Install DevEco Studio and configure the development environment. For details, see [Setting Up the Development Environment](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/environment_config-0000001052902427-V3). -When you are done, follow the instructions in [Getting Started with ArkTS in Stage Model](start-with-ets-stage.md), [Getting Started with ArkTS in FA Model](start-with-ets-fa.md), and [Getting Started with JavaScript in FA Model](start-with-js-fa.md). +When you are done, follow the instructions in [Getting Started with ArkTS in Stage Model](start-with-ets-stage.md). diff --git a/en/application-dev/quick-start/start-with-ets-stage.md b/en/application-dev/quick-start/start-with-ets-stage.md index fb8593d555aec31c44e7a6658f6a68f2ab99dccb..b36b98e08c31e1132ada81230d3ef8110227a422 100644 --- a/en/application-dev/quick-start/start-with-ets-stage.md +++ b/en/application-dev/quick-start/start-with-ets-stage.md @@ -1,20 +1,27 @@ # Getting Started with ArkTS in Stage Model -> **NOTE** -> -> To use ArkTS, your DevEco Studio must be V3.0.0.900 Beta3 or later. -> -> For best possible results, use [DevEco Studio 3.1 Beta2](https://developer.harmonyos.com/cn/develop/deveco-studio) for your development. - +> **NOTE** +> +> To use ArkTS, your DevEco Studio must be V3.0.0.900 Beta3 or later. +> +> In this document, DevEco Studio 4.0 Beta1 is used. You can download it [here](../../release-notes/OpenHarmony-v4.0-beta1.md#version-mapping). ## Creating an ArkTS Project -1. If you are opening DevEco Studio for the first time, click **Create Project**. If a project is already open, choose **File** > **New** > **Create Project** from the menu bar. On the **Choose Your Ability Template** page, select **Application** (or **Atomic Service**, depending on your project), select **Empty Ability** as the template, and click **Next**. +The procedure for creating a project varies, depending on whether the API version is later than 9 or not. + +The following describes how to create the OpenHarmony projects of API 10 and API 9. + +### Creating a Project of API Version 10 + +1. If you are opening DevEco Studio for the first time, click **Create Project**. If a project is already open, choose **File** > **New** > **Create Project** from the menu bar. + +2. On the **Choose Your Ability Template** page, select **Application** (or **Atomic Service**, depending on your project), select **Empty Ability** as the template, and click **Next**. ![createProject](figures/createProject.png) -2. On the project configuration page, set **Compile SDK** to **9**, **Model** to **Stage**, and retain the default values for other parameters. +3. On the project configuration page, set **Compile SDK** to **3.1.0(API 9** and retain the default values for other parameters. ![chooseStageModel](figures/chooseStageModel.png) @@ -25,27 +32,102 @@ > On the low-code development pages, you can design your application UI in an efficient, intuitive manner, with a wide array of UI editing features. > > To use the low-code development mode, turn on **Enable Super Visual** on the page shown above. - -3. Click **Finish**. DevEco Studio will automatically generate the sample code and resources that match your project type. Wait until the project is created. -4. After the project is created, in the **entry** > **build-profile.json5** file, change **runtimeOS** under **targets** to **OpenHarmony**, and click **Sync Now** in the upper right corner to start development. +4. Click **Finish**. DevEco Studio will automatically generate the sample code and resources that match your project type. Wait until the project is created. + +5. After the project is created, in the project-level **build-profile.json5** file, move the **compileSdkVersion** and **compatibleSdkVersion** fields from under **app** to under the current **products**. You can identify the current **products** by clicking the ![en-us_image_0000001609333677](figures/en-us_image_0000001609333677.png) icon in the upper right corner of the editing area. + + ![changeToAPI10](figures/changeToAPI10.png) + +6. Change the value of **targetSdkVersion** from **9** to **10** and set **runtimeOS** to **OpenHarmony**. + + ![targetSdkVersion](figures/targetSdkVersion.png) + +7. Delete the **runtimeOS** configuration from the **targets** field in all module-level **build-profile.json5** files. + + ![deleteRuntimeOS](figures/deleteRuntimeOS.png) + +8. Click **Sync Now** and wait until the synchronization is complete. A project of API version 10 is now created. + +### Creating a Project of API Version 9 + +1. If you are opening DevEco Studio for the first time, click **Create Project**. If a project is already open, choose **File** > **New** > **Create Project** from the menu bar. + +2. On the **Choose Your Ability Template** page, select **Application** (or **Atomic Service**, depending on your project), select **Empty Ability** as the template, and click **Next**. + + ![createProject](figures/createProject.png) + +3. On the project configuration page, set **Compile SDK** to **3.1.0(API 9** and retain the default values for other parameters. + + ![chooseStageModel](figures/chooseStageModel.png) + + > **NOTE** + > + > You can use the low-code development mode apart from the traditional coding approach. + > + > On the low-code development pages, you can design your application UI in an efficient, intuitive manner, with a wide array of UI editing features. + > + > To use the low-code development mode, turn on **Enable Super Visual** on the page shown above. + +4. Click **Finish**. DevEco Studio will automatically generate the sample code and resources that match your project type. Wait until the project is created. + +5. In the module-level **entry** > **build-profile.json5** file, set **runtimeOS** in **targets** to **OpenHarmony**. + +6. Click **Sync Now** and wait until the synchronization is complete. A project of API version 9 is now created. + + +## ArkTS Project Directory Structure (Stage Model, API Version 10) + +![en-us_image_0000001364054489](figures/en-us_image_0000001364054489.png) + +- **AppScope > app.json5**: application-level configuration information. + +- **entry**: OpenHarmony project module, which can be built into an OpenHarmony Ability Package ([HAP](../../glossary.md#hap)). + - **src > main > ets**: a collection of ArkTS source code. + + - **src > main > ets > entryability**: entry to your application/service. + + - **src > main > ets > pages**: pages included in your application/service. + + - **src > main > resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files. For details about resource files, see [Resource Categories and Access](resource-categories-and-access.md#resource-categories). + + - **src > main > module.json5**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details, see [module.json5 Configuration File](module-configuration-file.md). + + - **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**. + + - **hvigorfile.ts**: module-level build script. You can customize related tasks and code implementation in this file. + +- **oh_modules**: third-party library dependency information. For details about how to adapt a historical npm project to ohpm, see [Manually Migrating Historical Projects](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/project_overview-0000001053822398-V3#section108143331212). +- **build-profile.json5**: application-level configuration options, including **signingConfigs** and **products**. The **runtimeOS** field in **products** indicates the runtime OS. Its default value is **HarmonyOS**. If you are developing an OpenHarmony application, change the value to **OpenHarmony**. -## ArkTS Project Directory Structure (Stage Model) +- **hvigorfile.ts**: application-level build script. + +## ArkTS Project Directory Structure (Stage Model, API Version 9) ![en-us_image_0000001364054489](figures/en-us_image_0000001364054489.png) -- **AppScope** > **app.json5**: global configuration of your application. +- **AppScope > app.json5**: application-level configuration information. + - **entry**: OpenHarmony project module, which can be built into an OpenHarmony Ability Package ([HAP](../../glossary.md#hap)). - **src > main > ets**: a collection of ArkTS source code. + - **src > main > ets > entryability**: entry to your application/service. + - **src > main > ets > pages**: pages included in your application/service. + - **src > main > resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files. For details about resource files, see [Resource Categories and Access](resource-categories-and-access.md#resource-categories). + - **src > main > module.json5**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details, see [module.json5 Configuration File](module-configuration-file.md). - - **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**. Under **targets**, you can set **runtimeOS** to **HarmonyOS** (default) or **OpenHarmony**, depending on the OS of your application. - - **hvigorfile.ts**: module-level build script. You can customize related tasks and code implementation. + + - **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**. The **runtimeOS** field in **targets** indicates the runtime OS. Its default value is **HarmonyOS**. If you are developing an OpenHarmony application, change the value to **OpenHarmony**. + + - **hvigorfile.ts**: module-level build script. You can customize related tasks and code implementation in this file. + - **oh_modules**: third-party library dependency information. For details about how to adapt a historical npm project to ohpm, see [Manually Migrating Historical Projects](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/project_overview-0000001053822398-V3#section108143331212). -- **build-profile.json5**: application-level configuration information, including the signature and product configuration. + +- **build-profile.json5**: application-level configuration information, including the **signingConfigs** and **products** configuration. + - **hvigorfile.ts**: application-level build script. @@ -127,7 +209,7 @@ ![secondPage](figures/secondPage.png) - > **NOTE** + > **NOTE** > > You can also right-click the **pages** folder and choose **New** > **Page** from the shortcut menu. In this scenario, you do not need to manually configure page routes. - Configure the route for the second page: In the **Project** window, choose **entry** > **src** > **main** > **resources** > **base** > **profile**. In the **main_pages.json** file, set **pages/Second** under **src**. The sample code is as follows: diff --git a/en/application-dev/reference/Readme-EN.md b/en/application-dev/reference/Readme-EN.md index 85bb902ce576919aadc1422f1b8c35f7afd75718..e733f41e92e01a075b3572089134a36a9538dc64 100644 --- a/en/application-dev/reference/Readme-EN.md +++ b/en/application-dev/reference/Readme-EN.md @@ -1,11 +1,13 @@ # Development References + - [SystemCapability](syscap.md) - [SystemCapability List](syscap-list.md) +- [ArkTS API Reference](apis/Readme-EN.md) - [Component Reference (ArkTS-based Declarative Development Paradigm)](arkui-ts/Readme-EN.md) -- [Component Reference (JavaScript-compatible Web-like Development Paradigm)](arkui-js/Readme-EN.md) -- [JS Service Widget UI Component Reference](js-service-widget-ui/Readme-EN.md) -- [API Reference (ArkTS and JS APIs)](apis/Readme-EN.md) +- [Component Reference (JavaScript-compatible Web-like Development Paradigm - ArkUI.Full)](arkui-js/Readme-EN.md) +- [Component Reference (JavaScript-compatible Web-like Development Paradigm - ArkUI.Lite)](arkui-js-lite/Readme-EN.md) +- [JavaScript Service Widget UI Component Reference](js-service-widget-ui/Readme-EN.md) - [Error Codes](errorcodes/Readme-EN.md) -- API Reference (Native APIs) - - [Standard Libraries Supported by Native APIs](native-lib/Readme-EN.md) - +- Native API Reference + - [Native APIs](native-apis/Readme-EN.md) + - [Standard Libraries](native-lib/Readme-EN.md) diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 37bf36f22b5089789f6315e37a18947918501ff4..6bb9b3075d7fd7787a943e44fea8a1968e413551 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -86,8 +86,10 @@ - [AppStateData](js-apis-inner-application-appStateData.md) - [BaseContext](js-apis-inner-application-baseContext.md) - [Context](js-apis-inner-application-context.md) + - [ContinuableInfo](js-apis-inner-application-continuableInfo.md) - [ContinueCallback](js-apis-inner-application-continueCallback.md) - [ContinueDeviceInfo](js-apis-inner-application-continueDeviceInfo.md) + - [ContinueMissionInfo](js-apis-inner-application-continueMissionInfo.md) - [ErrorObserver](js-apis-inner-application-errorObserver.md) - [ExtensionContext](js-apis-inner-application-extensionContext.md) - [ExtensionRunningInfo](js-apis-inner-application-extensionRunningInfo.md) @@ -194,8 +196,7 @@ - [@ohos.router (Page Routing)](js-apis-router.md) - [@ohos.measure (Text Measurement)](js-apis-measure.md) - [@ohos.uiAppearance (UI Appearance)](js-apis-uiappearance.md) - -- Graphics +- Graphics - [@ohos.animation.windowAnimationManager (Window Animation Management)](js-apis-windowAnimationManager.md) - [@ohos.application.WindowExtensionAbility (WindowExtensionAbility)](js-apis-application-windowExtensionAbility.md) - [@ohos.display (Display)](js-apis-display.md) @@ -207,7 +208,6 @@ - webgl - [WebGL](js-apis-webgl.md) - [WebGL2](js-apis-webgl2.md) - - Multimedia - [@ohos.multimedia.audio (Audio Management)](js-apis-audio.md) - [@ohos.multimedia.avsession (AVSession Management)](js-apis-avsession.md) @@ -347,6 +347,7 @@ - [@ohos.brightness (Screen Brightness)](js-apis-brightness.md) - [@ohos.charger (Charging Type)](js-apis-charger.md) - [@ohos.cooperate (Screen Hopping)](js-apis-devicestatus-cooperate.md) + - [@ohos.deviceAttest (Device Attestation)](js-apis-deviceAttest.md) - [@ohos.deviceInfo (Device Information)](js-apis-device-info.md) - [@ohos.distributedHardware.deviceManager (Device Management)](js-apis-device-manager.md) - [@ohos.geoLocationManager (Geolocation Manager)](js-apis-geoLocationManager.md) @@ -356,6 +357,7 @@ - [@ohos.multimodalInput.inputEvent (Input Event)](js-apis-inputevent.md) - [@ohos.multimodalInput.inputEventClient (Key Event Injection)](js-apis-inputeventclient.md) - [@ohos.multimodalInput.inputMonitor (Input Monitor)](js-apis-inputmonitor.md) + - [@ohos.multimodalInput.intentionCode (Intention Code)](js-apis-intentioncode.md) - [@ohos.multimodalInput.keyCode (Key Code)](js-apis-keycode.md) - [@ohos.multimodalInput.keyEvent (Key Event)](js-apis-keyevent.md) - [@ohos.multimodalInput.mouseEvent (Mouse Event)](js-apis-mouseevent.md) @@ -364,6 +366,7 @@ - [@ohos.multimodalInput.shortKey (Shortcut Key)](js-apis-shortKey.md) - [@ohos.power (System Power Management)](js-apis-power.md) - [@ohos.runningLock (Runninglock)](js-apis-runninglock.md) + - [@ohos.resourceschedule.deviceStandby (Device Standby)](js-apis-resourceschedule-deviceStandby.md) - [@ohos.sensor (Sensor)](js-apis-sensor.md) - [@ohos.settings (Data Item Settings)](js-apis-settings.md) - [@ohos.stationary (Device Status Awareness Framework)](js-apis-stationary.md) @@ -378,7 +381,7 @@ - [@ohos.account.appAccount (App Account Management)](js-apis-appAccount.md) - [@ohos.account.distributedAccount (Distributed Account Management)](js-apis-distributed-account.md) - [@ohos.account.osAccount (OS Account Management)](js-apis-osAccount.md) - + - Customization - [@ohos.configPolicy (Configuration Policy)](js-apis-configPolicy.md) @@ -394,7 +397,7 @@ - [@ohos.enterprise.networkManager (Network Management)](js-apis-enterprise-networkManager.md) - [@ohos.enterprise.wifiManager (Wi-Fi Management)](js-apis-enterprise-wifiManager.md) -- Language Base Class Library +- Common Library - [@ohos.buffer (Buffer)](js-apis-buffer.md) - [@ohos.convertxml (XML-to-JavaScript Conversion)](js-apis-convertxml.md) - [@ohos.process (Obtaining Process Information)](js-apis-process.md) @@ -421,7 +424,6 @@ - Test - [@ohos.application.testRunner (TestRunner)](js-apis-application-testRunner.md) - - [@ohos.deviceAttest (Device Attestation)](js-apis-deviceAttest.md) - [@ohos.uitest (UiTest)](js-apis-uitest.md) - APIs No Longer Maintained diff --git a/en/application-dev/reference/apis/commonEventManager-definitions.md b/en/application-dev/reference/apis/commonEventManager-definitions.md index 05f158ad540403b78c11b77bd4f9ca45e6ea651f..f0695d7a98d24babd68c20f0bf554ff916026490 100644 --- a/en/application-dev/reference/apis/commonEventManager-definitions.md +++ b/en/application-dev/reference/apis/commonEventManager-definitions.md @@ -13,50 +13,32 @@ Indicates that the user has finished the boot process. - Value: **usual.event.LOCKED_BOOT_COMPLETED** - Required subscriber permissions: ohos.permission.RECEIVER_STARTUP_COMPLETED -## COMMON_EVENT_SHUTDOWN +## [COMMON_EVENT_SHUTDOWN](./common_event/commonEvent-powermgr.md) Indicates that the device is being shut down and the final shutdown will proceed. -- Value: **usual.event.SHUTDOWN** -- Required subscriber permissions: none -## COMMON_EVENT_BATTERY_CHANGED +## [COMMON_EVENT_BATTERY_CHANGED](./common_event/commonEvent-powermgr.md) Indicates that the charging state, level, and other information about the battery have changed. -- Value: **usual.event.BATTERY_CHANGED** -- Required subscriber permissions: none -## COMMON_EVENT_BATTERY_LOW +## [COMMON_EVENT_BATTERY_LOW](./common_event/commonEvent-powermgr.md) Indicates that the battery level is low. -- Value: **usual.event.BATTERY_LOW** -- Required subscriber permissions: none -## COMMON_EVENT_BATTERY_OKAY +## [COMMON_EVENT_BATTERY_OKAY](./common_event/commonEvent-powermgr.md) Indicates that the battery level is normal. -- Value: **usual.event.BATTERY_OKAY** -- Required subscriber permissions: none -## COMMON_EVENT_POWER_CONNECTED +## [COMMON_EVENT_POWER_CONNECTED](./common_event/commonEvent-powermgr.md) Indicates that the device is connected to an external power supply. -- Value: **usual.event.POWER_CONNECTED** -- Required subscriber permissions: none -## COMMON_EVENT_POWER_DISCONNECTED +## [COMMON_EVENT_POWER_DISCONNECTED](./common_event/commonEvent-powermgr.md) Indicates that the device is disconnected from the external power supply. -- Value: **usual.event.POWER_DISCONNECTED** -- Required subscriber permissions: none -## COMMON_EVENT_SCREEN_OFF +## [COMMON_EVENT_SCREEN_OFF](./common_event/commonEvent-powermgr.md) Indicates that the device screen is off and the device is in sleep mode. -- Value: **usual.event.SCREEN_OFF** -- Required subscriber permissions: none -## COMMON_EVENT_SCREEN_ON -Indicates that the device screen is on and the device is in interactive state. -- Value: **usual.event.SCREEN_ON** -- Required subscriber permissions: none +## [COMMON_EVENT_SCREEN_ON](./common_event/commonEvent-powermgr.md) +Indicates that the device screen is on and the device is in the active state. -## COMMON_EVENT_THERMAL_LEVEL_CHANGED8+ +## [COMMON_EVENT_THERMAL_LEVEL_CHANGED](./common_event/commonEvent-powermgr.md) Indicates that the device's thermal level has changed. -- Value: **usual.event.THERMAL_LEVEL_CHANGED** -- Required subscriber permissions: none ## COMMON_EVENT_USER_PRESENT(deprecated) (Reserved, not supported yet) Indicates that the user unlocks the device. @@ -65,37 +47,29 @@ Indicates that the device's thermal level has changed. > NOTE > > This API is deprecated since API version 10. +> You are advised to use [COMMON_EVENT_SCREEN_UNLOCKED10+](./common_event/commonEvent-screenlock.md) instead. -## COMMON_EVENT_TIME_TICK +## [COMMON_EVENT_TIME_TICK](./common_event/commonEvent-time.md) Indicates that the system time has changed as time ticks by. -- Value: **usual.event.TIME_TICK** -- Required subscriber permissions: none -## COMMON_EVENT_TIME_CHANGED +## [COMMON_EVENT_TIME_CHANGED](./common_event/commonEvent-time.md) Indicates that the system time is set. -- Value: **usual.event.TIME_CHANGED** -- Required subscriber permissions: none ## COMMON_EVENT_DATE_CHANGED (Reserved, not supported yet) Indicates that the system date has changed. - Value: **usual.event.DATE_CHANGED** - Required subscriber permissions: none -## COMMON_EVENT_TIMEZONE_CHANGED +## [COMMON_EVENT_TIMEZONE_CHANGED](./common_event/commonEvent-time.md) Indicates that the system time zone has changed. -- Value: **usual.event.TIMEZONE_CHANGED** -- Required subscriber permissions: none ## COMMON_EVENT_CLOSE_SYSTEM_DIALOGS (Reserved, not supported yet) Indicates that the user closes a temporary system dialog box. - Value: **usual.event.CLOSE_SYSTEM_DIALOGS** - Required subscriber permissions: none -## COMMON_EVENT_PACKAGE_ADDED +## [COMMON_EVENT_PACKAGE_ADDED](./common_event/commonEvent-bundleManager.md) Indicates that a new application package has been installed on the device. -- Value: **usual.event.PACKAGE_ADDED** -- Required subscriber permissions: none - ## COMMON_EVENT_PACKAGE_REPLACED (Reserved, not supported yet) Indicates that a later version of an installed application package has replaced the previous one on the device. - Value: **usual.event.PACKAGE_REPLACED** @@ -106,11 +80,8 @@ Indicates that a new application package has been installed on the device. - Value: **usual.event.MY_PACKAGE_REPLACED** - Required subscriber permissions: none -## COMMON_EVENT_PACKAGE_REMOVED +## [COMMON_EVENT_PACKAGE_REMOVED](./common_event/commonEvent-bundleManager.md) Indicates that an installed application has been uninstalled from the device with the application data retained. -- Value: **usual.event.PACKAGE_REMOVED** -- Required subscriber permissions: none - ## COMMON_EVENT_BUNDLE_REMOVED (Reserved, not supported yet) Indicates that an installed bundle has been uninstalled from the device with the application data retained. - Value: **usual.event.BUNDLE_REMOVED** @@ -121,22 +92,16 @@ Indicates that an installed application has been uninstalled from the device wit - Value: **usual.event.PACKAGE_FULLY_REMOVED** - Required subscriber permissions: none -## COMMON_EVENT_PACKAGE_CHANGED +## [COMMON_EVENT_PACKAGE_CHANGED](./common_event/commonEvent-bundleManager.md) Indicates that an application package has been changed (for example, an ability in the package has been enabled or disabled). -- Value: **usual.event.PACKAGE_CHANGED** -- Required subscriber permissions: none - ## [COMMON_EVENT_PACKAGE_RESTARTED](./common_event/commonEvent-ability.md) Indicates that the user closed all processes of the application and restarted the application. ## [COMMON_EVENT_PACKAGE_DATA_CLEARED](./common_event/commonEvent-ability.md) Indicates that the user cleared the application package data. -## COMMON_EVENT_PACKAGE_CACHE_CLEARED9+ +## [COMMON_EVENT_PACKAGE_CACHE_CLEARED9+](./common_event/commonEvent-bundleManager.md) Indicates that the user cleared the application package cache. -- Value: **usual.event.PACKAGE_CACHE_CLEARED** -- Required subscriber permissions: none - ## COMMON_EVENT_PACKAGES_SUSPENDED (Reserved, not supported yet) Indicates that application HAP files are suspended. - Value: **usual.event.PACKAGES_SUSPENDED** @@ -177,7 +142,6 @@ Indicates that an application HAP file is not suspended. - Value: **usual.event.PACKAGE_VERIFIED** - Required subscriber permissions: none - ## COMMON_EVENT_EXTERNAL_APPLICATIONS_AVAILABLE (Reserved, not supported yet) Indicates that applications installed on the external storage are available for the system. - Value: **usual.event.EXTERNAL_APPLICATIONS_AVAILABLE** @@ -233,11 +197,8 @@ Indicates that an application HAP file is not suspended. - Value: **usual.event.USER_FOREGROUND** - Required subscriber permissions: none -## COMMON_EVENT_USER_SWITCHED +## [COMMON_EVENT_USER_SWITCHED](./common_event/commonEvent-account.md) Indicates that user switching is in progress. -- Value: **usual.event.USER_SWITCHED** -- Required subscriber permissions: ohos.permission.MANAGE_LOCAL_ACCOUNTS - ## COMMON_EVENT_USER_STARTING (Reserved, not supported yet) Indicates that the user is being started. - Value: **usual.event.USER_STARTING** @@ -258,466 +219,335 @@ Indicates that user switching is in progress. - Value: **usual.event.USER_STOPPED** - Required subscriber permissions: none -## COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGIN +## [COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGIN](./common_event/commonEvent-account.md) (Reserved, not supported yet) Indicates a successful login to a distributed account. -- Value: **usual.event.DISTRIBUTED_ACCOUNT_LOGIN** -- Required subscriber permissions: none - -## COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOUT +## [COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOUT](./common_event/commonEvent-account.md) (Reserved, not supported yet) Indicates a successful logout of a distributed account. -- Value: **usual.event.DISTRIBUTED_ACCOUNT_LOGOUT** -- Required subscriber permissions: none - -## COMMON_EVENT_DISTRIBUTED_ACCOUNT_TOKEN_INVALID +## [COMMON_EVENT_DISTRIBUTED_ACCOUNT_TOKEN_INVALID](./common_event/commonEvent-account.md) (Reserved, not supported yet) Indicates the token of a distributed account is invalid. -- Value: **usual.event.DISTRIBUTED_ACCOUNT_TOKEN_INVALID** -- Required subscriber permissions: none - -## COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOFF +## [COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOFF](./common_event/commonEvent-account.md) (Reserved, not supported yet) Indicates that a distributed account is deregistered. -- Value: **usual.event.DISTRIBUTED_ACCOUNT_LOGOFF** -- Required subscriber permissions: none -## COMMON_EVENT_WIFI_POWER_STATE +## [COMMON_EVENT_WIFI_POWER_STATE](./common_event/commonEvent-wifi.md) Indicates that the Wi-Fi state has changed, for example, enabled or disabled. -- Value: **usual.event.wifi.POWER_STATE** -- Required subscriber permissions: none - -## COMMON_EVENT_WIFI_SCAN_FINISHED +## [COMMON_EVENT_WIFI_SCAN_FINISHED](./common_event/commonEvent-wifi.md) Indicates that the Wi-Fi access point has been detected and proven to be available. -- Value: **usual.event.wifi.SCAN_FINISHED** -- Required subscriber permissions: ohos.permission.LOCATION +## [COMMON_EVENT_WIFI_SCAN_STATE](./common_event/commonEvent-wifi.md) +Indicates that the Wi-Fi access point state has changed. -## COMMON_EVENT_WIFI_RSSI_VALUE +## [COMMON_EVENT_WIFI_RSSI_VALUE](./common_event/commonEvent-wifi.md) Indicates that the Wi-Fi signal strength (RSSI) has changed. -- Value: **usual.event.wifi.RSSI_VALUE** -- Required subscriber permissions: ohos.permission.GET_WIFI_INFO - -## COMMON_EVENT_WIFI_CONN_STATE +## [COMMON_EVENT_WIFI_CONN_STATE](./common_event/commonEvent-wifi.md) Indicates that the Wi-Fi connection state has changed. -- Value: **usual.event.wifi.CONN_STATE** -- Required subscriber permissions: none - -## COMMON_EVENT_WIFI_HOTSPOT_STATE +## [COMMON_EVENT_WIFI_HOTSPOT_STATE](./common_event/commonEvent-wifi.md) Indicates that the Wi-Fi hotspot state has changed, for example, enabled or disabled. -- Value: **usual.event.wifi.HOTSPOT_STATE** -- Required subscriber permissions: none - -## COMMON_EVENT_WIFI_AP_STA_JOIN +## [COMMON_EVENT_WIFI_AP_STA_JOIN](./common_event/commonEvent-wifi.md) Indicates that a client has joined the Wi-Fi hotspot of the current device. -- Value: **usual.event.wifi.WIFI_HS_STA_JOIN** -- Required subscriber permissions: ohos.permission.GET_WIFI_INFO - -## COMMON_EVENT_WIFI_AP_STA_LEAVE +## [COMMON_EVENT_WIFI_AP_STA_LEAVE](./common_event/commonEvent-wifi.md) Indicates that a client has disconnected from the Wi-Fi hotspot of the current device. -- Value: **usual.event.wifi.WIFI_HS_STA_LEAVE** -- Required subscriber permissions: ohos.permission.GET_WIFI_INFO - -## COMMON_EVENT_WIFI_MPLINK_STATE_CHANGE +## [COMMON_EVENT_WIFI_MPLINK_STATE_CHANGE](./common_event/commonEvent-wifi.md) Indicates that the state of MPLINK (an enhanced Wi-Fi feature) has changed. -- Value: **usual.event.wifi.mplink.STATE_CHANGE** -- Required subscriber permissions: ohos.permission.MPLINK_CHANGE_STATE - -## COMMON_EVENT_WIFI_P2P_CONN_STATE +## [COMMON_EVENT_WIFI_P2P_CONN_STATE](./common_event/commonEvent-wifi.md) Indicates that the Wi-Fi P2P connection state has changed. -- Value: **usual.event.wifi.p2p.CONN_STATE_CHANGE** -- Required subscriber permissions: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION - -## COMMON_EVENT_WIFI_P2P_STATE_CHANGED +## [COMMON_EVENT_WIFI_P2P_STATE_CHANGED](./common_event/commonEvent-wifi.md) Indicates that the Wi-Fi P2P state has changed, for example, enabled or disabled. -- Value: **usual.event.wifi.p2p.STATE_CHANGE** -- Required subscriber permissions: ohos.permission.GET_WIFI_INFO - -## COMMON_EVENT_WIFI_P2P_PEERS_STATE_CHANGED +## [COMMON_EVENT_WIFI_P2P_PEERS_STATE_CHANGED](./common_event/commonEvent-wifi.md) Indicates that the state of the Wi-Fi P2P peer device has changed. -- Value: **usual.event.wifi.p2p.DEVICES_CHANGE** -- Required subscriber permissions: ohos.permission.GET_WIFI_INFO - -## COMMON_EVENT_WIFI_P2P_PEERS_DISCOVERY_STATE_CHANGED +## [COMMON_EVENT_WIFI_P2P_PEERS_DISCOVERY_STATE_CHANGED](./common_event/commonEvent-wifi.md) Indicates that the Wi-Fi P2P discovery state has changed. -- Value: **usual.event.wifi.p2p.PEER_DISCOVERY_STATE_CHANGE** -- Required subscriber permissions: ohos.permission.GET_WIFI_INFO - -## COMMON_EVENT_WIFI_P2P_CURRENT_DEVICE_STATE_CHANGED +## [COMMON_EVENT_WIFI_P2P_CURRENT_DEVICE_STATE_CHANGED](./common_event/commonEvent-wifi.md) Indicates that the state of the Wi-Fi P2P local device has changed. -- Value: **usual.event.wifi.p2p.CURRENT_DEVICE_CHANGE** -- Required subscriber permissions: ohos.permission.GET_WIFI_INFO - -## COMMON_EVENT_WIFI_P2P_GROUP_STATE_CHANGED +## [COMMON_EVENT_WIFI_P2P_GROUP_STATE_CHANGED](./common_event/commonEvent-wifi.md) Indicates that the Wi-Fi P2P group information has changed. -- Value: **usual.event.wifi.p2p.GROUP_STATE_CHANGED** -- Required subscriber permissions: ohos.permission.GET_WIFI_INFO - ## COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CONNECT_STATE_UPDATE (Reserved, not supported yet) Indicates the connection state of Bluetooth handsfree communication. - Value: **usual.event.bluetooth.handsfree.ag.CONNECT_STATE_UPDATE** - Required subscriber permissions: ohos.permission.USE_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CURRENT_DEVICE_UPDATE (Reserved, not supported yet) Indicates that the device connected through Bluetooth handsfree is active. - Value: **usual.event.bluetooth.handsfree.ag.CURRENT_DEVICE_UPDATE** - Required subscriber permissions: ohos.permission.USE_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_AUDIO_STATE_UPDATE (Reserved, not supported yet) Indicates that the connection state of Bluetooth A2DP has changed. - Value: **usual.event.bluetooth.handsfree.ag.AUDIO_STATE_UPDATE** - Required subscriber permissions: ohos.permission.USE_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CONNECT_STATE_UPDATE (Reserved, not supported yet) Indicates the connection state of Bluetooth A2DP. - Value: **usual.event.bluetooth.a2dpsource.CONNECT_STATE_UPDATE** - Required subscriber permissions: ohos.permission.USE_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CURRENT_DEVICE_UPDATE (Reserved, not supported yet) Indicates that the device connected using Bluetooth A2DP is active. - Value: **usual.event.bluetooth.a2dpsource.CURRENT_DEVICE_UPDATE** - Required subscriber permissions: ohos.permission.USE_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_A2DPSOURCE_PLAYING_STATE_UPDATE (Reserved, not supported yet) Indicates that the playing state of Bluetooth A2DP has changed. - Value: **usual.event.bluetooth.a2dpsource.PLAYING_STATE_UPDATE** - Required subscriber permissions: ohos.permission.USE_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_A2DPSOURCE_AVRCP_CONNECT_STATE_UPDATE (Reserved, not supported yet) Indicates that the AVRCP connection state of Bluetooth A2DP has changed. - Value: **usual.event.bluetooth.a2dpsource.AVRCP_CONNECT_STATE_UPDATE** - Required subscriber permissions: ohos.permission.USE_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CODEC_VALUE_UPDATE (Reserved, not supported yet) Indicates that the audio codec state of Bluetooth A2DP has changed. - Value: **usual.event.bluetooth.a2dpsource.CODEC_VALUE_UPDATE** - Required subscriber permissions: ohos.permission.USE_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_DISCOVERED (Reserved, not supported yet) Indicates that a remote Bluetooth device is discovered. - Value: **usual.event.bluetooth.remotedevice.DISCOVERED** - Required subscriber permissions: ohos.permission.LOCATION and ohos.permission.USE_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CLASS_VALUE_UPDATE (Reserved, not supported yet) Indicates that the Bluetooth class of a remote Bluetooth device has changed. - Value: **usual.event.bluetooth.remotedevice.CLASS_VALUE_UPDATE** - Required subscriber permissions: ohos.permission.USE_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_CONNECTED (Reserved, not supported yet) Indicates that a low-ACL connection with a remote Bluetooth device has been established. - Value: **usual.event.bluetooth.remotedevice.ACL_CONNECTED** -- Required subscriber permissions: ohos.permission.USE_BLUETOOTH - +- Required subscriber permissions: none ## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_DISCONNECTED (Reserved, not supported yet) Indicates that the low-ACL connection with a remote Bluetooth device has been terminated. - Value: **usual.event.bluetooth.remotedevice.ACL_DISCONNECTED** - Required subscriber permissions: ohos.permission.USE_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_NAME_UPDATE (Reserved, not supported yet) Indicates that the friendly name of a remote Bluetooth device is retrieved for the first time or has changed since the last retrieval. - Value: **usual.event.bluetooth.remotedevice.NAME_UPDATE** - Required subscriber permissions: ohos.permission.USE_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIR_STATE (Reserved, not supported yet) Indicates that the connection state with a remote Bluetooth device has changed. - Value: **usual.event.bluetooth.remotedevice.PAIR_STATE** - Required subscriber permissions: ohos.permission.USE_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_BATTERY_VALUE_UPDATE (Reserved, not supported yet) Indicates that the battery level of a remote Bluetooth device is retrieved for the first time or has changed since the last retrieval. - Value: **usual.event.bluetooth.remotedevice.BATTERY_VALUE_UPDATE** - Required subscriber permissions: ohos.permission.USE_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_SDP_RESULT (Reserved, not supported yet) Indicates the SDP state of a remote Bluetooth device. - Value: **usual.event.bluetooth.remotedevice.SDP_RESULT** - Required subscriber permissions: none - ## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_UUID_VALUE (Reserved, not supported yet) Indicates the UUID connection state with a remote Bluetooth device. - Value: **usual.event.bluetooth.remotedevice.UUID_VALUE** - Required subscriber permissions: ohos.permission.DISCOVER_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_REQ (Reserved, not supported yet) Indicates the pairing request from a remote Bluetooth device. - Value: **usual.event.bluetooth.remotedevice.PAIRING_REQ** - Required subscriber permissions: ohos.permission.DISCOVER_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_CANCEL (Reserved, not supported yet) Indicates that Bluetooth pairing has been canceled. - Value: **usual.event.bluetooth.remotedevice.PAIRING_CANCEL** - Required subscriber permissions: none - ## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REQ (Reserved, not supported yet) Indicates the connection request from a remote Bluetooth device. - Value: **usual.event.bluetooth.remotedevice.CONNECT_REQ** - Required subscriber permissions: none - ## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REPLY (Reserved, not supported yet) Indicates the response to the connection request from a remote Bluetooth device. - Value: **usual.event.bluetooth.remotedevice.CONNECT_REPLY** - Required subscriber permissions: none - ## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_CANCEL (Reserved, not supported yet) Indicates that the connection to a remote Bluetooth device has been canceled. - Value: **usual.event.bluetooth.remotedevice.CONNECT_CANCEL** - Required subscriber permissions: none - ## COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_CONNECT_STATE_UPDATE (Reserved, not supported yet) Indicates that the connection state with a Bluetooth handsfree has changed. - Value: **usual.event.bluetooth.handsfreeunit.CONNECT_STATE_UPDATE** - Required subscriber permissions: none - ## COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AUDIO_STATE_UPDATE (Reserved, not supported yet) Indicates that the audio state of a Bluetooth handsfree has changed. - Value: **usual.event.bluetooth.handsfreeunit.AUDIO_STATE_UPDATE** - Required subscriber permissions: none - ## COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_COMMON_EVENT (Reserved, not supported yet) Indicates that the audio gateway state of a Bluetooth handsfree has changed. - Value: **usual.event.bluetooth.handsfreeunit.AG_COMMON_EVENT** - Required subscriber permissions: none - ## COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_CALL_STATE_UPDATE (Reserved, not supported yet) Indicates that the calling state of a Bluetooth handsfree has changed. - Value: **usual.event.bluetooth.handsfreeunit.AG_CALL_STATE_UPDATE** - Required subscriber permissions: none - ## COMMON_EVENT_BLUETOOTH_HOST_STATE_UPDATE (Reserved, not supported yet) Indicates that the state of a Bluetooth adapter has changed, for example, Bluetooth has been enabled or disabled. - Value: **usual.event.bluetooth.host.STATE_UPDATE** - Required subscriber permissions: ohos.permission.USE_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_HOST_REQ_DISCOVERABLE (Reserved, not supported yet) Indicates the request for the user to allow Bluetooth device scanning. - Value: **usual.event.bluetooth.host.REQ_DISCOVERABLE** - Required subscriber permissions: none - ## COMMON_EVENT_BLUETOOTH_HOST_REQ_ENABLE (Reserved, not supported yet) Indicates the request for the user to enable Bluetooth. - Value: **usual.event.bluetooth.host.REQ_ENABLE** - Required subscriber permissions: ohos.permission.USE_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_HOST_REQ_DISABLE (Reserved, not supported yet) Indicates the request for the user to disable Bluetooth. - Value: **usual.event.bluetooth.host.REQ_DISABLE** - Required subscriber permissions: ohos.permission.USE_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_HOST_SCAN_MODE_UPDATE (Reserved, not supported yet) Indicates that the Bluetooth scanning mode of the device has changed. - Value: **usual.event.bluetooth.host.SCAN_MODE_UPDATE** - Required subscriber permissions: ohos.permission.USE_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_STARTED (Reserved, not supported yet) Indicates that Bluetooth scanning has been started on the device. - Value: **usual.event.bluetooth.host.DISCOVERY_STARTED** - Required subscriber permissions: ohos.permission.USE_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_FINISHED (Reserved, not supported yet) Indicates that Bluetooth scanning is finished on the device. - Value: **usual.event.bluetooth.host.DISCOVERY_FINISHED** - Required subscriber permissions: ohos.permission.USE_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_HOST_NAME_UPDATE (Reserved, not supported yet) Indicates that the Bluetooth adapter name of the device has changed. - Value: **usual.event.bluetooth.host.NAME_UPDATE** - Required subscriber permissions: ohos.permission.USE_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_A2DPSINK_CONNECT_STATE_UPDATE (Reserved, not supported yet) Indicates that the connection state of Bluetooth A2DP Sink has changed. - Value: **usual.event.bluetooth.a2dpsink.CONNECT_STATE_UPDATE** - Required subscriber permissions: ohos.permission.USE_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_A2DPSINK_PLAYING_STATE_UPDATE (Reserved, not supported yet) Indicates that the playing state of Bluetooth A2DP Sink has changed. - Value: **usual.event.bluetooth.a2dpsink.PLAYING_STATE_UPDATE** - Required subscriber permissions: ohos.permission.USE_BLUETOOTH - ## COMMON_EVENT_BLUETOOTH_A2DPSINK_AUDIO_STATE_UPDATE (Reserved, not supported yet) Indicates that the audio state of Bluetooth A2DP Sink has changed. - Value: **usual.event.bluetooth.a2dpsink.AUDIO_STATE_UPDATE** - Required subscriber permissions: ohos.permission.USE_BLUETOOTH +## [COMMON_EVENT_NFC_ACTION_ADAPTER_STATE_CHANGED](./common_event/commonEvent-nfc.md) +Indicates that the state of the device NFC adapter has changed. -## COMMON_EVENT_NFC_ACTION_ADAPTER_STATE_CHANGED -(Reserved, not supported yet) Indicates that the state of the device NFC adapter has changed. -- Value: **usual.event.nfc.action.ADAPTER_STATE_CHANGED** -- Required subscriber permissions: none - - -## COMMON_EVENT_NFC_ACTION_RF_FIELD_ON_DETECTED -(Reserved, not supported yet) Indicates that the NFC RF field is detected to be in the enabled state. -- Value: **usual.event.nfc.action.RF_FIELD_ON_DETECTED** -- Required subscriber permissions: ohos.permission.MANAGE_SECURE_SETTINGS - +## [COMMON_EVENT_NFC_ACTION_RF_FIELD_ON_DETECTED](./common_event/commonEvent-nfc.md) +Indicates that the NFC RF field is on. -## COMMON_EVENT_NFC_ACTION_RF_FIELD_OFF_DETECTED -(Reserved, not supported yet) Indicates that the NFC RF field is detected to be in the disabled state. -- Value: **usual.event.nfc.action.RF_FIELD_OFF_DETECTED** -- Required subscriber permissions: ohos.permission.MANAGE_SECURE_SETTINGS +## [COMMON_EVENT_NFC_ACTION_RF_FIELD_OFF_DETECTED](./common_event/commonEvent-nfc.md) +Indicates that the NFC RF field is off. - -## COMMON_EVENT_DISCHARGING +## [COMMON_EVENT_DISCHARGING](./common_event/commonEvent-powermgr.md) Indicates that the system stops charging the battery. -- Value: **usual.event.DISCHARGING** -- Required subscriber permissions: none - -## COMMON_EVENT_CHARGING +## [COMMON_EVENT_CHARGING](./common_event/commonEvent-powermgr.md) Indicates that the system starts charging the battery. -- Value: **usual.event.CHARGING** -- Required subscriber permissions: none -## COMMON_EVENT_CHARGE_TYPE_CHANGED +## [COMMON_EVENT_CHARGE_TYPE_CHANGED](./common_event/commonEvent-powermgr.md) Indicates that the system charging type has changed. This event is available only for system applications. -- Value: **usual.event.CHARGE_TYPE_CHANGED** -- Required subscriber permissions: none ## [COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED](./common_event/commonEvent-resourceschedule.md) -(Reserved, not supported yet) Indicates that the system idle mode has changed. -- Value: **usual.event.DEVICE_IDLE_MODE_CHANGED** -- Required subscriber permissions: none - +Indicates that the system idle mode has changed. ## [COMMON_EVENT_DEVICE_IDLE_EXEMPTION_LIST_UPDATED10+](./common_event/commonEvent-resourceschedule.md) Indicates that the exemption list for resource usage restrictions has been updated in idle mode. This event is for system applications only. -- Value: **usual.event.DEVICE_IDLE_EXEMPTION_LIST_UPDATED** -- Required subscriber permissions: none -## COMMON_EVENT_POWER_SAVE_MODE_CHANGED +## [COMMON_EVENT_POWER_SAVE_MODE_CHANGED](./common_event/commonEvent-powermgr.md) Indicates that the system power saving mode has changed. -- Value: **usual.event.POWER_SAVE_MODE_CHANGED** -- Required subscriber permissions: none - -## COMMON_EVENT_USER_ADDED +## [COMMON_EVENT_USER_ADDED](./common_event/commonEvent-account.md) Indicates that a user has been added to the system. -- Value: **usual.event.USER_ADDED** -- Required subscriber permissions: ohos.permission.MANAGE_LOCAL_ACCOUNTS - - -## COMMON_EVENT_USER_REMOVED +## [COMMON_EVENT_USER_REMOVED](./common_event/commonEvent-account.md) Indicates that a user has been removed from the system. -- Value: **usual.event.USER_REMOVED** -- Required subscriber permissions: ohos.permission.MANAGE_LOCAL_ACCOUNTS - - ## COMMON_EVENT_ABILITY_ADDED (Reserved, not supported yet) Indicates that an ability has been added. - Value: **usual.event.ABILITY_ADDED** - Required subscriber permissions: ohos.permission.LISTEN_BUNDLE_CHANGE - ## COMMON_EVENT_ABILITY_REMOVED (Reserved, not supported yet) Indicates that an ability has been removed. - Value: **usual.event.ABILITY_REMOVED** - Required subscriber permissions: ohos.permission.LISTEN_BUNDLE_CHANGE - ## COMMON_EVENT_ABILITY_UPDATED (Reserved, not supported yet) Indicates that an ability has been updated. - Value: **usual.event.ABILITY_UPDATED** - Required subscriber permissions: ohos.permission.LISTEN_BUNDLE_CHANGE - ## COMMON_EVENT_LOCATION_MODE_STATE_CHANGED (Reserved, not supported yet) Indicates that the location mode of the system has changed. - Value: **usual.event.location.MODE_STATE_CHANGED** - Required subscriber permissions: none - ## COMMON_EVENT_IVI_SLEEP (Reserved, not supported yet) Indicates that the in-vehicle infotainment (IVI) system is in sleep mode. - Value: **common.event.IVI_SLEEP** - Required subscriber permissions: none - ## COMMON_EVENT_IVI_PAUSE (Reserved, not supported yet) Indicates that the IVI system as entered sleep mode and instructs the playing application to stop playback. - Value: **common.event.IVI_PAUSE** - Required subscriber permissions: none - ## COMMON_EVENT_IVI_STANDBY (Reserved, not supported yet) Requests a third-party application in the IVI system to pause the current work. - Value: **common.event.IVI_STANDBY** - Required subscriber permissions: none - ## COMMON_EVENT_IVI_LASTMODE_SAVE (Reserved, not supported yet) Requests a third-party application in the IVI system to save its last mode. - Value: **common.event.IVI_LASTMODE_SAVE** - Required subscriber permissions: none - ## COMMON_EVENT_IVI_VOLTAGE_ABNORMAL (Reserved, not supported yet) Indicates that the voltage of the vehicle's power system is abnormal. - Value: **common.event.IVI_VOLTAGE_ABNORMAL** - Required subscriber permissions: none - ## COMMON_EVENT_IVI_HIGH_TEMPERATURE (Reserved, not supported yet) Indicates that the temperature of the IVI system is high. - Value: **common.event.IVI_HIGH_TEMPERATURE** - Required subscriber permissions: none - ## COMMON_EVENT_IVI_EXTREME_TEMPERATURE (Reserved, not supported yet) Indicates that the temperature of the IVI system is extremely high. - Value: **common.event.IVI_EXTREME_TEMPERATURE** - Required subscriber permissions: none - ## COMMON_EVENT_IVI_TEMPERATURE_ABNORMAL (Reserved, not supported yet) Indicates that the IVI system is at an extreme temperature. - Value: **common.event.IVI_TEMPERATURE_ABNORMAL** - Required subscriber permissions: none - ## COMMON_EVENT_IVI_VOLTAGE_RECOVERY (Reserved, not supported yet) Indicates that the voltage of the vehicle's power system is restored to normal. - Value: **common.event.IVI_VOLTAGE_RECOVERY** @@ -733,36 +563,24 @@ Indicates that a user has been removed from the system. - Value: **common.event.IVI_ACTIVE** - Required subscriber permissions: none -## COMMON_EVENT_USB_STATE9+ +## [COMMON_EVENT_USB_STATE9+](common_event/commonEvent-usb.md) Indicates that the USB device state has changed. -For details, see [Common Events of the USB Subsystem](common_event/commonEvent-usb.md). - -## COMMON_EVENT_USB_PORT_CHANGED9+ +## [**COMMON_EVENT_USB_PORT_CHANGED**9+](./common_event/commonEvent-usb.md) Indicates that the USB port state of the device has changed. -For details, see [Common Events of the USB Subsystem](common_event/commonEvent-usb.md). - -## COMMON_EVENT_USB_DEVICE_ATTACHED +## [COMMON_EVENT_USB_DEVICE_ATTACHED](./common_event/commonEvent-usb.md) Indicates that a USB device has been attached to the device functioning as a USB host. -For details, see [Common Events of the USB Subsystem](common_event/commonEvent-usb.md). - -## COMMON_EVENT_USB_DEVICE_DETACHED +## [COMMON_EVENT_USB_DEVICE_DETACHED](./common_event/commonEvent-usb.md) Indicates that a USB device has been detached from the device functioning as a USB host. -For details, see [Common Events of the USB Subsystem](common_event/commonEvent-usb.md). - -## COMMON_EVENT_USB_ACCESSORY_ATTACHED +## [COMMON_EVENT_USB_ACCESSORY_ATTACHED](./common_event/commonEvent-usb.md) (Reserved, not supported yet) Indicates that a USB accessory was attached. -For details, see [Common Events of the USB Subsystem](common_event/commonEvent-usb.md). - -## COMMON_EVENT_USB_ACCESSORY_DETACHED +## [COMMON_EVENT_USB_ACCESSORY_DETACHED](./common_event/commonEvent-usb.md) (Reserved, not supported yet) Indicates that a USB accessory was detached. -For details, see [Common Events of the USB Subsystem](common_event/commonEvent-usb.md). - ## COMMON_EVENT_DISK_REMOVED (Reserved, not supported yet) Indicates that an external storage device was removed. - Value: **usual.event.data.DISK_BAD_REMOVAL** @@ -773,13 +591,11 @@ For details, see [Common Events of the USB Subsystem](common_event/commonEvent-u - Value: **usual.event.data.DISK_UNMOUNTABLE** - Required subscriber permissions: ohos.permission.STORAGE_MANAGER - ## COMMON_EVENT_DISK_MOUNTED (Reserved, not supported yet) Indicates that an external storage device was mounted. - Value: **usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED** - Required subscriber permissions: ohos.permission.STORAGE_MANAGER - ## COMMON_EVENT_DISK_BAD_REMOVAL (Reserved, not supported yet) Indicates that an external storage device was removed without being unmounted. - Value: usual.event.data.DISK_REMOVED @@ -795,30 +611,20 @@ For details, see [Common Events of the USB Subsystem](common_event/commonEvent-u - Value: **usual.event.data.DISK_EJECT** - Required subscriber permissions: ohos.permission.STORAGE_MANAGER -## COMMON_EVENT_VOLUME_REMOVED9+ +## [COMMON_EVENT_VOLUME_REMOVED9+](./common_event/commonEvent-filemanagement.md) Indicates that an external storage device was removed. -- Value: **usual.event.data.VOLUME_REMOVED** -- Required subscriber permissions: ohos.permission.STORAGE_MANAGER -## COMMON_EVENT_VOLUME_UNMOUNTED9+ +## [COMMON_EVENT_VOLUME_UNMOUNTED9+](./common_event/commonEvent-filemanagement.md) Indicates that an external storage device was unmounted. -- Value: **usual.event.data.VOLUME_UNMOUNTED** -- Required subscriber permissions: ohos.permission.STORAGE_MANAGER -## COMMON_EVENT_VOLUME_MOUNTED9+ +## [COMMON_EVENT_VOLUME_MOUNTED9+](./common_event/commonEvent-filemanagement.md) Indicates that an external storage device was mounted. -- Value: **usual.event.data.VOLUME_MOUNTED** -- Required subscriber permissions: ohos.permission.STORAGE_MANAGER -## COMMON_EVENT_VOLUME_BAD_REMOVAL9+ +## [COMMON_EVENT_VOLUME_BAD_REMOVAL9+](./common_event/commonEvent-filemanagement.md) Indicates that an external storage device was removed without being unmounted. -- Value: **usual.event.data.VOLUME_BAD_REMOVAL** -- Required subscriber permissions: ohos.permission.STORAGE_MANAGER -## COMMON_EVENT_VOLUME_EJECT9+ +## [COMMON_EVENT_VOLUME_EJECT9+](./common_event/commonEvent-filemanagement.md) Indicates that an external storage device was ejected (at the software level). -- Value: usual.event.data.VOLUME_EJECT -- Required subscriber permissions: ohos.permission.STORAGE_MANAGER ## COMMON_EVENT_VISIBLE_ACCOUNTS_UPDATED (Reserved, not supported yet) Indicates that the account visibility changed. @@ -845,11 +651,8 @@ Indicates that the screen has been split. - Value: **usual.event.SPLIT_SCREEN** - Required subscriber permissions: ohos.permission.RECEIVER_SPLIT_SCREEN -## COMMON_EVENT_SLOT_CHANGE9+ +## [COMMON_EVENT_SLOT_CHANGE9+](./common_event/commonEvent-ans.md) Indicates that the notification slot has been updated. -- Value: **usual.event.SLOT_CHANGE** -- Required subscriber permissions: ohos.permission.NOTIFICATION_CONTROLLER - ## COMMON_EVENT_SPN_INFO_CHANGED9+ Indicates that the SPN displayed has been updated. - Value: **usual.event.SPN_INFO_CHANGED** @@ -857,130 +660,99 @@ Indicates that the SPN displayed has been updated. ## [COMMON_EVENT_QUICK_FIX_APPLY_RESULT9+](./common_event/commonEvent-ability.md) Indicates the result of applying a quick fix to the application. -- Value: **usual.event.QUICK_FIX_APPLY_RESULT** -- Required subscriber permissions: none ## COMMON_EVENT_HTTP_PROXY_CHANGE10+ Indicates that the HTTP proxy configuration has changed. - Value: **usual.event.HTTP_PROXY_CHANGE** - Required subscriber permissions: none -## COMMON_EVENT_DOMAIN_ACCOUNT_STATUS_CHANGED10+ +## [COMMON_EVENT_DOMAIN_ACCOUNT_STATUS_CHANGED10+](./common_event/commonEvent-account.md) Indicates that the domain account status has changed. -- Value: **usual.event.DOMAIN_ACCOUNT_STATUS_CHANGED** -- Required subscriber permissions: none - ## [COMMON_EVENT_SIM_STATE_CHANGED10+](./common_event/commonEvent-telephony.md) Indicates that the SIM card state has changed. -- Value: **usual.event.SIM_STATE_CHANGED** -- Required subscriber permissions: none - ## [COMMON_EVENT_SMS_RECEIVED_COMPLETED10+](./common_event/commonEvent-telephony.md) Indicates that the SMS message is received. -- Value: **usual.event.SMS_RECEIVED_COMPLETED** -- Required subscriber permissions: ohos.permission.RECEIVE_SMS - ## [COMMON_EVENT_SMS_EMERGENCY_CB_RECEIVE_COMPLETED10+](./common_event/commonEvent-telephony.md) Indicates that an emergency cell broadcast message is received. -- Value: **usual.event.SMS_EMERGENCY_CB_RECEIVE_COMPLETED** -- Required subscriber permissions: ohos.permission.RECEIVE_SMS - ## [COMMON_EVENT_SMS_CB_RECEIVE_COMPLETED10+](./common_event/commonEvent-telephony.md) Indicates that a cell broadcast message is received. -- Value: **usual.event.SMS_CB_RECEIVE_COMPLETED** -- Required subscriber permissions: ohos.permission.RECEIVE_SMS - ## [COMMON_EVENT_STK_COMMAND10+](./common_event/commonEvent-telephony.md) (Reserved, not supported yet) Indicates the STK command. -- Value: **usual.event.STK_COMMAND** -- Required subscriber permissions: none - ## [COMMON_EVENT_STK_SESSION_END10+](./common_event/commonEvent-telephony.md) (Reserved, not supported yet) Indicates that an STK session ends. -- Value: **usual.event.STK_SESSION_END** -- Required subscriber permissions: none - ## [COMMON_EVENT_STK_CARD_STATE_CHANGED10+](./common_event/commonEvent-telephony.md) (Reserved, not supported yet) Indicates that the STK card state has changed. -- Value: **usual.event.STK_CARD_STATE_CHANGED** -- Required subscriber permissions: ohos.permission - ## [COMMON_EVENT_STK_ALPHA_IDENTIFIER10+](./common_event/commonEvent-telephony.md) (Reserved, not supported yet) Indicates the STK alpha indicator. -- Value: **usual.event.STK_ALPHA_IDENTIFIER** -- Required subscriber permissions: none - ## [COMMON_EVENT_SMS_WAPPUSH_RECEIVE_COMPLETED10+](./common_event/commonEvent-telephony.md) Indicates that a WAP push message is received. -- Value: **usual.event.SMS_WAPPUSH_RECEIVE_COMPLETED** -- Required subscriber permissions: ohos.permission.RECEIVE_SMS - ## [COMMON_EVENT_OPERATOR_CONFIG_CHANGED10+](./common_event/commonEvent-telephony.md) Indicates that the carrier configuration has been updated. -- Value: **usual.event.OPERATOR_CONFIG_CHANGED** -- Required subscriber permissions: none - ## [COMMON_EVENT_SIM_CARD_DEFAULT_SMS_SUBSCRIPTION_CHANGED10+](./common_event/commonEvent-telephony.md) Indicates that the default SIM card for the SMS service has changed. -- Value: **usual.event.DEFAULT_SMS_SUBSCRIPTION_CHANGED** -- Required subscriber permissions: none - ## [COMMON_EVENT_SIM_CARD_DEFAULT_DATA_SUBSCRIPTION_CHANGED10+](./common_event/commonEvent-telephony.md) Indicates that the default SIM card for the mobile data service has changed. -- Value: **usual.event.DEFAULT_DATA_SUBSCRIPTION_CHANGED** -- Required subscriber permissions: none - ## [COMMON_EVENT_SIM_CARD_DEFAULT_MAIN_SUBSCRIPTION_CHANGED10+](./common_event/commonEvent-telephony.md) Indicates that the default primary SIM card has changed. -- Value: **usual.event.SIM.DEFAULT_MAIN_SUBSCRIPTION_CHANGED** -- Required subscriber permissions: none - ## [COMMON_EVENT_SIM_CARD_DEFAULT_VOICE_SUBSCRIPTION_CHANGED10+](./common_event/commonEvent-telephony.md) Indicates that the default SIM card for the voice service has changed. -- Value: **usual.event.DEFAULT_VOICE_SUBSCRIPTION_CHANGED** -- Required subscriber permissions: none - ## [COMMON_EVENT_CALL_STATE_CHANGED10+](./common_event/commonEvent-telephony.md) Indicates that the call state has changed. -- Value: **usual.event.CALL_STATE_CHANGED** -- Required subscriber permissions: ohos.permission.GET_TELEPHONY_STATE - ## [COMMON_EVENT_CELLULAR_DATA_STATE_CHANGED10+](./common_event/commonEvent-telephony.md) Indicates that the cellular data state has changed. -- Value: **usual.event.CELLULAR_DATA_STATE_CHANGED** -- Required subscriber permissions: none - ## [COMMON_EVENT_NETWORK_STATE_CHANGED10+](./common_event/commonEvent-telephony.md) Indicates that the network state has changed. -- Value: **usual.event.NETWORK_STATE_CHANGED** -- Required subscriber permissions: none - ## [COMMON_EVENT_SIGNAL_INFO_CHANGED10+](./common_event/commonEvent-telephony.md) Indicates that the signal information is updated. -- Value: **usual.event.SIGNAL_INFO_CHANGED** -- Required subscriber permissions: none - ## [COMMON_EVENT_INCOMING_CALL_MISSED10+](./common_event/commonEvent-telephony.md) Indicates a missed call. -- Value: **usual.event.INCOMING_CALL_MISSED** -- Required subscriber permissions: ohos.permission.GET_TELEPHONY_STATE - ## [COMMON_EVENT_RADIO_STATE_CHANGE10+](./common_event/commonEvent-telephony.md) Indicates that the power-on and power-off status of the modem has changed. -- Value: **usual.event.RADIO_STATE_CHANGE** - -## COMMON_EVENT_SCREEN_LOCKED 10+ +## [COMMON_EVENT_SCREEN_LOCKED 10+](./common_event/commonEvent-screenlock.md) Indicates that the screen is locked. -- Value: **usual.event.SCREEN_LOCKED** -- Required subscriber permissions: none - -## COMMON_EVENT_SCREEN_UNLOCKED10+ +## [COMMON_EVENT_SCREEN_UNLOCKED10+](./common_event/commonEvent-screenlock.md) Indicates that the screen is unlocked. -- Value: **usual.event.SCREEN_UNLOCKED** -- Required subscriber permissions: none ## [COMMON_EVENT_QUICK_FIX_REVOKE_RESULT10+](./common_event/commonEvent-ability.md#common_event_quick_fix_revoke_result10) -ָIndicates the result of revoking a quick fix to the application. \ No newline at end of file +ָIndicates the result of revoking a quick fix to the application. + +## [COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGIN](./common_event/commonEvent-account.md) +(Reserved, not supported yet) Indicates a successful login to a distributed account. + +## [COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOUT](./common_event/commonEvent-account.md) +(Reserved, not supported yet) Indicates a successful logout of a distributed account. + +## [COMMON_EVENT_DISTRIBUTED_ACCOUNT_TOKEN_INVALID](./common_event/commonEvent-account.md) +(Reserved, not supported yet) Indicates the token of a distributed account is invalid. + +## [COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOFF](./common_event/commonEvent-account.md) +(Reserved, not supported yet) Indicates that a distributed account is deregistered. + +## [COMMON_EVENT_USER_INFO_UPDATED9+](./common_event/commonEvent-account.md) + +Indicates that the user information has been updated. + +## [COMMON_EVENT_AUDIO_QUALITY_CHANGE](./common_event/commonEvent-telephony.md) + +Indicates that the audio quality has changed. + +## [COMMON_EVENT_NET_QUOTA_WARNING10+](./common_event/commonEvent-netmanager.md) +Indicates that the network data usage has reached the alarm threshold. + +## [COMMON_EVENT_NET_QUOTA_LIMIT_REMINDED10+](./common_event/commonEvent-netmanager.md) +Indicates that the network data usage has reached the upper limit, and network access is still available. + +## [OMMON_EVENT_NET_QUOTA_LIMIT10+](./common_event/commonEvent-netmanager.md) +Indicates that the network data usage has reached the upper limit, and network access becomes unavailable. + +## [COMMON_EVENT_HTTP_PROXY_CHANGE10+](./common_event/commonEvent-netmanager.md) +Indicates that the HTTP proxy configuration has changed. + +## [COMMON_EVENT_AIRPLANE_MODE_CHANGED10+](./common_event/commonEvent-netmanager.md) +Indicates that the airplane mode state has changed. + +## [COMMON_EVENT_CONNECTIVITY_CHANGE10+](./common_event/commonEvent-netmanager.md) +Indicates that the network connection state has changed. \ No newline at end of file diff --git a/en/application-dev/reference/apis/common_event/commonEvent-account.md b/en/application-dev/reference/apis/common_event/commonEvent-account.md new file mode 100644 index 0000000000000000000000000000000000000000..f850f33644513de697c1cd2f56d2f3439c6660c2 --- /dev/null +++ b/en/application-dev/reference/apis/common_event/commonEvent-account.md @@ -0,0 +1,76 @@ +# Common Events of the Account Subsystem +This document lists the common system events provided by the account subsystem to applications. Applications can use [APIs](../js-apis-commonEventManager.md) to subscribe to common system events. + +## COMMON_EVENT_USER_ADDED +Indicates that a user has been added to the system. + +- Value: usual.event.USER_ADDED +- Required subscriber permissions: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +When a system account is created, the event notification service is triggered to publish this event carrying the system account ID. + +APIs related to this event: **createOsAccount** and **createOsAccountForDomain**. These APIs are system APIs. For details, see [@ohos.account.osAccount (OS Account Management)](../js-apis-osAccount.md). + +## COMMON_EVENT_USER_REMOVED +Indicates that a user has been removed from the system. + +- Value: usual.event.USER_REMOVED +- Required subscriber permissions: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +When a system account is removed, the event notification service is triggered to publish this event carrying the system account ID. + +APIs related to this event: **removeOsAccount**. This API is a system API. For details, see [@ohos.account.osAccount (OS Account Management)](../js-apis-osAccount.md). + +## COMMON_EVENT_DOMAIN_ACCOUNT_STATUS_CHANGED10+ +Indicates that the status of the domain account status changes. + +- Value: usual.event.DOMAIN_ACCOUNT_STATUS_CHANGED +- Required subscriber permissions: ohos.permission.GET_LOCAL_ACCOUNTS + +When a domain user account is authenticated, deleted, or has the token updated, the event notification service is triggered to publish this event carrying the system account ID, domain name, and account status. + +APIs related to this event: **removeOsAccount**, **DomainAccountManager.auth**, and **updateAccountToken**. These APIs are system APIs. For details, see [@ohos.account.osAccount (OS Account Management)](../js-apis-osAccount.md). + +## COMMON_EVENT_USER_SWITCHED +Indicates that user switching is in progress. + +- Value: usual.event.USER_SWITCHED +- Required subscriber permissions: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +When the system account is switched, the event notification service is triggered to publish this event carrying the system account ID. + +APIs related to this event: **activateOsAccount**. This API is a system API. For details, see [@ohos.account.osAccount (OS Account Management)](../js-apis-osAccount.md). + +## COMMON_EVENT_USER_INFO_UPDATED9+ +Indicates that the user information has been updated. + +- Value: **usual.event.USER_INFO_UPDATED** +- Required subscriber permissions: none + +When the distributed account information, system account profile picture, or system account name is changed, the event notification service is triggered to publish this event carrying the system account ID. + +APIs related to this event: **setOsAccountName**, **setOsAccountProfilePhoto**, and **setOsAccountDistributedInfon**. The first two are system APIs, and the last is a public API. For details, see [@ohos.account.osAccount (OS Account Management)](../js-apis-osAccount.md). + +## COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGIN +(Reserved, not supported yet) Indicates a successful login to a distributed account. + +- Value: usual.event.DISTRIBUTED_ACCOUNT_LOGIN +- Required subscriber permissions: none + +## COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOUT +(Reserved, not supported yet) Indicates a successful logout of a distributed account. + +- Value: usual.event.DISTRIBUTED_ACCOUNT_LOGOUT +- Required subscriber permissions: none + +## COMMON_EVENT_DISTRIBUTED_ACCOUNT_TOKEN_INVALID +(Reserved, not supported yet) Indicates the token of a distributed account is invalid. + +- Value: usual.event.DISTRIBUTED_ACCOUNT_TOKEN_INVALID +- Required subscriber permissions: none + +## COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOFF +(Reserved, not supported yet) Indicates that a distributed account is deregistered. + +- Value: usual.event.DISTRIBUTED_ACCOUNT_LOGOFF +- Required subscriber permissions: none diff --git a/en/application-dev/reference/apis/common_event/commonEvent-filemanagement.md b/en/application-dev/reference/apis/common_event/commonEvent-filemanagement.md new file mode 100644 index 0000000000000000000000000000000000000000..04c4d99a1e4f853d8960f053a203d6e49a2c5e97 --- /dev/null +++ b/en/application-dev/reference/apis/common_event/commonEvent-filemanagement.md @@ -0,0 +1,37 @@ +# Common Events of the File Management Subsystem +This document lists the common system events provided by the file management subsystem to applications. Applications can use [APIs](../js-apis-commonEventManager.md) to subscribe to common system events. + +## COMMON_EVENT_VOLUME_REMOVED9+ +Indicates that an external storage device was removed. +- Value: usual.event.data.VOLUME_REMOVED +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + +When an external storage device is removed, the event notification service is triggered to publish this event. + +## COMMON_EVENT_VOLUME_UNMOUNTED9+ +Indicates that an external storage device was unmounted. +- Value: usual.event.data.VOLUME_UNMOUNTED +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + +When an external storage device is successfully unmounted by calling [unmount](../js-apis-file-volumemanager.md) or by removing the device, the event notification service is triggered to publish this event. + +## COMMON_EVENT_VOLUME_MOUNTED9+ +Indicates that an external storage device was mounted. +- Value: usual.event.data.VOLUME_MOUNTED +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + +When an external storage device is mounted by calling [mount](../js-apis-file-volumemanager.md) or by inserting the device, the event notification service is triggered to publish this event. + +## COMMON_EVENT_VOLUME_BAD_REMOVAL9+ +Indicates that an external storage device was removed without being unmounted. +- Value: usual.event.data.VOLUME_BAD_REMOVAL +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + +When an external storage device is directly removed without being umounted, the event notification service is triggered to publish this event. + +## COMMON_EVENT_VOLUME_EJECT9+ +Indicates that an external storage device is about to be ejected. +- Value: usual.event.data.VOLUME_EJECT +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + +When the user calls [unmount](../js-apis-file-volumemanager.md) on a mounted external storage device or removes the device, the event notification service is triggered to publish this event. diff --git a/en/application-dev/reference/apis/common_event/commonEvent-mms.md b/en/application-dev/reference/apis/common_event/commonEvent-mms.md new file mode 100644 index 0000000000000000000000000000000000000000..4c4425b2db856a8da25649a0149e70b918610d6d --- /dev/null +++ b/en/application-dev/reference/apis/common_event/commonEvent-mms.md @@ -0,0 +1,11 @@ +# Common Events of the SMS Application +This document lists the common system events provided by the SMS application to applications. Applications can use [APIs](../js-apis-commonEventManager.md) to subscribe to common system events. + +## COMMON_EVENT_SMS_RECEIVE_COMPLETED + +Indicates that a new SMS message has been received. + +- Value: usual.event.SMS_RECEIVE_COMPLETED +- Required subscriber permissions: none + +When the device receives a new SMS message, the event notification service is triggered to publish this event. diff --git a/en/application-dev/reference/apis/common_event/commonEvent-netmanager.md b/en/application-dev/reference/apis/common_event/commonEvent-netmanager.md new file mode 100644 index 0000000000000000000000000000000000000000..73471c0ef6bdce80ca248ef67d7eb556c2ebdaf9 --- /dev/null +++ b/en/application-dev/reference/apis/common_event/commonEvent-netmanager.md @@ -0,0 +1,57 @@ +# Common Events of the Network Management Subsystem +This document lists the common system events provided by the network management subsystem to applications. Applications can use [APIs](../js-apis-commonEventManager.md) to subscribe to common system events. + + +## COMMON_EVENT_CONNECTIVITY_CHANGE10+ + +Indicates that the network connection state has changed. + +- Value: usual.event.CONNECTIVITY_CHANGE +- Required subscriber permissions: none + +When the (Ethernet, Wi-Fi, or cellular) network connection state changes (to disconnected, connecting, or connected), the event notification service is triggered to publish this event. + +## COMMON_EVENT_AIRPLANE_MODE_CHANGED10+ + +Indicates that the airplane mode state has changed. + +- Value: usual.event.AIRPLANE_MODE +- Required subscriber permissions: none + +When the airplane mode is set, the event notification service is triggered to publish this event. + +## COMMON_EVENT_HTTP_PROXY_CHANGE10+ + +Indicates that the HTTP proxy configuration has changed. + +- Value: usual.event.HTTP_PROXY_CHANGE +- Required subscriber permissions: none + +When the configuration of the global or network-specific (such as Ethernet and Wi-Fi) HTTP proxy changes, the event notification service is triggered to publish this event. + +## COMMON_EVENT_NET_QUOTA_WARNING10+ + +Indicates that the network data usage has reached the alarm threshold. + +- Value: usual.event.QUOTA_WARNING +- Required subscriber permissions: none + +When the network data usage reaches 80% of the limit, the event notification service is triggered to publish this event. + +## COMMON_EVENT_NET_QUOTA_LIMIT_REMINDED10+ + +Indicates that the network data usage has reached the upper limit, and network access is still available. + +- Value: usual.event.NET_QUOTA_LIMIT_REMINDED +- Required subscriber permissions: none + +When the network data usage reaches the upper limit and the user chooses to continue to use the network, the event notification service is triggered to publish this event. + +## COMMON_EVENT_NET_QUOTA_LIMIT10+ + +Indicates that the network data usage has reached the upper limit, and network access becomes unavailable. + +- Value: usual.event.NET_QUOTA_LIMIT +- Required subscriber permissions: none + +When the network data usage reaches the upper limit and continuing to use the network is not allowed, the event notification service is triggered to publish this event. diff --git a/en/application-dev/reference/apis/common_event/commonEvent-nfc.md b/en/application-dev/reference/apis/common_event/commonEvent-nfc.md new file mode 100644 index 0000000000000000000000000000000000000000..b049143416e9459108b3276266fb4d55f8037cae --- /dev/null +++ b/en/application-dev/reference/apis/common_event/commonEvent-nfc.md @@ -0,0 +1,26 @@ +# Common Events of the NFC Subsystem +This document lists the common system events provided by the NFC subsystem to applications. Applications can use [APIs](../js-apis-commonEventManager.md) to subscribe to common system events. + +## COMMON_EVENT_NFC_ACTION_ADAPTER_STATE_CHANGED +Indicates that the state of the device NFC adapter has changed. + +- Value: usual.event.nfc.action.ADAPTER_STATE_CHANGED +- Required subscriber permissions: none + +When the state of the device NFC adapter changes, the event notification service is triggered to publish this event. + +## COMMON_EVENT_NFC_ACTION_RF_FIELD_ON_DETECTED +Indicates that the NFC RF field is on. + +- Value: usual.event.nfc.action.RF_FIELD_ON_DETECTED +- Required subscriber permissions: ohos.permission.MANAGE_SECURE_SETTINGS + +When the NFC RF field becomes available, the event notification service is triggered to publish this event. + +## COMMON_EVENT_NFC_ACTION_RF_FIELD_OFF_DETECTED +Indicates that the NFC RF field is off. + +- Value: usual.event.nfc.action.RF_FIELD_OFF_DETECTED +- Required subscriber permissions: ohos.permission.MANAGE_SECURE_SETTINGS + +When the NFC RF field becomes unavailable, the event notification service is triggered to publish this event. diff --git a/en/application-dev/reference/apis/common_event/commonEvent-powermgr.md b/en/application-dev/reference/apis/common_event/commonEvent-powermgr.md new file mode 100644 index 0000000000000000000000000000000000000000..d2829f06383208c93abbdadec23dea9f0f44e1f9 --- /dev/null +++ b/en/application-dev/reference/apis/common_event/commonEvent-powermgr.md @@ -0,0 +1,106 @@ +# Common Events of the Power Management Subsystem +This document lists the common system events provided by the power management subsystem to applications. Applications can use [APIs](../js-apis-commonEventManager.md) to subscribe to common system events. + +## COMMON_EVENT_BATTERY_CHANGED +Indicates that the charging state, level, and other information about the battery have changed. + +- Value: usual.event.BATTERY_CHANGED +- Required subscriber permissions: none + +When any of the following information changes, the event notification service is triggered to publish this event: battery level, battery voltage, battery temperature, battery health status, type of the charger connected to the device, maximum current of the charger, maximum voltage of the charger, battery charging status, number of charging times, total battery capacity, remaining battery capacity, battery model, current of the battery, and battery charging type. + +## COMMON_EVENT_BATTERY_LOW +Indicates that the battery level is low. + +- Value: usual.event.BATTERY_LOW +- Required subscriber permissions: none + +When the battery level drops to lower than the low battery level set for the device, the event notification service is triggered to publish this event. For details about how to set the low battery level, see [Battery Level Customization](../../../../device-dev/subsystems/subsys-power-battery-level-customization.md). + +## COMMON_EVENT_BATTERY_OKAY +Indicates that the battery level is normal. + +- Value: usual.event.BATTERY_OKAY +- Required subscriber permissions: none + +When the battery level changes from the low level to normal level, the event notification service is triggered to publish this event. + +## COMMON_EVENT_POWER_CONNECTED +Indicates that the device is connected to an external power supply. + +- Value: usual.event.POWER_CONNECTED +- Required subscriber permissions: none + +When the device connects to an external charger, the event notification service is triggered to publish this event. + +## COMMON_EVENT_POWER_DISCONNECTED +Indicates that the device is disconnected from the external power supply. + +- Value: usual.event.POWER_DISCONNECTED +- Required subscriber permissions: none + +When the device is disconnected from the external power supply, the event notification service is triggered to publish this event. + +## COMMON_EVENT_DISCHARGING +Indicates that the system stops charging the battery. + +- Value: usual.event.DISCHARGING +- Required subscriber permissions: none + +When the system stops charging the battery, the event notification service is triggered to publish this event. + +## COMMON_EVENT_CHARGING +Indicates that the system starts charging the battery. + +- Value: usual.event.CHARGING +- Required subscriber permissions: none + +When the system starts charging the battery, the event notification service is triggered to publish this event. + +## COMMON_EVENT_CHARGE_TYPE_CHANGED +Indicates that the system charging type has changed. This event is available only for system applications. +- Value: usual.event.CHARGE_TYPE_CHANGED + +- Required subscriber permissions: none + +When the system charging type changes, the event notification service is triggered to publish this event. + +## COMMON_EVENT_SHUTDOWN +Indicates that the device is being and will be shut down. + +- Value: usual.event.SHUTDOWN +- Required subscriber permissions: none + +When the device is being shut down until it is powered off, the event notification service is triggered to publish this event. + +## COMMON_EVENT_SCREEN_OFF +Indicates that the device screen is off and the device is in sleep mode. + +- Value: usual.event.SCREEN_OFF +- Required subscriber permissions: none + +When the device screen is turned off and the device is in sleep mode, the event notification service is triggered to publish this event. + +## COMMON_EVENT_SCREEN_ON +Indicates that the device screen is on and the device is in the active state. + +- Value: usual.event.SCREEN_ON +- Required subscriber permissions: none + +When the device screen is turned on and in the active state, the event notification service is triggered to publish this event. + +## COMMON_EVENT_POWER_SAVE_MODE_CHANGED +Indicates that the system power saving mode has changed. + +- Value: usual.event.POWER_SAVE_MODE_CHANGED +- Required subscriber permissions: none + +When the system power saving mode changes, the event notification service is triggered to publish this event. + +## COMMON_EVENT_THERMAL_LEVEL_CHANGED +Indicates that the device's thermal level has changed. + +- Value: usual.event.THERMAL_LEVEL_CHANGED +- Required subscriber permissions: none + +When the device's thermal level changes, the event notification service is triggered to publish this event. For details about how to configure the thermal level, see [Thermal Level Customization](../../../../device-dev/subsystems/subsys-thermal_level.md). diff --git a/en/application-dev/reference/apis/common_event/commonEvent-screenlock.md b/en/application-dev/reference/apis/common_event/commonEvent-screenlock.md new file mode 100644 index 0000000000000000000000000000000000000000..01cbd10b6425de10526178c8808d6c2ba3216d4e --- /dev/null +++ b/en/application-dev/reference/apis/common_event/commonEvent-screenlock.md @@ -0,0 +1,18 @@ +# Common Events of the Theme Framework - Lock Screen +This document lists the common system events provided by the theme framework - lock screen to applications. Applications can use [APIs](../js-apis-commonEventManager.md) to subscribe to common system events. + +## COMMON_EVENT_SCREEN_LOCKED +Indicates that the screen has been locked. + +- Value: usual.event.SCREEN_LOCKED +- Required subscriber permissions: none + +When the screen is locked, the event notification service is triggered to publish this event. + +## COMMON_EVENT_SCREEN_UNLOCKED +Indicates that the screen has been unlocked. + +- Value: usual.event.SCREEN_UNLOCKED +- Required subscriber permissions: none + +When the screen is unlocked, the event notification service is triggered to publish this event. diff --git a/en/application-dev/reference/apis/common_event/commonEvent-time.md b/en/application-dev/reference/apis/common_event/commonEvent-time.md new file mode 100644 index 0000000000000000000000000000000000000000..d1fe1562c49885873592a608c00567c9faedbf98 --- /dev/null +++ b/en/application-dev/reference/apis/common_event/commonEvent-time.md @@ -0,0 +1,26 @@ +# Common Events of the Time and Time Zone Subsystem +This document lists the common system events provided by the time and time zone subsystem to applications. Applications can use [APIs](../js-apis-commonEventManager.md) to subscribe to common system events. + +## COMMON_EVENT_TIME_CHANGED +Indicates that the system time has been set. + +- Value: usual.event.TIME_CHANGED +- Required subscriber permissions: none + +When the system time is set, the event notification service is triggered to publish this event. + +## COMMON_EVENT_TIME_TICK +Indicates that the system time has changed. + +- Value: usual.event.TIME_TICK +- Required subscriber permissions: none + +When the system time changes, the event notification service is triggered to publish this event. + +## COMMON_EVENT_TIMEZONE_CHANGED +Indicates that the system time zone has changed. + +- Value: usual.event.TIMEZONE_CHANGED +- Required subscriber permissions: none + +When the system time zone changes, the event notification service is triggered to publish this event. diff --git a/en/application-dev/reference/apis/common_event/commonEvent-wifi.md b/en/application-dev/reference/apis/common_event/commonEvent-wifi.md new file mode 100644 index 0000000000000000000000000000000000000000..7930f1e688ddc57ea702ecfc96f459781f768476 --- /dev/null +++ b/en/application-dev/reference/apis/common_event/commonEvent-wifi.md @@ -0,0 +1,123 @@ +# Common Events of the Wi-Fi Subsystem +This document lists the common system events provided by the Wi-Fi subsystem to applications. Applications can use [APIs](../js-apis-commonEventManager.md) to subscribe to common system events. + +## COMMON_EVENT_WIFI_POWER_STATE +Indicates that the Wi-Fi state has changed, for example, enabled or disabled. + +- Value: usual.event.wifi.POWER_STATE +- Required subscriber permissions: none + +When the Wi-Fi state changes, the event notification service is triggered to publish this event. + +## COMMON_EVENT_WIFI_SCAN_FINISHED +Indicates that the Wi-Fi access point has been detected and proven to be available. + +- Value: usual.event.wifi.SCAN_FINISHED +- Required subscriber permissions: ohos.permission.LOCATION + +When a Wi-Fi access point is detected and proven to be available, the event notification service is triggered to publish this event. + +## COMMON_EVENT_WIFI_SCAN_STATE +Indicates that the Wi-Fi access point state has changed. + +- Value: usual.event.wifi.SCAN_STATE +- Required subscriber permissions: ohos.permission.LOCATION + +When the Wi-Fi access point state changes, the event notification service is triggered to publish this event. + +## COMMON_EVENT_WIFI_RSSI_VALUE +Indicates that the Wi-Fi signal strength (RSSI) has changed. + +- Value: usual.event.wifi.RSSI_VALUE +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO + +When the Wi-Fi signal strength (RSSI) changes, the event notification service is triggered to publish this event. + +## COMMON_EVENT_WIFI_CONN_STATE +Indicates that the Wi-Fi connection state has changed. + +- Value: usual.event.wifi.CONN_STATE +- Required subscriber permissions: none + +When the Wi-Fi connection state changes, the event notification service is triggered to publish this event. + +## COMMON_EVENT_WIFI_HOTSPOT_STATE +Indicates that the Wi-Fi hotspot state has changed, for example, enabled or disabled. + +- Value: usual.event.wifi.HOTSPOT_STATE +- Required subscriber permissions: none + +When the Wi-Fi hotspot state changes, the event notification service is triggered to publish this event. + +## COMMON_EVENT_WIFI_AP_STA_JOIN +Indicates that a client has joined the Wi-Fi hotspot of the current device. + +- Value: usual.event.wifi.WIFI_HS_STA_JOIN +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO + +When a client joins the Wi-Fi hotspot of the current device, the event notification service is triggered to publish this event. + + +## COMMON_EVENT_WIFI_AP_STA_LEAVE +Indicates that a client has disconnected from the Wi-Fi hotspot of the current device. + +- Value: usual.event.wifi.WIFI_HS_STA_LEAVE +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO + +When a client is disconnected from the Wi-Fi hotspot of the current device, the event notification service is triggered to publish this event. + +## COMMON_EVENT_WIFI_MPLINK_STATE_CHANGE +Indicates that the state of MPLINK (an enhanced Wi-Fi feature) has changed. + +- Value: usual.event.wifi.mplink.STATE_CHANGE +- Required subscriber permissions: ohos.permission.MPLINK_CHANGE_STATE + +When the state of MPLINK (an enhanced Wi-Fi feature) changes, the event notification service is triggered to publish this event. + +## COMMON_EVENT_WIFI_P2P_CONN_STATE +Indicates that the Wi-Fi P2P connection state has changed. + +- Value: usual.event.wifi.p2p.CONN_STATE_CHANGE +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +When the Wi-Fi P2P connection state changes, the event notification service is triggered to publish this event. + +## COMMON_EVENT_WIFI_P2P_STATE_CHANGED +Indicates that the Wi-Fi P2P state has changed, for example, enabled or disabled. + +- Value: usual.event.wifi.p2p.STATE_CHANGE +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO + +When the Wi-Fi P2P state changes, the event notification service is triggered to publish this event. + +## COMMON_EVENT_WIFI_P2P_PEERS_STATE_CHANGED +Indicates that the state of the Wi-Fi P2P peer device has changed. + +- Value: usual.event.wifi.p2p.DEVICES_CHANGE +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO + +When the state of the Wi-Fi P2P peer device changes, the event notification service is triggered to publish this event. + +## COMMON_EVENT_WIFI_P2P_PEERS_DISCOVERY_STATE_CHANGED +Indicates that the Wi-Fi P2P discovery state has changed. + +- Value: usual.event.wifi.p2p.PEER_DISCOVERY_STATE_CHANGE +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO + +When the Wi-Fi P2P discovery state changes, the event notification service is triggered to publish this event. + +## COMMON_EVENT_WIFI_P2P_CURRENT_DEVICE_STATE_CHANGED +Indicates that the state of the Wi-Fi P2P local device has changed. + +- Value: usual.event.wifi.p2p.CURRENT_DEVICE_CHANGE +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO + +When the state of the Wi-Fi P2P local device changes, the event notification service is triggered to publish this event. + +## COMMON_EVENT_WIFI_P2P_GROUP_STATE_CHANGED +Indicates that the Wi-Fi P2P group information has changed. + +- Value: usual.event.wifi.p2p.GROUP_STATE_CHANGED +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO + +When the Wi-Fi P2P group information changes, the event notification service is triggered to publish this event. diff --git a/en/application-dev/reference/apis/common_event/commonEvent-window.md b/en/application-dev/reference/apis/common_event/commonEvent-window.md new file mode 100644 index 0000000000000000000000000000000000000000..b6560085737805c7a708e8fc89e7daeb7d85ff1f --- /dev/null +++ b/en/application-dev/reference/apis/common_event/commonEvent-window.md @@ -0,0 +1,10 @@ +# Common Events of the Window Management Subsystem +This document lists the common system events provided by the window management subsystem to applications. Applications can use [APIs](../js-apis-commonEventManager.md) to subscribe to common system events. + +### COMMON_EVENT_SPLIT_SCREEN10+ +Indicates a screen splitting action. + +- Value: usual.event.SPLIT_SCREEN +- Required subscriber permissions: none + +When any of the following actions is performed, the event notification service is triggered to publish this event: accessing the recent tasks screen, creating a split-screen bar, and destroying a split-screen bar. diff --git a/en/application-dev/reference/apis/js-apis-ability-featureAbility.md b/en/application-dev/reference/apis/js-apis-ability-featureAbility.md index 262899f64ed644007d28d1dce9b53c369a830f12..b5ea0c253dba532a22c1e090f40e51656f64b27d 100644 --- a/en/application-dev/reference/apis/js-apis-ability-featureAbility.md +++ b/en/application-dev/reference/apis/js-apis-ability-featureAbility.md @@ -707,7 +707,7 @@ let connectId = featureAbility.connectAbility( ); featureAbility.disconnectAbility(connectId).then((data) => { - console.log('data: ${data)}'; + console.log('data: ${data)}') }).catch((error)=>{ console.error('featureAbilityTest result errCode : ${error.code}'); }); diff --git a/en/application-dev/reference/apis/js-apis-animator.md b/en/application-dev/reference/apis/js-apis-animator.md index 5eb3e73a20a45f459f1879b49cfc4c9743c22fa7..ca8c254cc2920df317a9c9b5d5cce55f3efa852d 100644 --- a/en/application-dev/reference/apis/js-apis-animator.md +++ b/en/application-dev/reference/apis/js-apis-animator.md @@ -7,7 +7,10 @@ The **Animator** module provides APIs for applying animation effects, including > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > > This module can be used only after a component instance is created, and it cannot be used in the [UIAbility](./js-apis-app-ability-uiAbility.md). - +> +> The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see [UIContext](./js-apis-arkui-UIContext.md#uicontext). +> +> Since API version 10, you can use the [createAnimator](./js-apis-arkui-UIContext.md#createanimator) API in [UIContext](./js-apis-arkui-UIContext.md#uicontext) to obtain the UI context. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md index ed56fca0dd96bdd53e0bc66548c72c028a0ddf4f..a19759144290c86e6af1f6812569683e39d74bae 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md @@ -388,7 +388,7 @@ abilityManager.getTopAbility().then((data) => { acquireShareData(missionId: number, callback: AsyncCallback<{[key: string]: Object}>): void; -Acquires the shared data of the target application. This API uses an asynchronous callback to return the result. **missionId** indicates the target application's mission ID, which can be obtained by running the **hdc shell aa dump -a** command or calling the [missionManager.getMissionInfos()](js-apis-app-ability-missionManager.md#getmissioninfos) API after the target application is started. **callback** indicates the data shared by the target application through the [UIAbility.onShare()](js-apis-app-ability-uiAbility.md#onshare) lifecycle callback. +Called by a system dialog box to obtain shared data, which is set by the target UIAbility through **onShare()**. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -429,10 +429,16 @@ try { acquireShareData(missionId: number): Promise<{[key: string]: Object}>; -Acquires the shared data of the target application. This API uses a promise to return the result. **missionId** indicates the target application's mission ID, which can be obtained by running the **hdc shell aa dump -a** command or calling the [missionManager.getMissionInfos()](js-apis-app-ability-missionManager.md#getmissioninfos) API after the target application is started. **Promise<{[key: string]: Object}>** indicates the data shared by the target application through the [UIAbility.onShare()](js-apis-app-ability-uiAbility.md#onshare) lifecycle callback. +Called by a system dialog box to obtain shared data, which is set by the target UIAbility through **onShare()**. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| missionId | number | Yes| Mission ID on the target application. The maximum value is 231-1.| + **Return value** | Type | Description | diff --git a/en/application-dev/reference/apis/js-apis-app-ability-appManager.md b/en/application-dev/reference/apis/js-apis-app-ability-appManager.md index 9fa26885cc9f8ab20b8c5a1dc17ee4be054195ad..5b655dddcbb03e56c1cfeef5efd726f189400599 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-appManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-appManager.md @@ -298,7 +298,7 @@ appManager.getRunningProcessInformation((err, data) => { }); ``` -## appManager.isSharedBundleRunning +## appManager.isSharedBundleRunning10+ isSharedBundleRunning(bundleName: string, versionCode: number): Promise\; @@ -323,11 +323,20 @@ Checks whether the shared library is in use. This API uses a promise to return t | -------- | -------- | | Promise\ | Promise used to return the result. The value **true** means that the shared library is in use, and **false** means the opposite.| +**Error codes** + +| ID | Error Message | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts import appManager from '@ohos.app.ability.appManager'; +const bundleName = "this is a bundleName"; +const versionCode = 1; appManager.isSharedBundleRunning(bundleName, versionCode).then((data) => { console.log('The shared bundle running is: ${JSON.stringify(data)}'); }).catch((error) => { @@ -335,7 +344,7 @@ appManager.isSharedBundleRunning(bundleName, versionCode).then((data) => { }); ``` -## appManager.isSharedBundleRunning +## appManager.isSharedBundleRunning10+ isSharedBundleRunning(bundleName: string, versionCode: number, callback: AsyncCallback\): void; @@ -353,18 +362,22 @@ Checks whether the shared library is in use. This API uses an asynchronous callb | --------- | ---------------------------------------- | ---- | -------------- | | bundleName | string | Yes | Bundle name of the shared library.| | versionCode | number | Yes | Version number of the shared library. | +|AsyncCallback\> | Callback used to return the result. The value **true** means that the shared library is in use, and **false** means the opposite.| -**Return value** +**Error codes** -| Type| Description| -| -------- | -------- | -|AsyncCallback\> | Callback used to return the result. The value **true** means that the shared library is in use, and **false** means the opposite.| +| ID | Error Message | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts import appManager from '@ohos.app.ability.appManager'; +const bundleName = "this is a bundleName"; +const versionCode = 1; appManager.isSharedBundleRunning(bundleName, versionCode, (err, data) => { if (err) { console.error('err: ${JSON.stringify(err)}'); diff --git a/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md b/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md index ebe37268a6ef9deab92d6e5d3108e573a352214f..2cfa9b0c9049adf9448ea87e6698d3bb179bc418 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md @@ -173,6 +173,8 @@ Saves the ability state, which will be used for recovery. This API can be used t ```ts import appRecovery from '@ohos.app.ability.appRecovery'; +import errorManager from '@ohos.app.ability.errorManager'; + let observer = { onUnhandledException(errorMsg) { console.log('onUnhandledException, errorMsg: ', errorMsg); diff --git a/en/application-dev/reference/apis/js-apis-app-ability-dialogRequest.md b/en/application-dev/reference/apis/js-apis-app-ability-dialogRequest.md index 8ee9ffa986edff4df3b22be677291bf3a8228911..1b3d1674ff726f31a42fe7c43acc1eb6c3d9a17d 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-dialogRequest.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-dialogRequest.md @@ -324,7 +324,7 @@ setRequestResult(result: RequestResult): void; Sets the result of the request for the modal dialog box. -**System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-app-ability-extensionAbility.md b/en/application-dev/reference/apis/js-apis-app-ability-extensionAbility.md index d532723b43a1c31f2b01b35799747ec689df5099..5b86b785a1de4da83408bfe14bce00ea14b76479 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-extensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-extensionAbility.md @@ -7,4 +7,10 @@ > 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 of this module can be used only in the stage model. +## Modules to Import + +```ts +import ExtensionAbility from '@ohos.app.ability.ExtensionAbility'; +``` + **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore diff --git a/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md b/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md index 9b616fd6cae71c233c37f126d038604aeb0aa338..9e3b401e5bf5f21c31210ef12736e5bc7e6fbc58 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md @@ -946,7 +946,7 @@ Clears all unlocked missions. This API uses a promise to return the result. import missionManager from '@ohos.app.ability.missionManager'; try { - missionManager.clearAllMissions(bundleName).then((data) => { + missionManager.clearAllMissions().then((data) => { console.info('clearAllMissions successfully. Data: ${JSON.stringify(data)}'); }).catch(err => { console.error('clearAllMissions failed: ${err.message}'); diff --git a/en/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md b/en/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md index e4d2183d51e6a98995db6ea12a4b5a025a9e83c5..8bf70bb32c3dedb1cf761119f5a0f380c0815f86 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md @@ -57,10 +57,10 @@ Applies a quick fix patch. This API uses an asynchronous callback to return the **Parameters** -| Parameter| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| hapModuleQuickFixFiles | Array\ | Yes| Quick fix patch files, each of which must contain a valid file path.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| + | Parameter| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | hapModuleQuickFixFiles | Array\ | Yes| Quick fix patch files, each of which must contain a valid file path.| + | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** @@ -116,15 +116,15 @@ Applies a quick fix patch. This API uses a promise to return the result. **Parameters** -| Parameter| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| hapModuleQuickFixFiles | Array\ | Yes| Quick fix patch files, each of which must contain a valid file path.| + | Parameter| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | hapModuleQuickFixFiles | Array\ | Yes| Quick fix patch files, each of which must contain a valid file path.| **Return value** -| Type| Description| -| -------- | -------- | -| Promise\ | Promise used to return the result.| + | Type| Description| + | -------- | -------- | + | Promise\ | Promise used to return the result.| **Error codes** @@ -225,9 +225,9 @@ Obtains the quick fix information of the application. This API uses a promise to **Return value** -| Type| Description| -| -------- | -------- | -| Promise\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Promise used to return the quick fix information.| + | Type| Description| + | -------- | -------- | + | Promise\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Promise used to return the quick fix information.| **Error codes** @@ -267,10 +267,10 @@ Revokes quick fix. This API uses an asynchronous callback to return the result. **Parameters** -| Parameter| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Name of the bundle for which the patch needs to be revoked.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| + | Parameter| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | bundleName | string | Yes| Name of the bundle for which the patch needs to be revoked.| + | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** @@ -312,15 +312,15 @@ Revokes quick fix. This API uses a promise to return the result. **Parameters** -| Parameter| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Name of the bundle for which the patch needs to be revoked.| + | Parameter| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | bundleName | string | Yes| Name of the bundle for which the patch needs to be revoked.| **Return value** -| Type| Description| -| -------- | -------- | -| Promise\ | Promise used to return the result.| + | Type| Description| + | -------- | -------- | + | Promise\ | Promise used to return the result.| **Error codes** @@ -349,5 +349,3 @@ If an error occurs during patch installation, the error code and message are ret console.info("revokeQuickFix " + bundleName +" failed, error code is ", JSON.stringify((err))); }); ``` - - \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md b/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md index 0c514446fd7e9be90f3e00e3ee401635466015fd..7aeaabcbf24df8d253c45a38faa1fd44e60a51df 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md @@ -19,7 +19,7 @@ import StartOptions from '@ohos.app.ability.StartOptions'; | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| [windowMode](js-apis-app-ability-abilityConstant.md#abilityconstantwindowmode) | number | No| Window mode.| +| [windowMode](js-apis-app-ability-abilityConstant.md#abilityconstantwindowmode) | number | No| Window mode.
**System API**: This is a system API and cannot be called by third-party applications.| | displayId | number | No| Display ID. The default value is **0**, indicating the current display.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md b/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md index 572f8909b48c89f8f9decdfee326976f62098fd2..cd3d92a89ca32ed4e5af29c1983d9d8f01341186 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md @@ -339,6 +339,51 @@ class MyUIAbility extends UIAbility { } ``` +## UIAbility.onPrepareToTerminate10+ + +onPrepareToTerminate(): boolean; + +Triggered when this UIAbility is about to terminate in case that the system parameter **persist.sys.prepare_terminate** is set to **true**. You can define an operation in this callback to determine whether to continue terminating the UIAbility. If a confirmation from the user is required, you can define a pre-termination operation in the callback and use it together with [terminateSelf](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself), for example, displaying a dialog box to ask the user whether to terminate the UIAbility. The UIAbility termination process is canceled when **persist.sys.prepare_terminate** is set to **true**. + +**Required permissions**: ohos.permission.PREPARE_APP_TERMINATE + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Return value** + +| Type| Description| +| -- | -- | +| boolean | Whether to terminate the UIAbility. The value **true** means that the termination process is canceled and the UIAbility is not terminated. The value **false** means to continue terminating the UIAbility.| + +**Example** + + ```ts + export default class EntryAbility extends UIAbility { + onPrepareToTerminate() { + // Define a pre-termination operation, + // for example, starting another UIAbility and performing asynchronous termination based on the startup result. + let want:Want = { + bundleName: "com.example.myapplication", + moduleName: "entry", + abilityName: "SecondAbility" + } + this.context.startAbilityForResult(want) + .then((result)=>{ + // Obtain the startup result and terminate the current UIAbility when resultCode in the return value is 0. + console.log('startAbilityForResult success, resultCode is ' + result.resultCode); + if (result.resultCode === 0) { + this.context.terminateSelf(); + } + }).catch((err)=>{ + // Exception handling. + console.log('startAbilityForResult failed, err:' + JSON.stringify(err)); + this.context.terminateSelf(); + }) + + return true; // The pre-termination operation is defined. The value true means that the UIAbility termination process is canceled. + } + } + ``` ## Caller @@ -623,11 +668,12 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ```ts import UIAbility from '@ohos.app.ability.UIAbility'; + import window from '@ohos.window'; let caller; let dstDeviceId: string; export default class MainAbility extends UIAbility { - onWindowStageCreate(windowStage: Window.WindowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { this.context.startAbilityByCall({ bundleName: 'com.example.myservice', abilityName: 'MainUIAbility', @@ -643,7 +689,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error } }).catch((err) => { console.log('Caller GetCaller error, error.code: ${JSON.stringify(err.code)}, error.message: ${JSON.stringify(err.message)}'); - }); + }) } } ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-want.md b/en/application-dev/reference/apis/js-apis-app-ability-want.md index 21520cc4829029ccbfd801dc4f2aa8a34d617059..777ea195d6990d7a2decfefce46272ed3c1074f0 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-want.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-want.md @@ -176,13 +176,14 @@ import Want from '@ohos.app.ability.Want'; bundleName: 'com.example.myapplication1', abilityName: 'ServiceExtensionAbility', }; - context.startAbility(want, (err) => { console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`); }); + ``` + ```ts // (2) The ServiceExtensionAbility starts UIAbility2, carrying **"ability.params.backToOtherMissionStack": true** during the startup. - let context = ...; // ServiceExtensionContext + let context ; // ServiceExtensionContext let want = { bundleName: 'com.example.myapplication2', abilityName: 'MainAbility', diff --git a/en/application-dev/reference/apis/js-apis-app-ability-wantConstant.md b/en/application-dev/reference/apis/js-apis-app-ability-wantConstant.md index a53fe7763dfadc0ef16bc2e13a1615eb1af2fead..ddb7f5227f4f675317c7d0a891eeb4459010d84f 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-wantConstant.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-wantConstant.md @@ -25,7 +25,7 @@ Defines **Params** (specifying the action that can be performed) in the Want. | DLP_PARAMS_MODULE_NAME | ohos.dlp.params.moduleName | Action of obtaining the DLP module name.
**System API**: This is a system API and cannot be called by third-party applications.| | DLP_PARAMS_ABILITY_NAME | ohos.dlp.params.abilityName | Action of obtaining the DLP ability name.
**System API**: This is a system API and cannot be called by third-party applications.| | DLP_PARAMS_INDEX | ohos.dlp.params.index | Action of obtaining the DLP index.
**System API**: This is a system API and cannot be called by third-party applications.| -| ABILITY_BACK_TO_OTHER_MISSION_STACK | ability.params.backToOtherMissionStack | Whether to support redirection back across mission stacks.
**System API**: This is a system API and cannot be called by third-party applications.| +| ABILITY_BACK_TO_OTHER_MISSION_STACK | ability.params.backToOtherMissionStack | Whether to support redirection back across mission stacks. | | ABILITY_RECOVERY_RESTART10+ | ohos.ability.params.abilityRecoveryRestart | Action of recovering an ability from a fault and restarting it.| | CONTENT_TITLE_KEY10+ | ohos.extra.param.key.contentTitle | Action of sharing the content title. | | SHARE_ABSTRACT_KEY10+ | ohos.extra.param.key.shareAbstract | Action of sharing the abstract. | diff --git a/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md b/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md index dbef711c25369d3eac61ca1b6516a7c43d8ecbc2..1f8af971be9c75fc3781d7a66422c38466f29aa4 100644 --- a/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md +++ b/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md @@ -1,4 +1,4 @@ -# @ohos.application.formBindingData (formBindingData) +# @ohos.app.form.formBindingData (formBindingData) The **FormBindingData** module provides APIs for widget data binding. You can use the APIs to create a **FormBindingData** object and obtain related information. @@ -12,6 +12,19 @@ The **FormBindingData** module provides APIs for widget data binding. You can us import formBindingData from '@ohos.app.form.formBindingData'; ``` + +## ProxyData10+ + +Defines the subscription information about the widget update by proxy. + +**System capability**: SystemCapability.Ability.Form + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| key | string | Yes| Subscriber ID of the widget update by proxy. The value is the same as that of the data publisher.| +| subscriberId | string | No| Subscription condition of the widget update by proxy. The default value is the current widget ID (specified by **formId**).| + + ## FormBindingData Describes a **FormBindingData** object. @@ -21,7 +34,7 @@ Describes a **FormBindingData** object. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | data | Object | Yes| Data to be displayed on the JS widget. The value can be an object containing multiple key-value pairs or a string in JSON format.| - +| proxies10+ | Array<[ProxyData](#proxydata)> | No| Subscription information of the widget update by proxy. The default value is an empty array.| ## createFormBindingData @@ -62,3 +75,14 @@ try { console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` + +## ProxyData + +Defines the widget proxy data. + +**System capability**: SystemCapability.Ability.Form + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| key | string | Yes| Key of the proxy. The value depends on the data publisher.| +| subscriberId | string | No| Subscriber ID. The value depends on the data publisher. The default value is the current widget ID.| diff --git a/en/application-dev/reference/apis/js-apis-app-form-formHost.md b/en/application-dev/reference/apis/js-apis-app-form-formHost.md index d81c78c439f21e0ce60ff3df6e33c3d949ee980a..97080042f95b5398709c2790a3217333c8437e19 100644 --- a/en/application-dev/reference/apis/js-apis-app-form-formHost.md +++ b/en/application-dev/reference/apis/js-apis-app-form-formHost.md @@ -1563,7 +1563,7 @@ Unsubscribes from widget uninstall events. This API uses an asynchronous callbac | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | type | string | Yes | Event type. The value **'formUninstall'** indicates a widget uninstall event.| -| callback | Callback<string> | No| Callback used to return the widget ID. If it is left unspecified, it indicates the callback for all the events that have been subscribed.
To cancel the subscription with a given callback, this parameter must be set to the same value as **callback** in **on('formUninstall')**. | +| callback | Callback<string> | No| Callback used to return the widget ID. If it is left unspecified, it indicates the callback for all the events that have been subscribed.
To cancel the subscription with a given callback, this parameter must be set to the same value as **callback** in **on('formUninstall')**.| **Error codes** @@ -1698,8 +1698,8 @@ Unsubscribes from widget removal events. This API uses an asynchronous callback | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | type | string | Yes | Event type. The value **'formRemove'** indicates a widget removal event.| -| callback | Callback<formInfo.RunningFormInfo> | No| Callback used to return **RunningFormInfo**. By default, all the subscriptions to the specified event are canceled.
To cancel the subscription with a given callback, this parameter must be set to the same value as **callback** in **on('formRemove')**. | -| bundleName | string | No| Name of the bundle that functions as the widget host.
To cancel the subscription for a given bundle name, this parameter must be set to the same value as **bundleName** in **on('formRemove')**.
By default, the subscriptions for all the widget hosts are canceled. | +| callback | Callback<formInfo.RunningFormInfo> | No| Callback used to return **RunningFormInfo**. By default, all the subscriptions to the specified event are canceled.
To cancel the subscription with a given callback, this parameter must be set to the same value as **callback** in **on('formRemove')**.| +| bundleName | string | No| Name of the bundle that functions as the widget host.
To cancel the subscription for a given bundle name, this parameter must be set to the same value as **bundleName** in **on('formRemove')**.
By default, the subscriptions for all the widget hosts are canceled.| **Example** @@ -2148,6 +2148,8 @@ Requests data from the widget provider. This API uses an asynchronous callback t | Error Code ID| Error Message| | -------- | -------- | +| 201 | Permissions denied. | +| 401 | If the input parameter is not valid parameter. | | 16500050 | An IPC connection error happened. | | 16500060 | A service connection error happened, please try again later. | | 16500100 | Failed to obtain the configuration information. | @@ -2162,9 +2164,11 @@ import formHost from '@ohos.app.form.formHost'; let formId = '12400633174999288'; try { - formHost.acquireFormData(formId, (error) => { + formHost.acquireFormData(formId, (error, data) => { if (error) { console.error(`error, code: ${error.code}, message: ${error.message}`); + } else { + console.log('formHost acquireFormData, data: ${JSON.stringify(data)}'); } }); } catch(error) { @@ -2192,12 +2196,14 @@ Requests data from the widget provider. This API uses a promise to return the re | Type | Description | | ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Promise<{[key: string]: Object}>| Promise used to return the API call result and the shared data.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | +| 201 | Permissions denied. | +| 401 | If the input parameter is not valid parameter. | | 16500050 | An IPC connection error happened. | | 16500060 | A service connection error happened, please try again later. | | 16500100 | Failed to obtain the configuration information. | @@ -2210,8 +2216,8 @@ import formHost from '@ohos.app.form.formHost'; let formId = '12400633174999288'; try { - formHost.acquireFormData(formId).then(() => { - console.log('formHost acquireFormData success'); + formHost.acquireFormData(formId).then((data) => { + console.log('formHost acquireFormData success' + data); }).catch((error) => { console.error(`error, code: ${error.code}, message: ${error.message}`); }); @@ -2248,9 +2254,14 @@ For details about the error codes, see [Form Error Codes](../errorcodes/errorcod | Error Code ID| Error Message| | -------- | -------- | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | | 16500050 | An IPC connection error happened. | +| 16500100 | Failed to obtain the configuration information. | | 16501000 | An internal functional error occurred. | + ```ts import formHost from '@ohos.app.form.formHost'; @@ -2273,7 +2284,7 @@ try { ## getRunningFormInfosByFilter10+ -getRunningFormInfosByFilter(formProviderFilter: formInfo.FormProviderFilter, callback: AsyncCallback<Array<formInfo.FormInfo>>): void +getRunningFormInfosByFilter(formProviderFilter: formInfo.FormProviderFilter, callback: AsyncCallback<Array<formInfo.RunningFormInfo>>): void Obtains the information about widget hosts based on the widget provider information. This API uses an asynchronous callback to return the result. @@ -2285,8 +2296,8 @@ Obtains the information about widget hosts based on the widget provider informat | Name | Type | Mandatory| Description | | ----------- | --------------- | ---- | -------------------------------- | -| formProviderFilter | formInfo.FormProviderFilter [formInfo.FormProviderFilter](js-apis-app-form-formInfo.md#formProviderFilter) | Yes | Information about the widget provider.| -| callback | AsyncCallback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the result. If the widget host information is obtained, **error** is **undefined** and **data** is the information obtained; otherwise, **data** is an error object.| +| formProviderFilter | [formInfo.FormProviderFilter](js-apis-app-form-formInfo.md#formProviderFilter) | Yes | Information about the widget provider.| +| callback | AsyncCallback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the result. If the widget host information is obtained, **error** is **undefined** and **data** is the information obtained; otherwise, **error** is an error object.| **Error codes** @@ -2294,9 +2305,14 @@ For details about the error codes, see [Form Error Codes](../errorcodes/errorcod | Error Code ID| Error Message| | -------- | -------- | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | | 16500050 | An IPC connection error happened. | +| 16500100 | Failed to obtain the configuration information. | | 16501000 | An internal functional error occurred. | + ```ts import formHost from '@ohos.app.form.formHost'; @@ -2321,7 +2337,8 @@ try { ## getRunningFormInfoById10+ -getRunningFormInfoById(formId: string): Promise<Array<formInfo.RunningFormInfo>> +function getRunningFormInfoById(formId: string): Promise<formInfo.RunningFormInfo> + Obtains the information about widget hosts based on the widget ID. This API uses a promise to return the result. @@ -2339,7 +2356,7 @@ Obtains the information about widget hosts based on the widget ID. This API uses | Type | Description | | ------------------- | ------------------------- | -| Promise<Array<formInfo.RunningFormInfo[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the widget host information obtained. | +| Promise<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)> | Promise used to return the widget host information obtained.| **Error codes** @@ -2347,9 +2364,14 @@ For details about the error codes, see [Form Error Codes](../errorcodes/errorcod | Error Code ID| Error Message| | -------- | -------- | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | | 16500050 | An IPC connection error happened. | +| 16500100 | Failed to obtain the configuration information. | | 16501000 | An internal functional error occurred. | + ```ts import formHost from '@ohos.app.form.formHost'; let formId = '12400633174999288'; @@ -2366,7 +2388,7 @@ try { ## getRunningFormInfoById10+ -getRunningFormInfoById(formId: string, callback: AsyncCallback<Array<formInfo.FormInfo>>): void +getRunningFormInfoById(formId: string, callback: AsyncCallback<formInfo.RunningFormInfo>): void Obtains the information about widget hosts based on the widget ID. This API uses an asynchronous callback to return the result. @@ -2379,7 +2401,7 @@ Obtains the information about widget hosts based on the widget ID. This API uses | Name | Type | Mandatory| Description | | ----------- | --------------- | ---- | -------------------------------- | | formId | string | Yes | Widget ID.| -| callback | AsyncCallback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the result. If the widget host information is obtained, **error** is **undefined** and **data** is the information obtained; otherwise, **data** is an error object.| +| callback | AsyncCallback<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)> | Yes| Callback used to return the result. If the widget host information is obtained, **error** is **undefined** and **data** is the information obtained; otherwise, **error** is an error object.| **Error codes** @@ -2387,7 +2409,11 @@ For details about the error codes, see [Form Error Codes](../errorcodes/errorcod | Error Code ID| Error Message| | -------- | -------- | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | | 16500050 | An IPC connection error happened. | +| 16500100 | Failed to obtain the configuration information. | | 16501000 | An internal functional error occurred. | ```ts @@ -2406,3 +2432,145 @@ try { console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` + +## on('notifyVisible')10+ + + on(type: 'notifyVisible', observerCallback: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>, bundleName?: string): void + +Subscribes to events indicating that a widget becomes visible. + +This event is triggered when **notifyVisibleForms** is called to make a widget visible. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. This value **'notifyVisible'** indicates a widget visibility event. | +| callback | Callback <Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | Yes | Callback used to return **RunningFormInfo** of the widget. | +| bundleName | string | No | Name of the bundle that functions as the widget host, on which the widget visibility state changes are subscribed.| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; +let bundleName = 'ohos.samples.FormApplication'; +let callback = function(data) { + console.log('form change visibility, data: ${JSON.stringify(data)'); +} + +formHost.on('notifyVisible', callback); +formHost.on('notifyVisible', callback, bundleName); +``` + +## off('notifyVisible')10+ + + off(type: "notifyVisible", observerCallback?: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>, bundleName?: string): void + +Unsubscribes from events indicating that a widget becomes visible. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. This value **'notifyVisible'** indicates a widget visibility event.| +| callback | Callback <Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | No | Callback registered during the subscription. By default, all the subscriptions to the specified event are canceled.
To cancel the subscription with a given callback, this parameter must be set to the same value as **callback** in **on('notifyVisible')**.| +| bundleName | string | No | Name of the bundle that functions as the widget host, on which the widget visibility state changes are subscribed.
To cancel the subscription for a given bundle name, this parameter must be set to the same value as **bundleName** in **on('notifyVisible')**. | + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; +let bundleName = 'ohos.samples.FormApplication'; +let callback = function(data) { + console.log('form change visibility, data: ${JSON.stringify(data)'); +} + +formHost.off('notifyVisible', callback); +formHost.off('notifyVisible', callback, bundleName); +``` + +> **NOTE** +> +> - **on('notifyVisible', callback)** and **off('notifyVisible', callback)** must be used in pairs. +> - **on('notifyVisible', callback, bundleName)** and **off('notifyVisible', callback, bundleName)** must be used in pairs. +> - To cancel the subscription with a given callback or for a given bundle name, the **callback** or **bundleName** parameter in **off()** must be set to the same value as that in **on()**. + + + +## on('notifyInvisible')10+ + + on(type: 'notifyInvisible', observerCallback: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>, bundleName?: string): void + +Subscribes to events indicating that a widget becomes invisible. + +This event is triggered when **notifyInvisibleForms** is called to make a widget invisible. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. This value **'notifyInvisible'** indicates a widget invisibility event. | +| callback | Callback <Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | Yes | Callback used to return **RunningFormInfo** of the widget. | +| bundleName | string | No | Name of the bundle that functions as the widget host, on which the widget visibility state changes are subscribed.| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; +let bundleName = 'ohos.samples.FormApplication'; +let callback = function(data) { + console.log('form change invisibility, data: ${JSON.stringify(data)'); +} + +formHost.on('notifyInvisible', callback); +formHost.on('notifyInvisible', callback, bundleName); +``` + +## off('notifyInvisible')10+ + + off(type: "notifyInvisible", observerCallback?: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>, bundleName?: string): void + +Unsubscribes from events indicating that a widget becomes invisible. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. This value **'notifyInvisible'** indicates a widget invisibility event. | +| callback | Callback <Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | No | Callback registered during the subscription. By default, all the subscriptions to the specified event are canceled.
To cancel the subscription with a given callback, this parameter must be set to the same value as **callback** in **on('notifyInvisible')**.| +| bundleName | string | No | Name of the bundle that functions as the widget host, on which the widget visibility state changes are subscribed.
To cancel the subscription for a given bundle name, this parameter must be set to the same value as **bundleName** in **on('notifyInvisible')**. | + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; +let bundleName = 'ohos.samples.FormApplication'; +let callback = function(data) { + console.log('form change invisibility, data: ${JSON.stringify(data)'); +} + +formHost.off('notifyInvisible', callback); +formHost.off('notifyInvisible', callback, bundleName); +``` + +> **NOTE** +> +> - **on('notifyInvisible', callback)** and **off('notifyInvisible', callback)** must be used in pairs. +> - **on('notifyInvisible', callback, bundleName)** and **off('notifyInvisible', callback, bundleName)** must be used in pairs. +> - To cancel the subscription with a given callback or for a given bundle name, the **callback** or **bundleName** parameter in **off()** must be set to the same value as that in **on()**. diff --git a/en/application-dev/reference/apis/js-apis-app-form-formInfo.md b/en/application-dev/reference/apis/js-apis-app-form-formInfo.md index 0e560c76f4f6dc155a0c0c99ef3be8b63b7f1131..cf0b272142873600a264ba6df959afdcd0c07f6d 100644 --- a/en/application-dev/reference/apis/js-apis-app-form-formInfo.md +++ b/en/application-dev/reference/apis/js-apis-app-form-formInfo.md @@ -18,8 +18,6 @@ Describes widget information. **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - | Name | Type | Readable | Writable | Description | | ----------- | -------- | -------- | -------------------- | ------------------------------------------------------------ | | bundleName | string | Yes | No | Name of the bundle to which the widget belongs. | @@ -27,6 +25,7 @@ Describes widget information. | abilityName | string | Yes | No | Name of the ability to which the widget belongs. | | name | string | Yes | No | Widget name. | | description | string | Yes | No | Description of the widget. | +| descriptionId | number | Yes | No | ID of the widget description. | | type | [FormType](#formtype) | Yes | No | Type of the widget. Currently, only JS widgets are supported.| | jsComponentName | string | Yes | No | Name of the component used in the JS widget. | | colorMode | [ColorMode](#colormode) | Yes | No | Color mode of the widget. | @@ -102,7 +101,7 @@ Enumerates the widget parameters. | HEIGHT_KEY | 'ohos.extra.param.key.form_height' | Widget height. | | TEMPORARY_KEY | 'ohos.extra.param.key.form_temporary' | Temporary widget. | | ABILITY_NAME_KEY | 'ohos.extra.param.key.ability_name' | Ability name. | -| DEVICE_ID_KEY | 'ohos.extra.param.key.device_id'
**System API**: This is a system API and cannot be called by third-party applications. | Device ID. | +| DEVICE_ID_KEY | 'ohos.extra.param.key.device_id' | Device ID.
**System API**: This is a system API and cannot be called by third-party applications. | | BUNDLE_NAME_KEY | 'ohos.extra.param.key.bundle_name' | Key that specifies the target bundle name.| | LAUNCH_REASON_KEY10+ | 'ohos.extra.param.key.form_launch_reason' | Reason for creating the widget. | | PARAM_FORM_CUSTOMIZE_KEY10+ | 'ohos.extra.param.key.form_customize' | Custom data. | @@ -128,9 +127,9 @@ Defines the widget information filter. Only the widget information that meets th **System capability**: SystemCapability.Ability.Form -| Name | Type | Description | -| ----------- | ---- | ------------ | -| moduleName | string | Optional. Only the information about the widget whose **moduleName** is the same as the provided value is returned.
If this parameter is not set, **moduleName** is not used for filtering. | +| Name | Type | Mandatory |Description | +| ----------- | ---- | ------------ |------------ | +| moduleName | string |No | Optional. Only the information about the widget whose **moduleName** is the same as the provided value is returned.
If this parameter is not set, **moduleName** is not used for filtering. | ## VisibilityType @@ -140,7 +139,7 @@ Enumerates the visibility types of the widget. | Name | Value | Description | | ----------- | ---- | ------------ | -| UNKNOWN | 0 | The visibility type of the widget is unknown.| +| UNKNOWN10+ | 0 | The visibility type of the widget is unknown.| | FORM_VISIBLE | 1 | The widget is visible.| | FORM_INVISIBLE | 2 | The widget is invisible.| @@ -150,6 +149,8 @@ Defines the information about the widget host. **System capability**: SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. + | Name | Type | Readable | Writable | Description | | ----------- | -------- | -------- | -------------------- | ------------------------------------------------------------ | | formId | string | Yes | No | Widget ID. | diff --git a/en/application-dev/reference/apis/js-apis-app-form-formProvider.md b/en/application-dev/reference/apis/js-apis-app-form-formProvider.md index 48618a9e2e6cf7a60232583133399f427a29b5a8..4d5aca1c9d6b6c05965c09518c2999c01558eebd 100644 --- a/en/application-dev/reference/apis/js-apis-app-form-formProvider.md +++ b/en/application-dev/reference/apis/js-apis-app-form-formProvider.md @@ -539,7 +539,7 @@ Checks whether a widget can be published to the widget host. This API uses an as | Error Code ID| Error Message| | -------- | -------- | -| 202 | The application is not a system application. | +| 202 | If the application is not a system application. | | 401 | If the input parameter is not valid parameter. | | 16500050 | An IPC connection error happened. | | 16501000 | An internal functional error occurred. | @@ -602,7 +602,7 @@ Checks whether a widget can be published to the widget host. This API uses a pro | Error Code ID| Error Message| | -------- | -------- | -| 202 | The application is not a system application. | +| 202 | If the application is not a system application. | | 16500050 | An IPC connection error happened. | | 16501000 | An internal functional error occurred. | diff --git a/en/application-dev/reference/apis/js-apis-arkui-UIContext.md b/en/application-dev/reference/apis/js-apis-arkui-UIContext.md new file mode 100644 index 0000000000000000000000000000000000000000..8afcf3acf26dfff247c8a9f6831543ac12658b2f --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-arkui-UIContext.md @@ -0,0 +1,1691 @@ +# @ohos.arkui.UIContext (UIContext) + +In the stage model, a window stage or window can use the **loadContent** API to load pages, create a UI instance, and render page content to the associated window. Naturally, UI instances and windows are associated on a one-by-one basis. Some global UI APIs are executed in the context of certain UI instances. When calling these APIs, you must identify the UI context, and consequently UI instance, by tracing the call chain. If these APIs are called on a non-UI page or in some asynchronous callback, the current UI context may fail to be identified, resulting in failure in API execution. + +**@ohos.window** adds the [getUIContext](./js-apis-window.md#getuicontext10) API in API version 10 for obtaining the **UIContext** object of a UI instance. The API provided by the **UIContext** object can be directly applied to the corresponding UI instance. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer. + +## UIContext + +In the following API examples, you must first use [getUIContext()](./js-apis-window.md#getuicontext10) in **@ohos.window** to obtain a **UIContext** instance, and then call the APIs using the obtained instance. In this document, the **UIContext** instance is represented by **uiContext**. + +### getFont + +getFont(): Font + +Obtains a **Font** object. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| ----- | ----------------- | +| [Font](#font) | **Font** object.| + +**Example** + +```ts +uiContext.getFont(); +``` + +### getMediaQuery + +getMediaQuery(): MediaQuery + +Obtains a **MediaQuery** object. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| ----- | ----------------- | +| [MediaQuery](#mediaquery) | **MediaQuery** object.| + +**Example** + +```ts +uiContext.getMediaQuery(); +``` + +### getRouter + +getRouter(): Router + +Obtains a **Router** object. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| ----- | ----------------- | +| [Router](#router) | **Router** object.| + +**Example** + +```ts +uiContext.getRouter(); +``` + +### getPromptAction + +getPromptAction(): PromptAction + +Obtains a **PromptAction** object. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| ----- | ----------------- | +| [PromptAction](#promptaction) | **PromptAction** object.| + +**Example** + +```ts +uiContext.getPromptAction(); +``` + +### animateTo + +animateTo(value: AnimateParam, event: () => void): void + +Applies a transition animation for state changes. + +Since API version 9, this API is supported in ArkTS widgets. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------------- | ------------ | -------------------- | -------------------- | +| value | [AnimateParam](../arkui-ts/ts-explicit-animation.md#animateparam) | Yes| Animation settings.| +| event | () => void | Yes| Closure function that displays the dynamic effect. The system automatically inserts the transition animation if the status changes in the closure function.| + +**Example** + +```ts +// xxx.ets +@Entry +@Component +struct AnimateToExample { + @State widthSize: number = 250 + @State heightSize: number = 100 + @State rotateAngle: number = 0 + private flag: boolean = true + + build() { + Column() { + Button('change size') + .width(this.widthSize) + .height(this.heightSize) + .margin(30) + .onClick(() => { + if (this.flag) { + uiContext.animateTo({ + duration: 2000, + curve: Curve.EaseOut, + iterations: 3, + playMode: PlayMode.Normal, + onFinish: () => { + console.info('play end') + } + }, () => { + this.widthSize = 150 + this.heightSize = 60 + }) + } else { + uiContext.animateTo({}, () => { + this.widthSize = 250 + this.heightSize = 100 + }) + } + this.flag = !this.flag + }) + Button('change rotate angle') + .margin(50) + .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle }) + .onClick(() => { + uiContext.animateTo({ + duration: 1200, + curve: Curve.Friction, + delay: 500, + iterations: -1, // The value -1 indicates that the animation is played for an unlimited number of times. + playMode: PlayMode.Alternate, + onFinish: () => { + console.info('play end') + } + }, () => { + this.rotateAngle = 90 + }) + }) + }.width('100%').margin({ top: 5 }) + } +} +``` + +### showAlertDialog + +showAlertDialog(options: AlertDialogParamWithConfirm | AlertDialogParamWithButtons): void + +Shows an alert dialog box. + +**Parameters** + +| Name | Type | Description| +| ---- | --------------- | -------- | +| options | [AlertDialogParamWithConfirm](../arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithconfirm) \| [AlertDialogParamWithButtons](../arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithbuttons) | Defines and displays the **\** component.| + +**Example** + +```ts +uiContext.showAlertDialog( + { + title: 'title', + message: 'text', + autoCancel: true, + alignment: DialogAlignment.Bottom, + offset: { dx: 0, dy: -20 }, + gridCount: 3, + confirm: { + value: 'button', + action: () => { + console.info('Button-clicking callback') + } + }, + cancel: () => { + console.info('Closed callbacks') + } + } +) +``` + +### showActionSheet + +showActionSheet(value: ActionSheetOptions): void + +Defines and shows the action sheet. + +**ActionSheetOptions parameters** + +| Name | Type | Mandatory | Description | +| ---------- | -------------------------- | ------- | ----------------------------- | +| title | [Resource](../arkui-ts/ts-types.md#resource) \| string | Yes | Title of the dialog box.| +| message | [Resource](../arkui-ts/ts-types.md#resource) \| string | Yes | Content of the dialog box. | +| autoCancel | boolean | No | Whether to close the dialog box when the overlay is clicked.
Default value: **true**| +| confirm | {
value: [ResourceStr](../arkui-ts/ts-types.md#resourcestr),
action: () => void
} | No | Text content of the confirm button and callback upon button clicking.
Default value:
**value**: button text.
**action**: callback upon button clicking.| +| cancel | () => void | No | Callback invoked when the dialog box is closed after the overlay is clicked. | +| alignment | [DialogAlignment](../arkui-ts/ts-methods-alert-dialog-box.md#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.
Default value: **DialogAlignment.Bottom**| +| offset | {
dx: [Length](../arkui-ts/ts-types.md#length),
dy: [Length](../arkui-ts/ts-types.md#length)
} | No | Offset of the dialog box relative to the alignment position.{
dx: 0,
dy: 0
} | +| sheets | Array<SheetInfo> | Yes | Options in the dialog box. Each option supports the image, text, and callback.| + +**SheetInfo parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ----------------- | +| title | [ResourceStr](../arkui-ts/ts-types.md#resourcestr) | Yes | Text of the option. | +| icon | [ResourceStr](../arkui-ts/ts-types.md#resourcestr) | No | Sheet icon. By default, no icon is displayed. | +| action | ()=>void | Yes | Callback when the sheet is selected.| + +**Example** + +```ts +uiContext.showActionSheet({ + title: 'ActionSheet title', + message: 'message', + autoCancel: true, + confirm: { + value: 'Confirm button', + action: () => { + console.log('Get Alert Dialog handled') + } + }, + cancel: () => { + console.log('actionSheet canceled') + }, + alignment: DialogAlignment.Bottom, + offset: { dx: 0, dy: -10 }, + sheets: [ + { + title: 'apples', + action: () => { + console.log('apples') + } + }, + { + title: 'bananas', + action: () => { + console.log('bananas') + } + }, + { + title: 'pears', + action: () => { + console.log('pears') + } + } + ] +}) +``` + +### showDatePickerDialog + +showDatePickerDialog(options: DatePickerDialogOptions): void + +Shows a date picker dialog box. + +**DatePickerDialogOptions parameters** + +| Name| Type| Mandatory| Default Value| Description| +| -------- | -------- | -------- | -------- | -------- | +| start | Date | No| Date('1970-1-1') | Start date of the picker.| +| end | Date | No| Date('2100-12-31') | End date of the picker.| +| selected | Date | No| Current system date| Selected date.| +| lunar | boolean | No| false | Whether to display the lunar calendar.| +| showTime | boolean | No| false | Whether to display the time item.| +| useMilitaryTime | boolean | No| false | Whether to display time in 24-hour format.| +| disappearTextStyle | [PickerTextStyle](../arkui-ts/ts-basic-components-datepicker.md#pickertextstyle10) | No| - | Font color, font size, and font width for the top and bottom items.| +| textStyle | [PickerTextStyle](../arkui-ts/ts-basic-components-datepicker.md#pickertextstyle10) | No| - | Font color, font size, and font width of all items except the top, bottom, and selected items.| +| selectedTextStyle | [PickerTextStyle](../arkui-ts/ts-basic-components-datepicker.md#pickertextstyle10) | No| - | Font color, font size, and font width of the selected item.| +| onAccept | (value: [DatePickerResult](../arkui-ts/ts-basic-components-datepicker.md#datepickerresult)) => void | No| - | Callback invoked when the OK button in the dialog box is clicked.| +| onCancel | () => void | No| - | Callback invoked when the Cancel button in the dialog box is clicked.| +| onChange | (value: [DatePickerResult](../arkui-ts/ts-basic-components-datepicker.md#datepickerresult)) => void | No| - | Callback invoked when the selected item in the picker changes.| + +**Example** + +```ts +let selectedDate: Date = new Date("2010-1-1") +uiContext.showDatePickerDialog({ + start: new Date("2000-1-1"), + end: new Date("2100-12-31"), + selected: selectedDate, + onAccept: (value: DatePickerResult) => { + // Use the setFullYear method to set the date when the OK button is touched. In this way, when the date picker dialog box is displayed again, the selected date is the date last confirmed. + selectedDate.setFullYear(value.year, value.month, value.day) + console.info("DatePickerDialog:onAccept()" + JSON.stringify(value)) + }, + onCancel: () => { + console.info("DatePickerDialog:onCancel()") + }, + onChange: (value: DatePickerResult) => { + console.info("DatePickerDialog:onChange()" + JSON.stringify(value)) + } +}) +``` + +### showTimePickerDialog + +showTimePickerDialog(options: TimePickerDialogOptions): void + +Shows a time picker dialog box. + +**TimePickerDialogOptions parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| selected | Date | No| Selected time.
Default value: current system time| +| useMilitaryTime | boolean | No| Whether to display time in 24-hour format. The 12-hour format is used by default.
Default value: **false**| +| disappearTextStyle | [PickerTextStyle](../arkui-ts/ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width for the top and bottom items.| +| textStyle | [PickerTextStyle](../arkui-ts/ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of all items except the top, bottom, and selected items.| +| selectedTextStyle | [PickerTextStyle](../arkui-ts/ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of the selected item.| +| onAccept | (value: [TimePickerResult](../arkui-ts/ts-basic-components-timepicker.md#timepickerresult)) => void | No| Callback invoked when the OK button in the dialog box is clicked.| +| onCancel | () => void | No| Callback invoked when the Cancel button in the dialog box is clicked.| +| onChange | (value: [TimePickerResult](../arkui-ts/ts-basic-components-timepicker.md#timepickerresult)) => void | No| Callback invoked when the selected time changes.| + +**Example** + +```ts +let selectTime: Date = new Date('2020-12-25T08:30:00') +uiContext.showTimePickerDialog({ + selected: this.selectTime, + onAccept: (value: TimePickerResult) => { + // Set selectTime to the time when the OK button is clicked. In this way, when the dialog box is displayed again, the selected time is the time when the operation was confirmed last time. + this.selectTime.setHours(value.hour, value.minute) + console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)) + }, + onCancel: () => { + console.info("TimePickerDialog:onCancel()") + }, + onChange: (value: TimePickerResult) => { + console.info("TimePickerDialog:onChange()" + JSON.stringify(value)) + } +}) +``` + +### showTextPickerDialog + +showTextPickerDialog(options: TextPickerDialogOptions): void + +Shows a text picker in the given settings. + +**TextPickerDialogOptions parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| range | string[] \| [Resource](../arkui-ts/ts-types.md#resource)\|[TextPickerRangeContent](../arkui-ts/ts-basic-components-textpicker.md#textpickerrangecontent10)[] | Yes| Data selection range of the picker. This parameter cannot be set to an empty array. If set to an empty array, it will not be displayed.| +| selected | number | No| Index of the selected item.
Default value: **0**| +| value | string | No | Text of the selected item. This parameter does not take effect when the **selected** parameter is set. If the value is not within the range, the first item in the range is used instead.| +| defaultPickerItemHeight | number \| string | No| Height of the picker item.| +| disappearTextStyle | [PickerTextStyle](../arkui-ts/ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width for the top and bottom items.| +| textStyle | [PickerTextStyle](../arkui-ts/ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of all items except the top, bottom, and selected items.| +| selectedTextStyle | [PickerTextStyle](../arkui-ts/ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of the selected item.| +| onAccept | (value: [TextPickerResult](../arkui-ts/ts-methods-textpicker-dialog.md#textpickerresult)) => void | No| Callback invoked when the OK button in the dialog box is clicked.| +| onCancel | () => void | No| Callback invoked when the Cancel button in the dialog box is clicked.| +| onChange | (value: [TextPickerResult](../arkui-ts/ts-methods-textpicker-dialog.md#textpickerresult)) => void | No| Callback invoked when the selected item changes.| + +**Example** + +```ts +let select: number = 2 +let fruits: string[] = ['apple1', 'orange2', 'peach3', 'grape4', 'banana5'] +uiContext.showTextPickerDialog({ + range: this.fruits, + selected: this.select, + onAccept: (value: TextPickerResult) => { + // Set select to the index of the item selected when the OK button is touched. In this way, when the text picker dialog box is displayed again, the selected item is the one last confirmed. + this.select = value.index + console.info("TextPickerDialog:onAccept()" + JSON.stringify(value)) + }, + onCancel: () => { + console.info("TextPickerDialog:onCancel()") + }, + onChange: (value: TextPickerResult) => { + console.info("TextPickerDialog:onChange()" + JSON.stringify(value)) + } +}) +``` + +### createAnimator + +createAnimator(options: AnimatorOptions): AnimatorResult + +Creates an **Animator** object. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ----------------------------------- | ---- | ------- | +| options | [AnimatorOptions](./js-apis-animator.md#animatoroptions) | Yes | Animator options.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------- | +| [AnimatorResult](./js-apis-animator.md#animatorresult) | Animator result.| + +**Example** + +```ts +let options = { + duration: 1500, + easing: "friction", + delay: 0, + fill: "forwards", + direction: "normal", + iterations: 3, + begin: 200.0, + end: 400.0 +}; +uiContext.createAnimator(options); +``` + +### runScopedTask + +runScopedTask(callback: () => void): void + +Executes the specified callback in this UI context. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ----------------------------------- | ---- | ------- | +| callback | () => void | Yes | Callback used to return the result.| + +**Example** + +```ts +uiContext.runScopedTask( + () => { + console.log('Succeeded in runScopedTask'); + } +); +``` + +## Font + +In the following API examples, you must first use [getFont()](#getfont) in **UIContext** to obtain a **Font** instance, and then call the APIs using the obtained instance. + +### registerFont + +registerFont(options: FontOptions): void + +Registers a custom font with the font manager. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | --------------------------- | ---- | ----------- | +| options | [FontOptions](js-apis-font.md#fontoptions) | Yes | Information about the custom font to register.| + +**Example** + +```ts +let font = uiContext.getFont(); +font.registerFont({ + familyName: 'medium', + familySrc: '/font/medium.ttf' +}); +``` + +## MediaQuery + +In the following API examples, you must first use [getMediaQuery()](#getmediaquery) in **UIContext** to obtain a **MediaQuery** instance, and then call the APIs using the obtained instance. + +### matchMediaSync + +matchMediaSync(condition: string): MediaQueryListener + +Sets the media query criteria and returns the corresponding listening handle. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | ---------------------------------------- | +| condition | string | Yes | Media query condition. For details, see [Syntax](../../ui/arkts-layout-development-media-query.md#syntax).| + +**Return value** + +| Type | Description | +| ------------------ | ---------------------- | +| MediaQueryListener | Listening handle to a media event, which is used to register or deregister the listening callback.| + +**Example** + +```ts +let mediaquery = uiContext.getMediaQuery(); +let listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. +``` + +## Router + +In the following API examples, you must first use [getRouter()](#getrouter) in **UIContext** to obtain a **Router** instance, and then call the APIs using the obtained instance. + +### pushUrl + +pushUrl(options: RouterOptions): Promise<void> + +Navigates to a specified page in the application. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | --------- | +| options | [RouterOptions](js-apis-router.md#routeroptions) | Yes | Page routing parameters.| + +**Return value** + +| Type | Description | +| ------------------- | --------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found. | +| 100002 | if the uri is not exist. | +| 100003 | if the pages are pushed too much. | + +**Example** + +```ts +let router = uiContext.getRouter(); +router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + } + } +}) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + }) +``` + +### pushUrl + +pushUrl(options: RouterOptions, callback: AsyncCallback<void>): void + +Navigates to a specified page in the application. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | --------- | +| options | [RouterOptions](js-apis-router.md#routeroptions) | Yes | Page routing parameters.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found. | +| 100002 | if the uri is not exist. | +| 100003 | if the pages are pushed too much. | + +**Example** + +```ts +let router = uiContext.getRouter(); +router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + } + } +}, (err) => { + if (err) { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('pushUrl success'); +}) +``` + +### pushUrl + +pushUrl(options: RouterOptions, mode: RouterMode): Promise<void> + +Navigates to a specified page in the application. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------- | +| options | [RouterOptions](js-apis-router.md#routeroptions) | Yes | Page routing parameters. | +| mode | [RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| + +**Return value** + +| Type | Description | +| ------------------- | --------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found. | +| 100002 | if the uri is not exist. | +| 100003 | if the pages are pushed too much. | + +**Example** + +```ts +let router = uiContext.getRouter(); +router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + } + } +}, router.RouterMode.Standard) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + }) +``` + +### pushUrl + +pushUrl(options: RouterOptions, mode: RouterMode, callback: AsyncCallback<void>): void + +Navigates to a specified page in the application. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------- | +| options | [RouterOptions](js-apis-router.md#routeroptions) | Yes | Page routing parameters. | +| mode | [RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found. | +| 100002 | if the uri is not exist. | +| 100003 | if the pages are pushed too much. | + +**Example** + +```ts +let router = uiContext.getRouter(); +router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + } + } +}, router.RouterMode.Standard, (err) => { + if (err) { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('pushUrl success'); +}) +``` + +### replaceUrl + +replaceUrl(options: RouterOptions): Promise<void> + +Replaces the current page with another one in the application and destroys the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | ------------------ | +| options | [RouterOptions](js-apis-router.md#routeroptions) | Yes | Description of the new page.| + +**Return value** + +| Type | Description | +| ------------------- | --------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found, only throw in standard system. | +| 200002 | if the uri is not exist. | + +**Example** + +```ts +let router = uiContext.getRouter(); +router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message' + } +}) + .then(() => { + // success + }) + .catch(err => { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + }) +``` + +### replaceUrl + +replaceUrl(options: RouterOptions, callback: AsyncCallback<void>): void + +Replaces the current page with another one in the application and destroys the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | ------------------ | +| options | [RouterOptions](js-apis-router.md#routeroptions) | Yes | Description of the new page.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found, only throw in standard system. | +| 200002 | if the uri is not exist. | + +**Example** + +```ts +let router = uiContext.getRouter(); +router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message' + } +}, (err) => { + if (err) { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('replaceUrl success'); +}) +``` + +### replaceUrl + +replaceUrl(options: RouterOptions, mode: RouterMode): Promise<void> + +Replaces the current page with another one in the application and destroys the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------- | +| options | [RouterOptions](js-apis-router.md#routeroptions) | Yes | Description of the new page. | +| mode | [RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| + +**Return value** + +| Type | Description | +| ------------------- | --------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if can not get the delegate, only throw in standard system. | +| 200002 | if the uri is not exist. | + +**Example** + +```ts +let router = uiContext.getRouter(); +router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message' + } +}, router.RouterMode.Standard) + .then(() => { + // success + }) + .catch(err => { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + }) +``` + +### replaceUrl + +replaceUrl(options: RouterOptions, mode: RouterMode, callback: AsyncCallback<void>): void + +Replaces the current page with another one in the application and destroys the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------- | +| options | [RouterOptions](js-apis-router.md#routeroptions) | Yes | Description of the new page. | +| mode | [RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found, only throw in standard system. | +| 200002 | if the uri is not exist. | + +**Example** + +```ts +let router = uiContext.getRouter(); +router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message' + } +}, router.RouterMode.Standard, (err) => { + if (err) { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('replaceUrl success'); +}); +``` + +### pushNamedRoute + +pushNamedRoute(options: NamedRouterOptions): Promise<void> + +Navigates to a page using the named route. This API uses a promise to return the result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | --------- | +| options | [NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Page routing parameters.| + +**Return value** + +| Type | Description | +| ------------------- | --------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found. | +| 100003 | if the pages are pushed too much. | +| 100004 | if the named route is not exist. | + +**Example** + +```ts +let router = uiContext.getRouter(); +router.pushNamedRoute({ + name: 'myPage', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + } + } +}) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); + }) +``` + +### pushNamedRoute + +pushNamedRoute(options: NamedRouterOptions, callback: AsyncCallback<void>): void + +Navigates to a page using the named route. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | --------- | +| options | [NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Page routing parameters.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found. | +| 100003 | if the pages are pushed too much. | +| 100004 | if the named route is not exist. | + +**Example** + +```ts +let router = uiContext.getRouter(); +router.pushNamedRoute({ + name: 'myPage', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + } + } +}, (err) => { + if (err) { + console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('pushNamedRoute success'); +}) +``` +### pushNamedRoute + +pushNamedRoute(options: NamedRouterOptions, mode: RouterMode): Promise<void> + +Navigates to a page using the named route. This API uses a promise to return the result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------- | +| options | [NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Page routing parameters. | +| mode | [RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| + +**Return value** + +| Type | Description | +| ------------------- | --------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found. | +| 100003 | if the pages are pushed too much. | +| 100004 | if the named route is not exist. | + +**Example** + +```ts +let router = uiContext.getRouter(); +router.pushNamedRoute({ + name: 'myPage', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + } + } +}, router.RouterMode.Standard) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); + }) +``` + +### pushNamedRoute + +pushNamedRoute(options: NamedRouterOptions, mode: RouterMode, callback: AsyncCallback<void>): void + +Navigates to a page using the named route. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------- | +| options | [NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Page routing parameters. | +| mode | [RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found. | +| 100003 | if the pages are pushed too much. | +| 100004 | if the named route is not exist. | + +**Example** + +```ts +let router = uiContext.getRouter(); +router.pushNamedRoute({ + name: 'myPage', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + } + } +}, router.RouterMode.Standard, (err) => { + if (err) { + console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('pushNamedRoute success'); +}) +``` + +### replaceNamedRoute + +replaceNamedRoute(options: NamedRouterOptions): Promise<void> + +Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | ------------------ | +| options | [NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Description of the new page.| + +**Return value** + +| Type | Description | +| ------------------- | --------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found. | +| 100004 | if the named route is not exist. | + +**Example** + +```ts +let router = uiContext.getRouter(); +router.replaceNamedRoute({ + name: 'myPage', + params: { + data1: 'message' + } +}) + .then(() => { + // success + }) + .catch(err => { + console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); + }) +``` + +### replaceNamedRoute + +replaceNamedRoute(options: NamedRouterOptions, callback: AsyncCallback<void>): void + +Replaces the current page with another one using the named route and destroys the current page. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | ------------------ | +| options | [NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Description of the new page.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found. | +| 100004 | if the named route is not exist. | + +**Example** + +```ts +let router = uiContext.getRouter(); +router.replaceNamedRoute({ + name: 'myPage', + params: { + data1: 'message' + } +}, (err) => { + if (err) { + console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('replaceNamedRoute success'); +}) +``` + +### replaceNamedRoute + +replaceNamedRoute(options: NamedRouterOptions, mode: RouterMode): Promise<void> + +Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------- | +| options | [NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Description of the new page. | +| mode | [RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| + + +**Return value** + +| Type | Description | +| ------------------- | --------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if can not get the delegate. | +| 100004 | if the named route is not exist. | + +**Example** + +```ts +let router = uiContext.getRouter(); +router.replaceNamedRoute({ + name: 'myPage', + params: { + data1: 'message' + } +}, router.RouterMode.Standard) + .then(() => { + // success + }) + .catch(err => { + console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); + }) +``` + +### replaceNamedRoute + +replaceNamedRoute(options: NamedRouterOptions, mode: RouterMode, callback: AsyncCallback<void>): void + +Replaces the current page with another one using the named route and destroys the current page. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------- | +| options | [NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Description of the new page. | +| mode | [RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found. | +| 100004 | if the named route is not exist. | + +**Example** + +```ts +let router = uiContext.getRouter(); +router.replaceNamedRoute({ + name: 'myPage', + params: { + data1: 'message' + } +}, router.RouterMode.Standard, (err) => { + if (err) { + console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('replaceNamedRoute success'); +}); +``` + +### back + +back(options?: RouterOptions ): void + +Returns to the previous page or a specified page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| options | [RouterOptions](js-apis-router.md#routeroptions) | No | Description of the page. The **url** parameter indicates the URL of the page to return to. If the specified page does not exist in the page stack, the application does not respond. If no URL is set, the application returns to the previous page, and the page is not rebuilt. The page in the page stack is not reclaimed. It will be reclaimed after being popped up.| + +**Example** + +```ts +let router = uiContext.getRouter(); +router.back({url:'pages/detail'}); +``` + +### clear + +clear(): void + +Clears all historical pages in the stack and retains only the current page at the top of the stack. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** + +```ts +let router = uiContext.getRouter(); +router.clear(); +``` + +### getLength + +getLength(): string + +Obtains the number of pages in the current stack. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| string | Number of pages in the stack. The maximum value is **32**.| + +**Example** + +```ts +let router = uiContext.getRouter(); +let size = router.getLength(); +console.log('pages stack size = ' + size); +``` + +### getState + +getState(): RouterState + +Obtains state information about the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| --------------------------- | ------- | +| [RouterState](js-apis-router.md#routerstate) | Page routing state.| + +**Example** + +```ts +let router = uiContext.getRouter(); +let page = router.getState(); +console.log('current index = ' + page.index); +console.log('current name = ' + page.name); +console.log('current path = ' + page.path); +``` + +### showAlertBeforeBackPage + +showAlertBeforeBackPage(options: EnableAlertOptions): void + +Enables the display of a confirm dialog box before returning to the previous page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | --------- | +| options | [EnableAlertOptions](js-apis-router.md#enablealertoptions) | Yes | Description of the dialog box.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found. | + +**Example** + +```ts +let router = uiContext.getRouter(); +try { + router.showAlertBeforeBackPage({ + message: 'Message Info' + }); +} catch(error) { + console.error(`showAlertBeforeBackPage failed, code is ${error.code}, message is ${error.message}`); +} +``` + +### hideAlertBeforeBackPage + +hideAlertBeforeBackPage(): void + +Disables the display of a confirm dialog box before returning to the previous page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** + +```ts +let router = uiContext.getRouter(); +router.hideAlertBeforeBackPage(); +``` + +### getParams + +getParams(): Object + +Obtains the parameters passed from the page that initiates redirection to the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| ------ | ---------------------------------- | +| object | Parameters passed from the page that initiates redirection to the current page.| + +**Example** + +```ts +let router = uiContext.getRouter(); +router.getParams(); +``` + +## PromptAction + +In the following API examples, you must first use [getPromptAction()](#getpromptaction) in **UIContext** to obtain a **PromptAction** instance, and then call the APIs using the obtained instance. + +### showToast + +showToast(options: ShowToastOptions): void + +Shows a toast. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------------- | ---- | ------- | +| options | [ShowToastOptions](js-apis-promptAction.md#showtoastoptions) | Yes | Toast options.| + +**Error codes** + +For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found. | + +**Example** + +```ts +let promptAction = uiContext.getPromptAction(); +try { + promptAction.showToast({ + message: 'Message Info', + duration: 2000 + }); +} catch (error) { + console.error(`showToast args error code is ${error.code}, message is ${error.message}`); +}; +``` + +### showDialog + +showDialog(options: ShowDialogOptions, callback: AsyncCallback<ShowDialogSuccessResponse<): void + +Shows a dialog box. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------ | +| options | [ShowDialogOptions](js-apis-promptAction.md#showdialogoptions) | Yes | Dialog box options.| +| callback | AsyncCallback<[ShowDialogSuccessResponse](js-apis-promptAction.md#showdialogsuccessresponse)> | Yes | Callback used to return the dialog box response result. | + +**Error codes** + +For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found. | + +**Example** + +```ts +let promptAction = uiContext.getPromptAction(); +try { + promptAction.showDialog({ + title: 'showDialog Title Info', + message: 'Message Info', + buttons: [ + { + text: 'button1', + color: '#000000' + }, + { + text: 'button2', + color: '#000000' + } + ] + }, (err, data) => { + if (err) { + console.info('showDialog err: ' + err); + return; + } + console.info('showDialog success callback, click button: ' + data.index); + }); +} catch (error) { + console.error(`showDialog args error code is ${error.code}, message is ${error.message}`); +}; +``` + +### showDialog + +showDialog(options: ShowDialogOptions): Promise<ShowDialogSuccessResponse> + +Shows a dialog box. This API uses a promise to return the result synchronously. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | --------------------------------------- | ---- | ------ | +| options | [ShowDialogOptions](js-apis-promptAction.md#showdialogoptions) | Yes | Dialog box options.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | -------- | +| Promise<[ShowDialogSuccessResponse](js-apis-promptAction.md#showdialogsuccessresponse)> | Promise used to return the dialog box response result.| + +**Error codes** + +For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found. | + +**Example** + +```ts +let promptAction = uiContext.getPromptAction(); +try { + promptAction.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); + }) +} catch (error) { + console.error(`showDialog args error code is ${error.code}, message is ${error.message}`); +}; +``` + +### showActionMenu + +showActionMenu(options: ActionMenuOptions, callback: AsyncCallback<ActionMenuSuccessResponse>):void + +Shows an action menu. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| options | [ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | Yes | Action menu options. | +| callback | AsyncCallback<[ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)> | Yes | Callback used to return the action menu response result.| + +**Error codes** + +For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found. | + +**Example** + +```ts +let promptAction = uiContext.getPromptAction(); +try { + promptAction.showActionMenu({ + title: 'Title Info', + buttons: [ + { + text: 'item1', + color: '#666666' + }, + { + text: 'item2', + color: '#000000' + }, + ] + }, (err, data) => { + if (err) { + console.info('showActionMenu err: ' + err); + return; + } + console.info('showActionMenu success callback, click button: ' + data.index); + }) +} catch (error) { + console.error(`showActionMenu args error code is ${error.code}, message is ${error.message}`); +}; +``` + +### showActionMenu + +showActionMenu(options: ActionMenuOptions): Promise<ActionMenuSuccessResponse> + +Shows an action menu. This API uses a promise to return the result synchronously. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | --------------------------------------- | ---- | ------- | +| options | [ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | Yes | Action menu options.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise<[ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)> | Promise used to return the action menu response result.| + +**Error codes** + +For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found. | + +**Example** + +```ts +let promptAction = uiContext.getPromptAction(); +try { + promptAction.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); + }) +} catch (error) { + console.error(`showActionMenu args error code is ${error.code}, message is ${error.message}`); +}; +``` diff --git a/en/application-dev/reference/apis/js-apis-arraylist.md b/en/application-dev/reference/apis/js-apis-arraylist.md index 0cd79c938c8bb74f7fb919c7e6dc2e1afaa97cd8..f9012db2add74f9810baa032b103a4eff48dbd04 100644 --- a/en/application-dev/reference/apis/js-apis-arraylist.md +++ b/en/application-dev/reference/apis/js-apis-arraylist.md @@ -379,15 +379,15 @@ Replaces all elements in this container with new elements, and returns the new o | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callbackFn | function | Yes| Callback invoked for the replacement.| -| thisArg | Object | No| Value to use when the callback is invoked.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked. The default value is this instance.| -callbackfn +callbackFn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | T | Yes| Value of the element that is currently traversed.| -| index | number | No| Position index of the element that is currently traversed.| -| arrlist | ArrayList<T> | No| Instance that invokes the **replaceAllElements** method.| +| index | number | No| Position index of the element that is currently traversed. The default value is **0**.| +| arrlist | ArrayList<T> | No| Instance that calls the **replaceAllElements** API. The default value is this instance.| **Error codes** @@ -425,15 +425,15 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callbackFn | function | Yes| Callback invoked for the replacement.| -| thisArg | Object | No| Value to use when the callback is invoked.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked. The default value is this instance.| -callbackfn +callbackFn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | T | Yes| Value of the element that is currently traversed.| -| index | number | No| Position index of the element that is currently traversed.| -| arrlist | ArrayList<T> | No| Instance that invokes the **forEach** method.| +| index | number | No| Position index of the element that is currently traversed. The default value is 0.| +| arrlist | ArrayList<T> | No| Instance that calls the **forEach** API. The default value is this instance.| **Error codes** @@ -468,7 +468,7 @@ Sorts elements in this container. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| comparator | function | No| Callback invoked for sorting.| +| comparator | function | No| Callback invoked for sorting. The default value is the callback function for sorting elements in ascending order.| comparator diff --git a/en/application-dev/reference/apis/js-apis-avsession.md b/en/application-dev/reference/apis/js-apis-avsession.md index d70b0712fa9df71eb1ca31a3a03970a714c03f91..b2ad9fb70720b8d56ee05c19a59c12183a3cf199 100644 --- a/en/application-dev/reference/apis/js-apis-avsession.md +++ b/en/application-dev/reference/apis/js-apis-avsession.md @@ -307,9 +307,9 @@ Creates a session controller based on the session ID. Multiple session controlle **Return value** -| Type | Description | -| ----------------------------------------------------- | ------------------------------------------------------------ | -| Promise<[AVSessionController](#avsessioncontroller10)\> | Promise used to return the session controller created, which can be used to obtain the session ID,
send commands and events to sessions, and obtain metadata and playback state information.| +| Type | Description | +| ------------------------------------------------------- | ------------------------------------------------------------ | +| Promise<[AVSessionController](#avsessioncontroller10)\> | Promise used to return the session controller created, which can be used to obtain the session ID, send commands and events to sessions, and obtain metadata and playback state information. | **Error codes** @@ -1119,6 +1119,10 @@ For details about the error codes, see [AVSession Management Error Codes](../err **Example** ```js +import image from '@ohos.multimedia.image'; +import resourceManager from '@ohos.resourceManager'; + +let value : Uint8Array = await resourceManager.getRawFile('IMAGE_URI'); let imageSource : imageImageSource = image.createImageSource(value.buffer); let imagePixel : image.PixelMap = await imageSource.createPixelMap({desiredSize:{width: 150, height: 150}}); let queueItemDescription_1 = { @@ -1139,7 +1143,7 @@ let queueItemDescription_2 = { title: 'music_name', subtitle: 'music_sub_name', description: 'music_description', - icon: PIXELMAP_OBJECT, + icon: imagePixel, iconUri: 'http://www.xxx.com', extras: {'extras':'any'} }; @@ -1182,6 +1186,10 @@ For details about the error codes, see [AVSession Management Error Codes](../err **Example** ```js +import image from '@ohos.multimedia.image'; +import resourceManager from '@ohos.resourceManager'; + +let value : Uint8Array = await resourceManager.getRawFile('IMAGE_URI'); let imageSource : imageImageSource = image.createImageSource(value.buffer); let imagePixel : image.PixelMap = await imageSource.createPixelMap({desiredSize:{width: 150, height: 150}}); let queueItemDescription_1 = { @@ -1202,7 +1210,7 @@ let queueItemDescription_2 = { title: 'music_name', subtitle: 'music_sub_name', description: 'music_description', - icon: PIXELMAP_OBJECT, + icon: imagePixel, iconUri: 'http://www.icon.uri.com', extras: {'extras':'any'} }; @@ -2252,7 +2260,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ------------------------------ | | 6600101 | Session service exception. | -| 6600103 | The session controller does not exist. | +| 6600102 | The session does not exist. | **Example** @@ -2531,6 +2539,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------- | | 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -2795,6 +2804,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | -------- | ---------------------------------------- | | 6600101 | Session service exception. | | 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** @@ -2830,6 +2840,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | -------- | ---------------------------------------- | | 6600101 | Session service exception. | | 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** @@ -3002,6 +3013,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | 6600101 | Session service exception. | | 6600102 | The session does not exist. | | 6600103 | The session controller does not exist. | +| 6600105 | Invalid session command. | +| 6600107 | Too many commands or events. | **Example** ```js @@ -3033,6 +3046,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | 6600101 | Session service exception. | | 6600102 | The session does not exist. | | 6600103 | The session controller does not exist. | +| 6600105 | Invalid session command. | +| 6600107 | Too many commands or events. | **Example** ```js @@ -4025,6 +4040,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------- | | 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -4054,6 +4070,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------- | | 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -4083,6 +4100,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------- | | 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -4112,6 +4130,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------- | | 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -4141,6 +4160,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------- | | 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -4201,6 +4221,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------- | | 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -4230,6 +4251,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------- | | 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -4259,6 +4281,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message | | -------- | ---------------- | | 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -4288,6 +4311,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID | Error Message | | -------- | ---------------- | | 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-buffer.md b/en/application-dev/reference/apis/js-apis-buffer.md index 737c9f1dbf05e30e2f84e185b89e804642b0c39f..f50bdfe83cca98808fbb79237bd21194ec30b7a4 100644 --- a/en/application-dev/reference/apis/js-apis-buffer.md +++ b/en/application-dev/reference/apis/js-apis-buffer.md @@ -204,7 +204,7 @@ Concatenates an array of **Buffer** instances of the specified length into a new | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | list | Buffer[] \| Uint8Array[] | Yes| Array of instances to concatenate.| -| totalLength | number | No| Total length of bytes to be copied.| +| totalLength | number | No| Total length of bytes to be copied. The default value is **0**.| **Return value** @@ -1915,7 +1915,7 @@ Converts the data at the specified position in this **Buffer** instance into a s | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| encoding | string | No| Encoding format of the string. The default value is **utf-8**.| +| encoding | string | No| Encoding format (valid only when **value** is a string). The default value is **utf-8**.| | start | number | No| Offset to the start position of the data to convert. The default value is **0**.| | end | number | No| Offset to the end position of the data to convert. The default value is the length of this **Buffer** instance.| diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-bundleInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-bundleInfo.md index 5ac1f36f06bc8cab683227b26bcacab465323408..229d7cd7b76df72c23f78955f3c49c702ee3c62f 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-bundleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-bundleInfo.md @@ -36,6 +36,7 @@ Provides the detailed information of the permissions to request from the system. | Name | Type | Readable| Writable| Description | | --------------------- | ----------------------- | ---- | ---- | ---------------------| | name | string | Yes | Yes | Name of the permission to request. | +| moduleName10+ | string | Yes | Yes | Name of the module that requests the permission. | | reason | string | Yes | Yes | Reason for requesting the permission. | | reasonId | number | Yes | Yes | ID of the reason for requesting the permission.| | usedScene | [UsedScene](#usedscene) | Yes | Yes | Application scenario and timing for using the permission.| diff --git a/en/application-dev/reference/apis/js-apis-camera.md b/en/application-dev/reference/apis/js-apis-camera.md index c86b21c5f8c541e29b38eeb38cb25edfc13bfc14..56a63d8d5620ba09928caffd6de17861f500b2cb 100644 --- a/en/application-dev/reference/apis/js-apis-camera.md +++ b/en/application-dev/reference/apis/js-apis-camera.md @@ -576,7 +576,7 @@ Listens for camera mute status changes. This API uses an asynchronous callback t **Example** ```js -cameraManager.on('cameraMute', (curMuetd) => { +cameraManager.on('cameraMute', (err, curMuetd) => { let isMuted = curMuetd; }) ``` @@ -1770,7 +1770,7 @@ Before the setting, you are advised to use **[getExposureBiasRange](#getexposure | Name | Type | Mandatory| Description | | -------- | -------------------------------| ---- | ------------------- | -| exposureBias | number | Yes | EV. The supported EV range can be obtained by calling **getExposureBiasRange**. If the value passed is not within the supported range, the nearest critical point is used. There is a step for EV. For example, if the step is 0.5 and this parameter is set to 1.2, the EV that takes effect is 1.0. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned. | +| exposureBias | number | Yes | EV. The supported EV range can be obtained by calling **getExposureBiasRange**. If the value passed is not within the supported range, the nearest critical point is used. There is a step for EV. For example, if the step is 0.5 and this parameter is set to 1.2, the EV that takes effect is 1.0. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| **Error codes** @@ -1804,7 +1804,7 @@ Obtains the exposure value in use. | Type | Description | | ---------- | ----------------------------- | -| number | Exposure value obtained. There is a step for EV. For example, if the step is 0.5 and this parameter is set to 1.2, the EV that takes effect is 1.0. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned. | +| number | Exposure value obtained. There is a step for EV. For example, if the step is 0.5 and this parameter is set to 1.2, the EV that takes effect is 1.0. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| **Error codes** @@ -2281,7 +2281,7 @@ Listens for focus state changes. This API uses an asynchronous callback to retur **Example** ```js -captureSession.on('focusStateChange', (focusState) => { +captureSession.on('focusStateChange', (err, focusState) => { console.log(`Focus state : ${focusState}`); }) ``` @@ -2883,7 +2883,7 @@ Listens for shooting start events. This API uses an asynchronous callback to ret **Example** ```js -photoOutput.on('captureStart', (captureId) => { +photoOutput.on('captureStart', (err, captureId) => { console.log(`photo capture stated, captureId : ${captureId}`); }) ``` @@ -2906,7 +2906,7 @@ Listens for frame shutter events. This API uses an asynchronous callback to retu **Example** ```js -photoOutput.on('frameShutter', (frameShutterInfo) => { +photoOutput.on('frameShutter', (err, frameShutterInfo) => { console.log(`photo capture end, captureId : ${frameShutterInfo.captureId}`); console.log(`Timestamp for frame : ${frameShutterInfo.timestamp}`); }) @@ -2930,7 +2930,7 @@ Listens for shooting end events. This API uses an asynchronous callback to retur **Example** ```js -photoOutput.on('captureEnd', (captureEndInfo) => { +photoOutput.on('captureEnd', (err, captureEndInfo) => { console.log(`photo capture end, captureId : ${captureEndInfo.captureId}`); console.log(`frameCount : ${captureEndInfo.frameCount}`); }) @@ -3378,7 +3378,7 @@ Listens for metadata objects. This API uses an asynchronous callback to return t **Example** ```js -metadataOutput.on('metadataObjectsAvailable', (metadataObjectArr) => { +metadataOutput.on('metadataObjectsAvailable', (err, metadataObjectArr) => { console.log(`metadata output metadataObjectsAvailable`); }) ``` diff --git a/en/application-dev/reference/apis/js-apis-cryptoFramework.md b/en/application-dev/reference/apis/js-apis-cryptoFramework.md index afb1bd3f8d80a74415c359af492492286364008c..422104663d3902e3d02488ca879e4089394a7f83 100644 --- a/en/application-dev/reference/apis/js-apis-cryptoFramework.md +++ b/en/application-dev/reference/apis/js-apis-cryptoFramework.md @@ -8,2250 +8,2346 @@ The **cryptoFramework** module shields underlying hardware and algorithm librari ## Modules to Import -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" ``` ## Result -Enumerates the error codes. + Enumerates the operation results. -**System capability**: SystemCapability.Security.CryptoFramework + **System capability**: SystemCapability.Security.CryptoFramework | Name | Value | Description | | ------------------------------------- | -------- | ---------------------------- | -| INVALID_PARAMS | 401 | Invalid parameters. | +| INVALID_PARAMS | 401 | Invalid parameters. | | NOT_SUPPORT | 801 | Unsupported operation. | | ERR_OUT_OF_MEMORY | 17620001 | Memory error. | | ERR_RUNTIME_ERROR | 17620002 | Runtime error. | -| ERR_CRYPTO_OPERATION | 17630001 | Cryptographic operation error. | +| ERR_CRYPTO_OPERATION | 17630001 | Failed to invoke the third-party cryptographic API. | ## DataBlob Defines a binary data array. -**System capability**: SystemCapability.Security.CryptoFramework + **System capability**: SystemCapability.Security.CryptoFramework | Name| Type | Readable| Writable| Description | | ---- | ---------- | ---- | ---- | ------ | | data | Uint8Array | Yes | Yes | Binary data array. | +## ParamsSpec -## cryptoFramework.createMac - -createMac(algName : string) : Mac +Defines the parameters used for encryption and decryption.
For the symmetric encryption and decryption modes that require parameters such as the initialization vector (IV), you need to construct a child class object and pass it to [init()](#init-2). If the IV is not required (for example, the ECB mode), pass in **null** in [init()](#init-2). -Creates a **Mac** instance for message authentication code (MAC) operations. +**System capability**: SystemCapability.Security.CryptoFramework -For details about the supported specifications, see [HMAC Algorithm Specifications](../../security/cryptoFramework-overview.md#hmac-algorithm-specifications). +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| algName | string | Yes | Yes | Symmetric encryption and decryption parameters. Options:
- **IvParamsSpec**: applicable to the CBC, CTR, OFB, and CFB modes.
- **GcmParamsSpec**: applicable to the GCM mode.
- **CcmParamsSpec**: applicable to the CCM mode.| -**System capability**: SystemCapability.Security.CryptoFramework +> **NOTE** +> +> The **params** parameter in [init()](#init-2) is of the **ParamsSpec** type (parent class). However, a specific child class object (such as **IvParamsSpec**) needs to be passed in. When constructing the child class object, you need to set **algName** for the parent class **ParamsSpec** to specify the child class object in **init()**. -**Parameters** +## IvParamsSpec -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------------------------------------------------------ | -| algName | string | Yes | Digest algorithm. For details about the supported algorithms, see [HMAC Algorithm Specifications](../../security/cryptoFramework-overview.md#hmac-algorithm-specifications).| +Defines the child class of [ParamsSpec](#paramsspec). It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption.
**IvParamsSpec** applies to the encryption and decryption modes such as CBC, CTR, OFB, and CFB, which use only the IV. -**Return value** +**System capability**: SystemCapability.Security.CryptoFramework -| Type| Description | -| ---- | --------------------------------------- | -| Mac | [Mac](#mac) instance created.| +| Name| Type | Readable| Writable| Description | +| ---- | --------------------- | ---- | ---- | ------------------------------------------------------------ | +| iv | [DataBlob](#datablob) | Yes | Yes | IV for encryption and decryption. Options:
- AES CBC, CTR, OFB, or CFB mode: 16-byte IV
- 3DES CBC, OFB, or CFB mode: 8-byte IV| -**Error codes** +> **NOTE** +> +> Before passing [init()](#init-2), specify **algName** for its parent class [ParamsSpec](#paramsspec). -| ID| Error Message | -| -------- | ------------------ | -| 17620001 | memory error. | +## GcmParamsSpec -**Example** +Defines the child class of [ParamsSpec](#paramsspec) for the GCM mode. It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption.
**GcmParamsSpec** applies to the GCM mode. -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +**System capability**: SystemCapability.Security.CryptoFramework -var mac; -try { - // Set algName based on the algorithm supported. - mac = cryptoFramework.createMac("SHA256"); -} catch (error) { - console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); -} -``` +| Name | Type | Readable| Writable| Description | +| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | +| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 12 bytes. | +| aad | [DataBlob](#datablob) | Yes | Yes | Additional authentication data (AAD), which is of 8 bytes. | +| authTag | [DataBlob](#datablob) | Yes | Yes | Authentication tag, which is of 16 bytes.
When the GCM mode is used for encryption, the last 16 bytes of the [DataBlob](#datablob) output by [doFinal()](#dofinal-2) are used as the **authTag** in [GcmParamsSpec](#gcmparamsspec) of [init()](#init-2). | -## Mac +> **NOTE** +> +> Before passing [init()](#init-2), specify **algName** for its parent class [ParamsSpec](#paramsspec). -Provides APIs for MAC operations. Before using any API of the **Mac** class, you must create a **Mac** instance by using [createMac](#cryptoframeworkcreatemac). +## CcmParamsSpec -### Attributes +Defines the child class of [ParamsSpec](#paramsspec) for the CCM mode. It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption.
**CcmParamsSpec** applies to the CCM mode. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | -------------------- | -| algName | string | Yes | No | Digest algorithm to use.| +| Name | Type | Readable| Writable| Description | +| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | +| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 7 bytes. | +| aad | [DataBlob](#datablob) | Yes | Yes | Additional authentication data (AAD), which is of 8 bytes. | +| authTag | [DataBlob](#datablob) | Yes | Yes | Authentication tag, which is of 12 bytes.
When the CCM mode is used for encryption, the last 12 bytes of the [DataBlob](#datablob) output by [doFinal()](#dofinal-2) are used as the **authTag** in [CcmParamsSpec](#ccmparamsspec) of [init()](#init-2).| -### init +> **NOTE** +> +> Before passing [init()](#init-2), specify **algName** for its parent class [ParamsSpec](#paramsspec). -init(key : SymKey, callback : AsyncCallback\) : void; +## CryptoMode -Initializes the MAC computation using a symmetric key. This API uses an asynchronous callback to return the result. +Enumerates the cryptographic operations. **System capability**: SystemCapability.Security.CryptoFramework -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------ | -| key | [SymKey](#symkey) | Yes | Shared symmetric key.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | +| Name | Value | Description | +| ------------ | ---- | ------------------ | +| ENCRYPT_MODE | 0 | Encryption.| +| DECRYPT_MODE | 1 | Decryption.| -**Error codes** +## AsyKeySpecItem10+ -| ID| Error Message | -| -------- | ---------------------- | -| 17630001 | crypto operation error. | +Enumerates the key parameters. -**Example** +**System capability**: SystemCapability.Security.CryptoFramework -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +| Name | Value | Description | +| ------------ | ---- | ---------------- | +| DSA_P_BN | 101 | Prime modulus **p** in the DSA algorithm.| +| DSA_Q_BN | 102 | Parameter **q** (prime factor of p – 1) in the DSA algorithm.| +| DSA_G_BN | 103 | Parameter **g** in the DSA algorithm.| +| DSA_SK_BN | 104 | Private key **sk** in the DSA algorithm.| +| DSA_PK_BN | 105 | Public key **pk** in the DSA algorithm.| +| ECC_FP_P_BN | 201 | Prime number **p** in the **Fp** fields of the elliptic curve in the DSA algorithm.| +| ECC_A_BN | 202 | First coefficient **a** of the elliptic curve in the DSA algorithm.| +| ECC_B_BN | 203 | Second coefficient **b** of the elliptic curve in the DSA algorithm.| +| ECC_G_X_BN | 204 | X coordinate of the base point **g** in the ECC algorithm.| +| ECC_G_Y_BN | 205 | Y coordinate of the base point **g** in the ECC algorithm.| +| ECC_N_BN | 206 | Order **n** of the base point **g** in the ECC algorithm.| +| ECC_H_NUM | 207 | Cofactor **h** in the ECC algorithm.| +| ECC_SK_BN | 208 | Private key **sk** in the ECC algorithm.| +| ECC_PK_X_BN | 209 | X coordinate of the public key **pk** (a point on the elliptic curve) in the ECC algorithm.| +| ECC_PK_Y_BN | 210 | Y coordinate of the public key **pk** (a point on the elliptic curve) in the ECC algorithm.| +| ECC_FIELD_TYPE_STR | 211 | Elliptic curve field type in the ECC algorithm. Currently, only the **Fp** field is supported.| +| ECC_FIELD_SIZE_NUM | 212 | Size of the field in the ECC algorithm, in bits.
**NOTE**: For the **Fp** field, the field size is the length of the prime **p**, in bits. | +| ECC_CURVE_NAME_STR | 213 | SECG curve name in the ECC algorithm.| +| RSA_N_BN | 301 | Modulus **n** in the RSA algorithm.| +| RSA_SK_BN | 302 | Private key **sk** (private key exponent **d**) in the RSA algorithm.| +| RSA_PK_BN | 303 | Public key **pk** (public key exponent **e**) in the RSA algorithm.| + +## AsyKeySpecType10+ + +Enumerates the key parameter types. -var mac; -try { - mac = cryptoFramework.createMac("SHA256"); -} catch (error) { - console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); -} -var KeyBlob; -var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); -symKeyGenerator.convertKey(KeyBlob, (err, symKey) => { - if (err) { - console.error("[Callback] err: " + err.code); - } - mac.init(symKey, (err1, ) => { - if (err1) { - console.error("[Callback] err: " + err1.code); - } - }); -}); -``` +**System capability**: SystemCapability.Security.CryptoFramework -### init +| Name | Value | Description | +| ------------ | ---- | ---------------- | +| COMMON_PARAMS_SPEC | 0 | Common parameters contained in the public and private keys. You can use [generateKeyPair()](#generatekeypair-2) to randomly generate a key pair based on the parameters of this type.| +| PRIVATE_KEY_SPEC | 1 | Parameter contained in the private key. You can use [generatePriKey()](#generateprikey) to generate a private key based on the parameters of this type.| +| PUBLIC_KEY_SPEC | 2 | Parameter contained in the public key. You can use [generatePubKey()](#generatepubkey) to generate a public key based on the parameters of this type.| +| KEY_PAIR_SPEC | 3 | All parameters contained in the public and private keys. You can use [generateKeyPair](#generatekeypair-2) to generate a key pair based on the parameters of this type.| -init(key : SymKey) : Promise\; +## CipherSpecItem10+ -Initializes the MAC computation using a symmetric key. This API uses a promise to return the result. +Enumerates the cipher parameters. You can use [setCipherSpec](#setcipherspec10) to set cipher parameters, and use [getCipherSpec](#getcipherspec10) to obtain cipher parameters.
Currently, only the RSA is supported. For details, see [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). **System capability**: SystemCapability.Security.CryptoFramework -**Parameters** +| Name | Value | Description | +| ------------ | ---- | ---------------- | +| OAEP_MD_NAME_STR | 100 | Name of the message digest algorithm when the PKCS1_OAEP padding mode is used in the RSA.| +| OAEP_MGF_NAME_STR | 101 | Mask generation algorithm when the PKCS1_OAEP padding mode is used in the RSA. Currently, only MGF1 is supported.| +| OAEP_MGF1_MD_STR | 102 | Message digest algorithm for the MGF1 mask generation when the PKCS1_OAEP padding mode is used in the RSA.| +| OAEP_MGF1_PSRC_UINT8ARR | 103 | **pSource** byte stream when the PKCS1_OAEP padding mode is used in the RSA.| -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------ | -| key | [SymKey](#symkey) | Yes | Shared symmetric key.| +## SignSpecItem10+ -**Return value** +Enumerates the parameters for signing and signature verification. You can use [setSignSpec](#setsignspec10) and [setVerifySpec](#setverifyspec10) to set these parameters, and use [getSignSpec](#getsignspec10) and [getVerifySpec](#getverifyspec10) to obtain the parameters.
Currently, only the RSA is supported. For details, see [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). -| Type | Description | -| -------------- | ----------- | -| Promise\ | Promise used to return the result.| +**System capability**: SystemCapability.Security.CryptoFramework -**Error codes** +| Name | Value | Description | +| ------------ | ---- | ---------------- | +| PSS_MD_NAME_STR | 100 | Name of the message digest algorithm when the PSS padding mode is used in the RSA.| +| PSS_MGF_NAME_STR | 101 | Mask generation algorithm when the PSS padding mode is used in the RSA. Currently, only MGF1 is supported.| +| PSS_MGF1_MD_STR | 102 | Message digest parameters for the MGF1 mask generation when the PSS padding mode is used in the RSA.| +| PSS_SALT_LEN_NUM | 103 | Length of the salt in bytes when the PSS padding mode is used in the RSA.| +| PSS_TRAILER_FIELD_NUM | 104 | Integer used for encoding when the PSS padding mode is used in the RSA. The value is **1**.| -| ID| Error Message | -| -------- | ---------------------- | -| 17630001 | crypto operation error. | +## AsyKeySpec10+ -**Example** +Defines the asymmetric key parameters for creating a key generator. You need to construct a child class object and pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. All the parameters of the bigint type in the child class object must be integers in big-endian format. -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +**System capability**: SystemCapability.Security.CryptoFramework -var mac; -try { - mac = cryptoFramework.createMac("SHA256"); -} catch (error) { - console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); -} -console.error("Mac algName is: " + mac.algName); +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| algName | string | Yes | Yes | Algorithm of the asymmetric key pair, for example, **RSA**, **DSA**, or **ECC**.| +| specType | [AsyKeySpecType](#asykeyspectype10) | Yes | Yes| Key parameter type, which is used to distinguish public and private key parameters.| -var KeyBlob; -var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); -var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); -promiseConvertKey.then(symKey => { - var promiseMacInit = mac.init(symKey); - return promiseMacInit; -}).catch(error => { - console.error("[Promise]: error: " + error.message); -}); +## DSACommonParamsSpec10+ -``` +Defines the common parameters contained in the public and private keys in the DSA algorithm. It is a child class of [AsyKeySpec](#asykeyspec10) and can be used to randomly generate public or private keys.
When key parameters are used to generate a key, you can pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. -### update +**System capability**: SystemCapability.Security.CryptoFramework -update(input : DataBlob, callback : AsyncCallback\) : void; +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| p | bigint | Yes | Yes | Prime modulus **p** in the DSA algorithm.| +| q | bigint | Yes | Yes | Parameter **q** (prime factor of **p** – 1) in the DSA algorithm.| +| g | bigint | Yes | Yes | Parameter **g** in the DSA algorithm.| -Updates the MAC computation data. This API uses an asynchronous callback to return the result. +## DSAPubKeySpec10+ -> **NOTE**
-> For details about the sample code for calling **update()** multiple times, see [Generating a MAC](../../security/cryptoFramework-guidelines.md#generating-a-mac). +Defines the parameters contained in the public key in the DSA algorithm. It is a child class of [AsyKeySpec](#asykeyspec10).
When key parameters are used to generate a key, you can pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. **System capability**: SystemCapability.Security.CryptoFramework -**Parameters** +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| params | [DSACommonParamsSpec](#dsacommonparamsspec10) | Yes | Yes | Common parameters contained in both public and private keys in the DSA algorithm.| +| pk | bigint | Yes | Yes | Public key of the DSA algorithm.| -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------- | -| input | [DataBlob](#datablob)| Yes | Data to pass in.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | +## DSAKeyPairSpec10+ -**Error codes** +Defines full parameters contained in the public and private keys in the DSA algorithm. It is a child class of [AsyKeySpec](#asykeyspec10).
When key parameters are used to generate a key, you can pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. -| ID| Error Message | -| -------- | ---------------------- | -| 17630001 | crypto operation error. | +**System capability**: SystemCapability.Security.CryptoFramework -**Example** +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| params | [DSACommonParamsSpec](#dsacommonparamsspec10) | Yes | Yes | Common parameters contained in both public and private keys in the DSA algorithm.| +| sk | bigint | Yes | Yes | Private key **sk** in the DSA algorithm.| +| pk | bigint | Yes | Yes | Public key **pk** in the DSA algorithm.| -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +## ECField10+ -var KeyBlob; -var mac; -try { - mac = cryptoFramework.createMac("SHA256"); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); -} -var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); -symKeyGenerator.convertKey(KeyBlob, (err, symKey) => { - if (err) { - console.error("[Callback] err: " + err.code); - } - mac.init(symKey, (err1, ) => { - if (err1) { - console.error("[Callback] err: " + err1.code); - } - let blob; - mac.update(blob, (err2, data) => { - if (err2) { - console.error("[Callback] err: " + err2.code); - } - }); - }); -}); -``` +Defines the elliptic curve field. Currently, only the **Fp** field is supported. -### update +**System capability**: SystemCapability.Security.CryptoFramework -update(input : DataBlob) : Promise\; +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| fieldType | string | Yes | Yes | Type of the elliptic curve field. Currently, only **Fp** is supported.| -Updates the MAC computation data. This API uses a promise to return the result. +## ECFieldFp10+ -> **NOTE**
-> For details about the sample code for calling **update()** multiple times, see [Generating a MAC](../../security/cryptoFramework-guidelines.md#generating-a-mac). +Defines the prime field of the elliptic curve. It is a child class of [ECField](#ecfield10). **System capability**: SystemCapability.Security.CryptoFramework -**Parameters** +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| p | bigint | Yes | Yes | Prime **p**.| -| Name| Type | Mandatory| Description | -| ------ | -------- | ---- | ---------- | -| input | [DataBlob](#datablob) | Yes | Data to pass in.| +## Point10+ -**Return value** +Defines a point on the elliptic curve. -| Type | Description | -| -------------- | ----------- | -| Promise\ | Promise used to return the result.| +**System capability**: SystemCapability.Security.CryptoFramework -**Error codes** +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| x | bigint | Yes | Yes | X coordinate of the point on an elliptic curve.| +| y | bigint | Yes | Yes | Y coordinate of the point on an elliptic curve.| -| ID| Error Message | -| -------- | ---------------------- | -| 17630001 | crypto operation error. | +## ECCCommonParamsSpec10+ -**Example** +Defines the common parameters contained in the public and private keys in the ECC algorithm. It is a child class of [AsyKeySpec](#asykeyspec10) and can be used to randomly generate public or private keys.
When key parameters are used to generate a key, you can pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +**System capability**: SystemCapability.Security.CryptoFramework -var mac; -try { - mac = cryptoFramework.createMac("SHA256"); -} catch (error) { - console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); -} -console.error("Mac algName is: " + mac.algName); +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| field | [ECField](#ecfield10) | Yes | Yes | Field of the elliptic curve. Currently, only the **Fp** field is supported.| +| a | bigint | Yes | Yes | First coefficient **a** of the elliptic curve.| +| b | bigint | Yes | Yes | Second coefficient **b** of the elliptic curve.| +| g | [Point](#point10) | Yes | Yes | Base point g.| +| n | bigint | Yes | Yes | Order **n** of the base point **g**.| +| h | number | Yes | Yes | Cofactor **h**.| -var KeyBlob; -var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); -var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); -promiseConvertKey.then(symKey => { - var promiseMacInit = mac.init(symKey); - return promiseMacInit; -}).then(() => { - let blob; - var promiseMacUpdate = mac.update(blob); - return promiseMacUpdate; -}).catch(error => { - console.error("[Promise]: error: " + error.message); -}); +## ECCPriKeySpec10+ -``` +Defines the parameters contained in the private key in the ECC algorithm. It is a child class of [AsyKeySpec](#asykeyspec10).
When key parameters are used to generate a key, you can pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. -### doFinal +**System capability**: SystemCapability.Security.CryptoFramework -doFinal(callback : AsyncCallback\) : void; +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| params | [ECCCommonParamsSpec](#ecccommonparamsspec10) | Yes | Yes | Common parameters contained in both public and private keys in the ECC algorithm.| +| sk | bigint | Yes | Yes | Private key **sk** in the ECC algorithm.| -Finalizes the MAC computation. This API uses an asynchronous callback to return the result. +## ECCPubKeySpec10+ + +Defines the parameters contained in the public key in the ECC algorithm. It is a child class of [AsyKeySpec](#asykeyspec10).
When key parameters are used to generate a key, you can pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. **System capability**: SystemCapability.Security.CryptoFramework -**Parameters** +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| params | [ECCCommonParamsSpec](#ecccommonparamsspec10) | Yes | Yes | Common parameters contained in both public and private keys in the ECC algorithm.| +| pk | [Point](#point10) | Yes | Yes | Public key **pk** in the ECC algorithm.| -| Name | Type | Mandatory| Description | -| -------- | ------------------------ | ---- | -------- | -| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result.| +## ECCKeyPairSpec10+ -**Error codes** +Defines full parameters contained in the public and private keys in the ECC algorithm. It is a child class of [AsyKeySpec](#asykeyspec10).
When key parameters are used to generate a key, you can pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. -| ID| Error Message | -| -------- | ---------------------- | -| 17620001 | memory error. | -| 17630001 | crypto operation error. | +**System capability**: SystemCapability.Security.CryptoFramework -**Example** +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| params | [ECCCommonParamsSpec](#ecccommonparamsspec10) | Yes | Yes | Common parameters contained in both public and private keys in the ECC algorithm.| +| sk | bigint | Yes | Yes | Private key **sk** in the ECC algorithm.| +| pk | [Point](#point10) | Yes | Yes | Public key **pk** in the ECC algorithm.| -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +## RSACommonParamsSpec10+ -var KeyBlob; -var mac; -try { - mac = cryptoFramework.createMac("SHA256"); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); -} -var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); -symKeyGenerator.convertKey(KeyBlob, (err, symKey) => { - if (err) { - console.error("[Callback] err: " + err.code); - } - mac.init(symKey, (err1, ) => { - if (err1) { - console.error("[Callback] err: " + err1.code); - } - let blob; - mac.update(blob, (err2, ) => { - if (err2) { - console.error("[Callback] err: " + err2.code); - } - mac.doFinal((err3, macOutput) => { - if (err3) { - console.error("[Callback] err: " + err3.code); - } else { - console.error("[Promise]: HMAC result: " + macOutput); - } - }); - }); - }); -}); -``` +Defines the common parameters contained in the public and private keys in the RSA algorithm. It is a child class of [AsyKeySpec](#asykeyspec10) and can be used to randomly generate public or private keys.
When key parameters are used to generate a key, you can pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. -### doFinal +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| n | bigint | Yes | Yes | Modulus **n**.| -doFinal() : Promise\ +## RSAPubKeySpec10+ -Finalizes the MAC computation. This API uses a promise to return the result. +Defines the parameters contained in the public key in the RSA algorithm. It is a child class of [AsyKeySpec](#asykeyspec10).
When key parameters are used to generate a key, you can pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. **System capability**: SystemCapability.Security.CryptoFramework -**Return value** +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| params | [RSACommonParamsSpec](#rsacommonparamsspec10) | Yes | Yes | Common parameters contained in both public and private keys in the RSA algorithm.| +| pk | bigint | Yes | Yes | Public key **pk** in the RSA algorithm.| -| Type | Description | -| ------------------ | ----------- | -| Promise\<[DataBlob](#datablob)> | Promise used to return the result.| +## RSAKeyPairSpec10+ -**Error codes** +Defines full parameters contained in the public and private keys in the RSA algorithm. It is a child class of [AsyKeySpec](#asykeyspec10).
When key parameters are used to generate a key, you can pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. -| ID| Error Message | -| -------- | ---------------------- | -| 17620001 | memory error. | -| 17630001 | crypto operation error. | +**System capability**: SystemCapability.Security.CryptoFramework -**Example** +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| params | [RSACommonParamsSpec](#rsacommonparamsspec10) | Yes | Yes | Common parameters contained in both public and private keys in the RSA algorithm.| +| sk | bigint | Yes | Yes | Private key **sk** in the RSA algorithm.| +| pk | bigint | Yes | Yes | Public key **pk** in the RSA algorithm.| -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +## Key -var mac; -try { - mac = cryptoFramework.createMac("SHA256"); -} catch (error) { - console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); -} -console.error("Mac algName is: " + mac.algName); +Provides APIs for key operations. Before performing cryptographic operations (such as encryption and decryption), you need to construct a child class object of **Key** and pass it to [init()](#init-2) of the [Cipher](#cipher) instance.
Keys can be generated by a key generator. -var KeyBlob; -var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); -var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); -promiseConvertKey.then(symKey => { - var promiseMacInit = mac.init(symKey); - return promiseMacInit; -}).then(() => { - let blob; - var promiseMacUpdate = mac.update(blob); - return promiseMacUpdate; -}).then(() => { - var PromiseMacDoFinal = mac.doFinal(); - return PromiseMacDoFinal; -}).then(macOutput => { - console.error("[Promise]: HMAC result: " + macOutput.data); -}).catch(error => { - console.error("[Promise]: error: " + error.message); -}); -``` +### Attributes -### getMacLength +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| format | string | Yes | No | Format of the key. | +| algName | string | Yes | No | Algorithm name (including the key length).| -getMacLength() : number +### getEncoded -Obtains the MAC length, in bytes. +getEncoded(): DataBlob + +Obtains the byte stream of the key data synchronously. The key can be a symmetric key, public key, or private key. The public key must be in DER encoding format and comply with the ASN.1 syntax and X.509 specifications. The private key must be in DER encoding format and comply with the ASN.1 syntax and PKCS#8 specifications. + +> **NOTE** +> +> When key parameters are used to generate an RSA private key, the private key object does not support **getEncoded()**. **System capability**: SystemCapability.Security.CryptoFramework **Return value** -| Type | Description | -| ------ | ------------------------- | -| number | MAC length obtained.| +| Type | Description | +| --------------------- | ------------------------ | +| [DataBlob](#datablob) | Key obtained.| **Error codes** | ID| Error Message | | -------- | ---------------------- | +| 801 | this operation is not supported. | +| 17620001 | memory error. | | 17630001 | crypto operation error. | **Example** -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" - -var mac; -try { - mac = cryptoFramework.createMac("SHA256"); -} catch (error) { - console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); +function uint8ArrayToShowStr(uint8Array) { + return Array.prototype.map + .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) + .join(''); } -console.error("Mac algName is: " + mac.algName); -var KeyBlob; -var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); -var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); -promiseConvertKey.then(symKey => { - var promiseMacInit = mac.init(symKey); - return promiseMacInit; -}).then(() => { - let blob; - var promiseMacUpdate = mac.update(blob); - return promiseMacUpdate; -}).then(() => { - var PromiseMacDoFinal = mac.doFinal(); - return PromiseMacDoFinal; -}).then(macOutput => { - console.error("[Promise]: HMAC result: " + macOutput.data); - let macLen = mac.getMacLength(); - console.error("MAC len: " + macLen); -}).catch(error => { - console.error("[Promise]: error: " + error.message); -}); +let key; // The key is generated by a key generator. The generation process is omitted here. +let encodedKey = key.getEncoded(); +console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); ``` -## cryptoFramework.createMd - -createMd(algName : string) : Md - -Creates an **Md** instance for message digest operations. - -For details about the supported specifications, see [MD Algorithm Specifications](../../security/cryptoFramework-overview.md#md-algorithm-specifications). - -**System capability**: SystemCapability.Security.CryptoFramework - -**Parameters** +## SymKey -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------------------------------------------------------ | -| algName | string | Yes | Digest algorithm. For details about the supported algorithms, see [MD Algorithm Specifications](../../security/cryptoFramework-overview.md#md-algorithm-specifications).| +Provides APIs for symmetric key operations. It is a child class of [Key](#key). Its objects need to be passed to [init()](#init-2) of the [Cipher](#cipher) instance in symmetric encryption and decryption.
Symmetric keys can be generated by a [SymKeyGenerator](#symkeygenerator). -**Return value** +### clearMem -| Type| Description | -| ---- | ------------------------------------- | -| Md | [Md](#md) instance created.| +clearMem(): void -**Error codes** +Clears the keys in the memory. This API returns the result synchronously. You are advised to use this API when symmetric key instances are no longer used. -| ID| Error Message | -| -------- | ------------------ | -| 17620001 | memory error. | +**System capability**: SystemCapability.Security.CryptoFramework **Example** -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" - -var md; -try { - // Set algName based on the algorithm supported. - md = cryptoFramework.createMd("SHA256"); -} catch (error) { - console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); +function uint8ArrayToShowStr(uint8Array) { + return Array.prototype.map + .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) + .join(''); } + +let key; // The key is generated by a symKeyGenerator. The generation process is omitted here. +let encodedKey = key.getEncoded(); +console.info("key hex: "+ uint8ArrayToShowStr(encodedKey.data)); // Display key content. +key.clearMem(); +encodedKey = key.getEncoded(); +console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); // Display all 0s. ``` -## Md +## PubKey -Provides APIs for message digest operations. Before using any API of the **Md** class, you must create an **Md** instance by using [createMd](#cryptoframeworkcreatemd). +Provides APIs for public key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement.
The public key can be generated by using the asymmetric key generator [AsyKeyGenerator](#asykeygenerator) or [AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10). ### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | -------------------- | -| algName | string | Yes | No | Digest algorithm.| - -### update +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| format | string | Yes | No | Format of the key. | +| algName | string | Yes | No | Algorithm name (including the key length).| -update(input : DataBlob, callback : AsyncCallback\) : void; +### getAsyKeySpec10+ -Updates the message digest data. This API uses an asynchronous callback to return the result. +getAsyKeySpec(itemType: AsyKeySpecItem): bigint | string | number -> **NOTE**
-> For details about the sample code for calling **update()** multiple times, see [Generating a Digest](../../security/cryptoFramework-guidelines.md#generating-a-digest). +Obtains a key parameter synchronously. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------- | -| input | [DataBlob](#datablob)| Yes | Data to pass in.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | +| Name| Type | Mandatory| Description | +| ---- | --------------------- | ---- | -------------------- | +| item | [AsyKeySpecItem](#asykeyspecitem10) | Yes | Key parameter to obtain.| + +**Return value** + +| Type | Description | +| --------------------------- | --------------------------------- | +| bigint\|string\|number | Content of the key parameter obtained.| **Error codes** | ID| Error Message | | -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | | 17630001 | crypto operation error. | **Example** -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +```js +let key; // key is a public key object. The generation process is omitted here. +let p = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_FP_P_BN); +console.info("ecc item --- p: " + p.toString(16)); +``` -var md; -try { - md = cryptoFramework.createMd("SHA256"); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); -} -console.error("Md algName is: " + md.algName); +## PriKey -let blob; -md.update(blob, (err,) => { - if (err) { - console.error("[Callback] err: " + err.code); - } -}); -``` +Provides APIs for private key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signing, and key agreement.
The public key can be generated by using the asymmetric key generator [AsyKeyGenerator](#asykeygenerator) or [AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10). -### update +### Attributes -update(input : DataBlob) : Promise\; +**System capability**: SystemCapability.Security.CryptoFramework -Updates the message digest data. This API uses a promise to return the result. +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| format | string | Yes | No | Format of the key. | +| algName | string | Yes | No | Algorithm name (including the key length).| -> **NOTE**
-> For details about the sample code for calling **update()** multiple times, see [Generating a Digest](../../security/cryptoFramework-guidelines.md#generating-a-digest). +### clearMem + +clearMem(): void + +Clears the keys in the memory. This API returns the result synchronously. **System capability**: SystemCapability.Security.CryptoFramework -| Name| Type | Mandatory| Description | -| ------ | -------- | ---- | ---------- | -| input | DataBlob | Yes | Data to pass in.| +**Example** + +```js +let key; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here. +key.clearMem(); +``` + +### getAsyKeySpec10+ + +getAsyKeySpec(itemType: AsyKeySpecItem): bigint | string | number + +Obtains a key parameter synchronously. + +**System capability**: SystemCapability.Security.CryptoFramework + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | --------------------- | ---- | -------------------- | +| item | [AsyKeySpecItem](#asykeyspecitem10) | Yes | Key parameter to obtain.| **Return value** -| Type | Description | -| -------------- | ----------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| --------------------------- | --------------------------------- | +| bigint\|string\|number | Content of the key parameter obtained.| **Error codes** | ID| Error Message | | -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | | 17630001 | crypto operation error. | **Example** -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +```js +let key; // key is a private key object. The generation process is omitted here. +let p = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_FP_P_BN); +console.info("ecc item --- p: " + p.toString(16)); +``` -var md; -try { - md = cryptoFramework.createMd("SHA256"); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); -} -console.error("Md algName is: " + md.algName); - -let blob; -var promiseMdUpdate = md.update(blob); -promiseMdUpdate.then(() => { - // do something -}).catch(error => { - console.error("[Promise]: error: " + error.message); -}); -``` +## KeyPair -### digest +Defines an asymmetric key pair, which includes a public key and a private key.
The asymmetric key pair can be generated by using the asymmetric key generator [AsyKeyGenerator](#asykeygenerator) or [AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10). -digest(callback : AsyncCallback\) : void +> **NOTE** +> +> The **pubKey** and **priKey** objects in the **KeyPair** object exist as one parameter in the **KeyPair** object. When **KeyPair** leaves the scope, its internal objects can be destructed. +> +> The service must reference the **KeyPair** object instead of the internal **pubKey** or **priKey** object. -Generates a message digest. This API uses an asynchronous callback to return the result. +### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | ------------------------ | ---- | -------- | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| - -**Error codes** - -| ID| Error Message | -| -------- | ---------------------- | -| 17620001 | memory error. | -| 17630001 | crypto operation error. | - -**Example** +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------ | +| priKey | [PriKey](#prikey) | Yes | No | Private key. | +| pubKey | [PubKey](#pubkey) | Yes | No | Public key. | -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" -var md; -try { - md = cryptoFramework.createMd("SHA256"); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); -} -console.error("Md algName is: " + md.algName); +## cryptoFramework.createSymKeyGenerator -let blob; -md.update(blob, (err,) => { - if (err) { - console.error("[Callback] err: " + err.code); - } - md.digest((err1, mdOutput) => { - if (err1) { - console.error("[Callback] err: " + err1.code); - } else { - console.error("[Callback]: MD result: " + mdOutput); - } - }); -}); -``` +createSymKeyGenerator(algName: string): SymKeyGenerator -### digest +Creates a **symKeyGenerator** instance based on the specified algorithm.
For details about the supported specifications, see [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications). -digest() : Promise\ +**System capability**: SystemCapability.Security.CryptoFramework -Generates a message digest. This API uses a promise to return the result. +**Parameters** -**System capability**: SystemCapability.Security.CryptoFramework +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------------------------------------ | +| algName | string | Yes | Algorithm used to create the **symKeyGenerator** instance.
For details, see "String Parameter" in [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications).| **Return value** -| Type | Description | -| ------------------ | ----------- | -| Promise\<[DataBlob](#datablob)> | Promise used to return the result.| - -**Error codes** +| Type | Description | +| ----------------------------------- | -------------------------- | +| [SymKeyGenerator](#symkeygenerator) | **symKeyGenerator** instance created.| | ID| Error Message | | -------- | ---------------------- | -| 17620001 | memory error. | -| 17630001 | crypto operation error. | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | **Example** -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; +let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192'); +``` -var md; -try { - md = cryptoFramework.createMd("SHA256"); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); -} -console.error("Md algName is: " + md.algName); +## SymKeyGenerator -let blob; -var promiseMdUpdate = md.update(blob); -promiseMdUpdate.then(() => { - var PromiseMdDigest = md.digest(); - return PromiseMdDigest; -}).then(mdOutput => { - console.error("[Promise]: MD result: " + mdOutput.data); -}).catch(error => { - console.error("[Promise]: error: " + error.message); -}); -``` +Provides APIs for using the **symKeyGenerator**.
Before using any API of the **SymKeyGenerator** class, you must create a **symKeyGenerator** instance by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). -### getMdLength +### Attributes -getMdLength() : number +**System capability**: SystemCapability.Security.CryptoFramework -Obtains the message digest length, in bytes. +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------ | +| algName | string | Yes | No | Algorithm used by the **symKeyGenerator**.| + +### generateSymKey + +generateSymKey(callback: AsyncCallback\): void + +Generates a key randomly. This API uses an asynchronous callback to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
**RAND_priv_bytes()** of OpenSSL can be used to generate random keys. **System capability**: SystemCapability.Security.CryptoFramework -**Return value** +**Parameters** -| Type | Description | -| ------ | ------------------------ | -| number | Message digest length obtained.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the symmetric key generated. Otherwise, **err** is an error object.| **Error codes** -| ID| Error Message | -| -------- | ---------------------- | -| 17630001 | crypto operation error. | +| ID| Error Message | +| -------- | ------------- | +| 17620001 | memory error. | **Example** -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" - -var md; -try { - md = cryptoFramework.createMd("SHA256"); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); -} -console.error("Md algName is: " + md.algName); - -let blob; -var promiseMdUpdate = md.update(blob); -promiseMdUpdate.then(() => { - var PromiseMdDigest = md.digest(); - return PromiseMdDigest; -}).then(mdOutput => { - console.error("[Promise]: MD result: " + mdOutput.data); - let mdLen = md.getMdLength(); - console.error("MD len: " + mdLen); -}).catch(error => { - console.error("[Promise]: error: " + error.message); -}); +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; +let symAlgName = '3DES192'; +let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); +symKeyGenerator.generateSymKey((err, symKey) => { + if (err) { + console.error(`Generate symKey failed, ${err.code}, ${err.message}`); + } else { + console.info(`Generate symKey success, algName: ${symKey.algName}`); + } +}) ``` -## cryptoFramework.createRandom +### generateSymKey -createRandom() : Random +generateSymKey(): Promise\ -Creates a **Random** instance for generating a random number and setting a seed. +Generates a key randomly. This API uses a promise to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
**RAND_priv_bytes()** of OpenSSL can be used to generate random keys. **System capability**: SystemCapability.Security.CryptoFramework **Return value** -| Type | Description | -| ------ | --------------------------------------------- | -| Random | [Random](#random) instance created.| +| Type | Description | +| --------------------------- | --------------------------------- | +| Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.| **Error codes** -| ID| Error Message | -| -------- | ------------ | +| ID| Error Message | +| -------- | ------------- | | 17620001 | memory error. | **Example** -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" - -try { - var rand = cryptoFramework.createRandom(); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); -} +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; +let symAlgName = 'AES128'; +let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); +symKeyGenerator.generateSymKey() +.then(symKey => { + console.info(`Generate symKey success, algName: ${symKey.algName}`); +}, error => { + console.error(`Generate symKey failed, ${error.code}, ${error.message}`); +}) ``` -## Random - -Provides APIs for computing random numbers and setting seeds. Before using any API of the **Random** class, you must create a **Random** instance by using [createRandom](#cryptoframeworkcreaterandom). - -### generateRandom +### convertKey -generateRandom(len : number, callback: AsyncCallback\) : void; +convertKey(key: DataBlob, callback: AsyncCallback\): void -Generates a random number of the given length. This API uses an asynchronous callback to return the result. +Converts data into a symmetric key. This API uses an asynchronous callback to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------ | ---- | -------------------- | -| len | number | Yes | Length of the random number to generate.| -| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | +| key | [DataBlob](#datablob) | Yes | Data to convert. | +| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the symmetric key generated. Otherwise, **err** is an error object.| **Error codes** -| ID| Error Message | -| -------- | ---------------------- | -| 17620001 | memory error. | -| 17630001 | crypto operation error. | +| ID| Error Message | +| -------- | --------------------------------------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | **Example** -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; -var rand; -try { - rand = cryptoFramework.createRandom(); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +function genKeyMaterialBlob() { + let arr = [ + 0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56, + 0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c, + 0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes) + let keyMaterial = new Uint8Array(arr); + return {data: keyMaterial}; } -rand.generateRandom(12, (err, randData) => { - if (err) { - console.error("[Callback] err: " + err.code); - } else { - console.error("[Callback]: generate random result: " + randData.data); - } -}); + +let symAlgName = '3DES192'; +let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); +let keyMaterialBlob = genKeyMaterialBlob(); +symKeyGenerator.convertKey(keyMaterialBlob, (err, symKey) => { + if (err) { + console.error(`Convert symKey failed, ${err.code}, ${err.message}`); + } else { + console.info(`Convert symKey success, algName: ${symKey.algName}`); + } +}) ``` -### generateRandom +### convertKey -generateRandom(len : number) : Promise\; +convertKey(key: DataBlob): Promise\ -Generates a random number of the given length. This API uses a promise to return the result. +Converts data into a symmetric key. This API uses a promise to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------------------- | -| len | number | Yes | Length of the random number to generate.| +| Name| Type | Mandatory| Description | +| ---- | --------------------- | ---- | -------------------- | +| key | [DataBlob](#datablob) | Yes | Data to convert.| **Return value** -| Type | Description | -| ------------------ | ----------- | -| Promise\<[DataBlob](#datablob)> | Promise used to return the result.| +| Type | Description | +| --------------------------- | --------------------------------- | +| Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.| **Error codes** -| ID| Error Message | -| -------- | ---------------------- | -| 17620001 | memory error. | -| 17630001 | crypto operation error. | +| ID| Error Message | +| -------- | --------------------------------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | **Example** -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; -var rand; -try { - rand = cryptoFramework.createRandom(); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +function genKeyMaterialBlob() { + let arr = [ + 0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56, + 0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c, + 0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes) + let keyMaterial = new Uint8Array(arr); + return {data: keyMaterial}; } -var promiseGenerateRand = rand.generateRandom(12); -promiseGenerateRand.then(randData => { - console.error("[Promise]: rand result: " + randData.data); -}).catch(error => { - console.error("[Promise]: error: " + error.message); -}); +let symAlgName = '3DES192'; +let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); +let keyMaterialBlob = genKeyMaterialBlob(); +symKeyGenerator.convertKey(keyMaterialBlob) +.then(symKey => { + console.info(`Convert symKey success, algName: ${symKey.algName}`); +}, error => { + console.error(`Convert symKey failed, ${error.code}, ${error.message}`); +}) ``` -### setSeed +## cryptoFramework.createAsyKeyGenerator -setSeed(seed : DataBlob) : void; +createAsyKeyGenerator(algName: string): AsyKeyGenerator -Sets a seed. This API uses an asynchronous callback to return the result. +Creates an **AsyKeyGenerator** instance based on the specified algorithm.
For details about the supported specifications, see [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications). **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ---------- | -| seed | DataBlob | Yes | Seed to set.| +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | -------------------------------- | +| algName | string | Yes | Algorithm used to create the **symkeyGenerator**.| + +**Return value** + +| Type | Description | +| --------------- | ---------------------------- | +| [AsyKeyGenerator](#asykeygenerator) | **AsyKeyGenerator** instance created.| **Error codes** -| ID| Error Message | -| -------- | ----------------- | -| 17620001 | memory error. | +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | +| 17620001 | memory error. | **Example** -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" -var rand; -try { - rand = cryptoFramework.createRandom(); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); -} - -rand.generateRandom(12, (err, randData) => { - if (err) { - console.error("[Callback] err: " + err.code); - } else { - console.error("[Callback]: generate random result: " + randData.data); - try { - rand.setSeed(randData); - } catch (error) { - console.log("setSeed failed, errCode: " + error.code + ", errMsg: " + error.message); - } - } -}); +let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); ``` -## ParamsSpec +## AsyKeyGenerator -Defines the parameters used for encryption and decryption. +Provides APIs for using the **AsKeyGenerator**. Before using any API of the **AsKeyGenerator** class, you must create an **AsyKeyGenerator** instance by using **createAsyKeyGenerator()**. -For the symmetric encryption and decryption modes that require parameters such as the initialization vector (IV), you must construct a child class object and pass it to [init()](#init-2). If no IV is required (for example, the ECB mode is used), pass in **null** in [init()](#init-2). +### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | -| algName | string | Yes | Yes | Symmetric encryption and decryption parameters. Options:
- **IvParamsSpec**: applicable to the CBC, CTR, OFB, and CFB modes.
- **GcmParamsSpec**: applicable to the GCM mode.
- **CcmParamsSpec**: applicable to the CCM mode.| - -> **NOTE**
-> The **params** parameter in [init()](#init-2) is of the **ParamsSpec** type (parent class), but a child class object (such as **IvParamsSpec**) needs to be passed in. When constructing the child class object, set **algName** in the parent class **ParamsSpec** to let the algorithm library know the type of child class object to pass in in **init()**. +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | -------------------------------- | +| algName | string | Yes | No | Algorithm used by the **AsKeyGenerator**.| -## IvParamsSpec +### generateKeyPair -Defines the child class of [ParamsSpec](#paramsspec). It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption. +generateKeyPair(callback: AsyncCallback\): void -**IvParamsSpec** applies to the encryption and decryption modes such as CBC, CTR, OFB, and CFB, which use only the IV. +Generates a key pair randomly. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.CryptoFramework -| Name| Type | Readable| Writable| Description | -| ---- | --------------------- | ---- | ---- | ------------------------------------------------------------ | -| iv | [DataBlob](#datablob) | Yes | Yes | IV for encryption and decryption. Options:
- AES CBC, CTR, OFB, or CFB mode: 16-byte IV
- 3DES CBC, OFB, or CFB mode: 8-byte IV| - -> **NOTE**
-> Before passing **IvParamsSpec** to [init()](#init-2), specify **algName** in its parent class [ParamsSpec](#paramsspec). +**Parameters** -## GcmParamsSpec +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------ | +| callback | AsyncCallback\<[KeyPair](#keypair)> | Yes | Callback invoked to return the key pair obtained.| -Defines the child class of [ParamsSpec](#paramsspec) for the GCM mode. It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption. +**Error codes** -**GcmParamsSpec** applies to the GCM mode. +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | -**System capability**: SystemCapability.Security.CryptoFramework +**Example** -| Name | Type | Readable| Writable| Description | -| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | -| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 12 bytes. | -| aad | [DataBlob](#datablob) | Yes | Yes | Additional authenticated data (AAD), which is of 8 bytes. | -| authTag | [DataBlob](#datablob) | Yes | Yes | Authentication tag, which is of 16 bytes.
When the GCM mode is used for encryption, [DataBlob](#datablob) output by [doFinal()](#dofinal-2) is required. The last 16 bytes of [DataBlob](#datablob) are used as as **authTag** in [GcmParamsSpec](#gcmparamsspec) of [init()](#init-2). | +```js +import cryptoFramework from "@ohos.security.cryptoFramework" -> **NOTE** -> Before passing **GcmParamsSpec** to [init()](#init-2), specify **algName** in its parent class [ParamsSpec](#paramsspec). +let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); +asyKeyGenerator.generateKeyPair((err, keyPair) => { + if (err) { + console.error("generateKeyPair: error."); + return; + } + console.info("generateKeyPair: success."); +}) +``` -## CcmParamsSpec +### generateKeyPair -Defines the child class of [ParamsSpec](#paramsspec) for the CCM mode. It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption. +generateKeyPair(): Promise\ -**CcmParamsSpec** applies to the CCM mode. +Generates a key pair randomly. This API uses a promise to return the result. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | -| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 7 bytes. | -| aad | [DataBlob](#datablob) | Yes | Yes | AAD, which is of 8 bytes. | -| authTag | [DataBlob](#datablob) | Yes | Yes | Authentication tag, which is of 12 bytes.
When the CCM mode is used for encryption, [DataBlob](#datablob) output by [doFinal()](#dofinal-2) is required. The last 12 bytes of [DataBlob](#datablob) are used as as **authTag** in [CcmParamsSpec](#ccmparamsspec) of [init()](#init-2).| - -> **NOTE** -> Before passing **CcmParamsSpec** to [init()](#init-2), specify **algName** in its parent class [ParamsSpec](#paramsspec). - -## CryptoMode +**Return value** -Enumerates the cryptographic operations. +| Type | Description | +| ----------------- | --------------------------------- | +| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair generated.| -**System capability**: SystemCapability.Security.CryptoFramework +**Error codes** -| Name | Value | Description | -| ------------ | ---- | ---------------- | -| ENCRYPT_MODE | 0 | Encryption.| -| DECRYPT_MODE | 1 | Decryption.| +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | -## Key +**Example** -Provides APIs for key operations. Before performing cryptographic operations (such as encryption and decryption), you need to construct a child class object of **Key** and pass it to [init()](#init-2) of the [Cipher](#cipher) instance.
Keys can be generated by a key generator. +```js +import cryptoFramework from "@ohos.security.cryptoFramework" -### Attributes +let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); +let keyGenPromise = asyKeyGenerator.generateKeyPair(); +keyGenPromise.then( keyPair => { + console.info("generateKeyPair success."); +}).catch(error => { + console.error("generateKeyPair error."); +}); +``` -**System capability**: SystemCapability.Security.CryptoFramework +### convertKey -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------------- | -| format | string | Yes | No | Format of the key. | -| algName | string | Yes | No | Algorithm name (including the key length).| +convertKey(pubKey: DataBlob, priKey: DataBlob, callback: AsyncCallback\): void -### getEncoded +Converts data into an asymmetric key. This API uses an asynchronous callback to return the result. For details, see **Key Conversion**. -getEncoded() : DataBlob +**System capability**: SystemCapability.Security.CryptoFramework -Obtains a key in hexadecimal format. This API returns the result synchronously. +**Parameters** -**System capability**: SystemCapability.Security.CryptoFramework +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ------------------------------ | +| pubKey | [DataBlob](#datablob) | Yes | Public key material to convert. If no public key is required, set this parameter to **null**. | +| priKey | [DataBlob](#datablob) | Yes | Private key material to convert. If no private key is required, set this parameter to **null**. | +| callback | AsyncCallback\<[KeyPair](#keypair)> | Yes | Callback invoked to return the key pair obtained.| -**Return value** +**Error codes** -| Type | Description | -| --------------------- | ------------------------ | -| [DataBlob](#datablob) | Key obtained.| +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | **Example** ```js import cryptoFramework from "@ohos.security.cryptoFramework" -function uint8ArrayToShowStr(uint8Array) { - return Array.prototype.map - .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) - .join(''); -} -let key; // The key is generated by a symKeyGenerator. The generation process is omitted here. -let encodedKey = key.getEncoded(); -console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); +let pubKeyArray = new Uint8Array([48,89,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,3,66,0,4,83,96,142,9,86,214,126,106,247,233,92,125,4,128,138,105,246,162,215,71,81,58,202,121,26,105,211,55,130,45,236,143,55,16,248,75,167,160,167,106,2,152,243,44,68,66,0,167,99,92,235,215,159,239,28,106,124,171,34,145,124,174,57,92]); +let priKeyArray = new Uint8Array([48,49,2,1,1,4,32,115,56,137,35,207,0,60,191,90,61,136,105,210,16,27,4,171,57,10,61,123,40,189,28,34,207,236,22,45,223,10,189,160,10,6,8,42,134,72,206,61,3,1,7]); +let pubKeyBlob = {data: pubKeyArray}; // Data of the public key. +let priKeyBlob = {data: priKeyArray}; // Data of the private key. +let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); +asyKeyGenerator.convertKey(pubKeyBlob, priKeyBlob, (err, keyPair) => { + if (err) { + console.error("convertKey: error."); + return; + } + console.info("convertKey: success."); +}) ``` -## SymKey +### convertKey -Provides APIs for symmetric key operations. **SymKey** is a child class of [Key](#key), and its objects need to be passed to [init()](#init-2) of the [Cipher](#cipher) instance in symmetric encryption and decryption. +convertKey(pubKey: DataBlob, priKey: DataBlob): Promise\ -Symmetric keys can be generated by a [SymKeyGenerator](#symkeygenerator). +Converts data into an asymmetric key. This API uses a promise to return the result. For details, see **Key Conversion**. -### clearMem +**System capability**: SystemCapability.Security.CryptoFramework + +**Parameters** -clearMem() : void +| Name | Type | Mandatory| Description | +| ------ | -------- | ---- | ---------------- | +| pubKey | DataBlob | Yes | Public key material to convert. If no public key is required, set this parameter to **null**.| +| priKey | DataBlob | Yes | Private key material to convert. If no private key is required, set this parameter to **null**.| -Clears the keys in the memory. This API returns the result synchronously. You are advised to use this API when symmetric key instances are no longer used. +**Return value** -**System capability**: SystemCapability.Security.CryptoFramework +| Type | Description | +| ----------------- | --------------------------------- | +| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair generated.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | **Example** ```js import cryptoFramework from "@ohos.security.cryptoFramework" -function uint8ArrayToShowStr(uint8Array) { - return Array.prototype.map - .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) - .join(''); -} -let key; // The key is generated by a symKeyGenerator. The generation process is omitted here. -let encodedKey = key.getEncoded(); -console.info("key hex: "+ uint8ArrayToShowStr(encodedKey.data)); // Key content is displayed. -key.clearMem(); -encodedKey = key.getEncoded(); -console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); // All 0s are displayed. +let pubKeyArray = new Uint8Array([48,89,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,3,66,0,4,83,96,142,9,86,214,126,106,247,233,92,125,4,128,138,105,246,162,215,71,81,58,202,121,26,105,211,55,130,45,236,143,55,16,248,75,167,160,167,106,2,152,243,44,68,66,0,167,99,92,235,215,159,239,28,106,124,171,34,145,124,174,57,92]); +let priKeyArray = new Uint8Array([48,49,2,1,1,4,32,115,56,137,35,207,0,60,191,90,61,136,105,210,16,27,4,171,57,10,61,123,40,189,28,34,207,236,22,45,223,10,189,160,10,6,8,42,134,72,206,61,3,1,7]); +let pubKeyBlob = {data: pubKeyArray}; // Data of the public key. +let priKeyBlob = {data: priKeyArray}; // Data of the private key. +let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); +let keyGenPromise = asyKeyGenerator.convertKey(pubKeyBlob, priKeyBlob); +keyGenPromise.then( keyPair => { + console.info("convertKey success."); +}).catch(error => { + console.error("convertKey error."); +}); ``` -## PubKey - -Provides APIs for public key operations. **PubKey** is a child class of [Key](#key), and its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement. +**Key Conversion** -Public keys can be generated by an **AsyKeyGenerator**. +1. After **getEncoded()** is called for the asymmetric (RSA, ECC, or DSA) public and private keys, binary data in X.509 format and binary data in PKCS #8 format are returned, respectively. The binary data can be used for cross-application transfer or persistent storage. +2. The public key returned by **convertKey()** must comply with the ASN.1 syntax, X.509 specifications, and DER encoding format, and the private key must comply with the ASN.1 syntax, PKCS #8 specifications, and DER encoding format. +3. In **convertKey()**, you can pass in either **pubKey** or **priKey**, or both of them. If one of them is passed in, the returned **KeyPair** instance contains only the key converted from the data you passed in. -### Attributes +## cryptoFramework.createAsyKeyGeneratorBySpec10+ -**System capability**: SystemCapability.Security.CryptoFramework +createAsyKeyGeneratorBySpec(asyKeySpec: AsyKeySpec): AsyKeyGeneratorBySpec -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------------- | -| format | string | Yes | No | Format of the key. | -| algName | string | Yes | No | Algorithm name (including the key length).| +Creates an **AsyKeyGenerator** instance based on the key parameters.
For details about the supported specifications, see [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications). +**System capability**: SystemCapability.Security.CryptoFramework -### getEncoded +**Parameters** -getEncoded() : DataBlob +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | -------------------------------- | +| asyKeySpec | [AsyKeySpec](#asykeyspec10) | Yes | Key parameters. The **AsyKeyGenerator** generates the public/private key based on the specified parameters.| -Obtains a key in binary format. This API returns the result synchronously. The public key format must comply with the ASN.1 syntax, X.509 specifications, and DER encoding format. +**Return value** -**System capability**: SystemCapability.Security.CryptoFramework +| Type | Description | +| ----------------------------------------------- | -------------------------- | +| [AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10) | Returns the **AsyKeyGenerator** instance created.| -**Return value** +**Error codes** -| Type | Description | -| --------------------- | ------------------------ | -| [DataBlob](#datablob) | Key obtained.| +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | +| 17620001 | memory error. | **Example** ```js -function uint8ArrayToShowStr(uint8Array) { - return Array.prototype.map - .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) - .join(''); +import cryptoFramework from "@ohos.security.cryptoFramework" + +// Set the common parameters contained in both the DSA1024 public and private keys. +function genDsa1024CommonSpecBigE() { + let dsaCommonSpec = { + algName : "DSA", + specType : cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC, + p : BigInt("0xed1501551b8ab3547f6355ffdc2913856ddeca198833dbd04f020e5f25e47c50e0b3894f7690a0d2ea5ed3a7be25c54292a698e1f086eb3a97deb4dbf04fcad2dafd94a9f35c3ae338ab35477e16981ded6a5b13d5ff20bf55f1b262303ad3a80af71aa6aa2354d20e9c82647664bdb6b333b7bea0a5f49d55ca40bc312a1729"), + q : BigInt("0xd23304044019d5d382cfeabf351636c7ab219694ac845051f60b047b"), + g : BigInt("0x2cc266d8bd33c3009bd67f285a257ba74f0c3a7e12b722864632a0ac3f2c17c91c2f3f67eb2d57071ef47aaa8f8e17a21ad2c1072ee1ce281362aad01dcbcd3876455cd17e1dd55d4ed36fa011db40f0bbb8cba01d066f392b5eaa9404bfcb775f2196a6bc20eeec3db32d54e94d87ecdb7a0310a5a017c5cdb8ac78597778bd"), + } + return dsaCommonSpec; +} +// Set full parameters contained in the DSA1024 public and private keys. +function genDsa1024KeyPairSpecBigE() { + let dsaCommonSpec = genDsa1024CommonSpecBigE(); + let dsaKeyPairSpec = { + algName : "DSA", + specType : cryptoFramework.AsyKeySpecType.KEY_PAIR_SPEC, + params : dsaCommonSpec, + sk : BigInt("0xa2dd2adb2d11392c2541930f61f1165c370aabd2d78d00342e0a2fd9"), + pk : BigInt("0xae6b5d5042e758f3fc9a02d009d896df115811a75b5f7b382d8526270dbb3c029403fafb8573ba4ef0314ea86f09d01e82a14d1ebb67b0c331f41049bd6b1842658b0592e706a5e4d20c14b67977e17df7bdd464cce14b5f13bae6607760fcdf394e0b73ac70aaf141fa4dafd736bd0364b1d6e6c0d7683a5de6b9221e7f2d6b"), + } + return dsaKeyPairSpec; } -let key; // The key is a public key generated by the asymmetric key generator. The generation process is omitted here. -console.info("key format:" + key.format); -console.info("key algName:" + key.algName); -var encodedKey = key.getEncoded(); -console.info("key encoded:" + uint8ArrayToShowStr(encodedKey.data)); +let asyKeyPairSpec = genDsa1024KeyPairSpecBigE(); // The JS input must be a positive number in big-endian format. +let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); ``` -## PriKey - -Provides APIs for private key operations. **PriKey** is a child class of [Key](#key), and its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement. +## AsyKeyGeneratorBySpec10+ -Private keys can be generated by an **AsyKeyGenerator**. +Provides APIs for using the **AsKeyGenerator**. Before using the APIs of this class, you need to use [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create an **AsyKeyGeneratorBySpec** instance. ### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------------- | -| format | string | Yes | No | Format of the key. | -| algName | string | Yes | No | Algorithm name (including the key length).| +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | -------------------------- | +| algName | string | Yes | No | Algorithm used by the asymmetric key generator.| -### getEncoded +### generateKeyPair -getEncoded() : DataBlob +generateKeyPair(callback: AsyncCallback\): void -Obtains a key in binary format. This API returns the result synchronously. The private key format must comply with the ASN.1 syntax, PKCS #8 specifications, and DER encoding mode. +Generates an asymmetric key pair. This API uses an asynchronous callback to return the result. When you use key parameters of the **COMMON_PARAMS_SPEC** type to create the key generator, you can obtain a key pair randomly generated. When you use **KEY_PAIR_SPEC** to create the key generator, you can obtain a key pair that matches the key parameters. **System capability**: SystemCapability.Security.CryptoFramework -**Return value** +**Parameters** -| Type | Description | -| --------------------- | ------------------------ | -| [DataBlob](#datablob) | Key obtained.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------ | +| callback | AsyncCallback\<[KeyPair](#keypair)> | Yes | Callback invoked to return the key pair obtained.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | **Example** ```js -function uint8ArrayToShowStr(uint8Array) { - return Array.prototype.map - .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) - .join(''); -} +import cryptoFramework from "@ohos.security.cryptoFramework" -let key; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here. -console.info("key format:" + key.format); -console.info("key algName:" + key.algName); -var encodedKey = key.getEncoded(); -console.info("key encoded:" + uint8ArrayToShowStr(encodedKey.data)); +let asyKeyPairSpec; // asyKeyPairSpec specifies full parameters contained in the private and public keys. The generation process is omitted here. +let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); +asyKeyGeneratorBySpec.generateKeyPair((err, keyPair) => { + if (err) { + console.error("generateKeyPair: error."); + return; + } + console.info("generateKeyPair: success."); +}) ``` -### clearMem +### generateKeyPair -clearMem() : void +generateKeyPair(): Promise\ -Clears the keys in the memory. This API returns the result synchronously. +Generates an asymmetric key pair. This API uses a promise to return the result. When you use key parameters of the **COMMON_PARAMS_SPEC** type to create the key generator, you can obtain a key pair randomly generated. When you use **KEY_PAIR_SPEC** to create the key generator, you can obtain a key pair that matches the key parameters. **System capability**: SystemCapability.Security.CryptoFramework -**Example** - -```js -let key; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here. -key.clearMem(); -``` - -## KeyPair - -Defines an asymmetric key pair, which includes a public key and a private key. - -Asymmetric key pairs can be generated by an **AsyKeyGenerator**. +**Return value** -> **NOTE** -> -> The **pubKey** and **priKey** objects in the **KeyPair** object are defined as one parameter in **KeyPair**. When **KeyPair** leaves the scope, its internal objects may be destructed.
The service must reference the **KeyPair** object instead of the **pubKey** or **priKey** object. +| Type | Description | +| ----------------- | --------------------------------- | +| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair generated.| -### Attributes +**Error codes** -**System capability**: SystemCapability.Security.CryptoFramework +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ------------ | -| priKey | [PriKey](#prikey) | Yes | No | Private key. | -| pubKey | [PubKey](#pubkey) | Yes | No | Public key. | +**Example** +```js +import cryptoFramework from "@ohos.security.cryptoFramework" -## cryptoFramework.createSymKeyGenerator +let asyKeyPairSpec; // asyKeyPairSpec specifies full parameters contained in the private and public keys. The generation process is omitted here. +let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); +let keyGenPromise = asyKeyGeneratorBySpec.generateKeyPair(); +keyGenPromise.then( keyPair => { + console.info("generateKeyPair success."); +}).catch(error => { + console.error("generateKeyPair error."); +}); +``` -createSymKeyGenerator(algName : string) : SymKeyGenerator +### generatePriKey -Creates a **symKeyGenerator** instance based on the specified algorithm. +generatePriKey(callback: AsyncCallback\): void -For details about the supported specifications, see [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications). +Generates a private key. This API uses an asynchronous callback to return the result. If you use key parameters of the **PRIVATE_KEY_SPEC** type to create the key generator, you can obtain the specified private key. If you use **KEY_PAIR_SPEC** to create the key generator, you can obtain the private key from the generated key pair. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------------------------------------------------------ | -| algName | string | Yes | Algorithm used to create the **symKeyGenerator** instance.
For details, see "String Parameter" in [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications). | +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------ | +| callback | AsyncCallback\<[PriKey](#prikey)> | Yes | Callback invoked to return the key pair obtained.| -**Return value** +**Error codes** -| Type | Description | -| ----------------------------------- | -------------------------- | -| [SymKeyGenerator](#symkeygenerator) | **symKeyGenerator** instance created.| +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | **Example** ```js -import cryptoFramework from '@ohos.security.cryptoFramework'; -let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192'); -``` +import cryptoFramework from "@ohos.security.cryptoFramework" -## SymKeyGenerator +let asyKeyPairSpec; // asyKeyPairSpec specifies full parameters contained in the private and public keys. +let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); +asyKeyGeneratorBySpec.generatePriKey((err, prikey) => { + if (err) { + console.error("generatePriKey: error."); + return; + } + console.info("generatePriKey: success."); +}) +``` -Provides APIs for using the **symKeyGenerator**. +### generatePriKey -Before using any API of the **SymKeyGenerator** class, you must create a **symKeyGenerator** instance by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). +generatePriKey(): Promise\ -### Attributes +Generates a private key. This API uses a promise to return the result. If you use key parameters of the **PRIVATE_KEY_SPEC** type to create the key generator, you can obtain the specified private key. If you use **KEY_PAIR_SPEC** to create the key generator, you can obtain the private key from the generated key pair. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ------------------------------ | -| algName | string | Yes | No | Algorithm used by the **symKeyGenerator**.| +**Return value** -### generateSymKey +| Type | Description | +| ----------------- | --------------------------------- | +| Promise\<[PriKey](#prikey)> | Promise used to return the key generated.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | + +**Example** -generateSymKey(callback : AsyncCallback\) : void +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +let asyKeyPairSpec; // asyKeyPairSpec specifies full parameters contained in the private and public keys. +let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); +let keyGenPromise = asyKeyGeneratorBySpec.generatePriKey(); +keyGenPromise.then( priKey => { + console.info("generatePriKey success."); +}).catch(error => { + console.error("generatePriKey error."); +}); +``` -Generates a symmetric key randomly. This API uses an asynchronous callback to return the result. +### generatePubKey -This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). +generatePubKey(callback: AsyncCallback\): void -**RAND_priv_bytes()** of OpenSSL can be used to generate random keys. +Generates a public key. This API uses an asynchronous callback to return the result. If you use key parameters of the **PUBLIC_KEY_SPEC** type to create the key generator, you can obtain the specified public key. If you use **KEY_PAIR_SPEC** to create the key generator, you can obtain the public key from the generated key pair. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the symmetric key generated. Otherwise, **err** is an error object.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------ | +| callback | AsyncCallback\<[PubKey](#pubkey)> | Yes | Callback invoked to return the key pair obtained.| **Error codes** -| ID| Error Message | -| -------- | ------------- | -| 17620001 | memory error. | +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | **Example** ```js -import cryptoFramework from '@ohos.security.cryptoFramework'; -let symAlgName = '3DES192'; -let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); -symKeyGenerator.generateSymKey((err, symKey) => { +import cryptoFramework from "@ohos.security.cryptoFramework" + +let asyKeyPairSpec; // asyKeyPairSpec specifies full parameters contained in the private and public keys. The generation process is omitted here. +let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); +asyKeyGeneratorBySpec.generateKeyPair((err, pubKey) => { if (err) { - console.error(`Generate symKey failed, ${err.code}, ${err.message}`); - } else { - console.info(`Generate symKey success, algName: ${symKey.algName}`); + console.error("generatePubKey: error."); + return; } + console.info("generatePubKey: success."); }) ``` -### generateSymKey - -generateSymKey() : Promise\ +### generatePubKey -Generates a symmetric key randomly. This API uses a promise to return the result. +generatePubKey(): Promise\ -This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). - -**RAND_priv_bytes()** of OpenSSL can be used to generate random keys. +Generates a public key. This API uses a promise to return the result. If you use key parameters of the **PUBLIC_KEY_SPEC** type to create the key generator, you can obtain the specified public key. If you use **KEY_PAIR_SPEC** to create the key generator, you can obtain the public key from the generated key pair. **System capability**: SystemCapability.Security.CryptoFramework **Return value** -| Type | Description | -| --------------------------- | --------------------------------- | -| Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.| +| Type | Description | +| ----------------- | --------------------------------- | +| Promise\<[PubKey](#pubkey)> | Promise used to return the key pair generated.| **Error codes** -| ID| Error Message | -| -------- | ------------- | -| 17620001 | memory error. | +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | **Example** ```js -import cryptoFramework from '@ohos.security.cryptoFramework'; -let symAlgName = 'AES128'; -let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); -symKeyGenerator.generateSymKey() -.then(symKey => { - console.info(`Generate symKey success, algName: ${symKey.algName}`); -}, error => { - console.error(`Generate symKey failed, ${error.code}, ${error.message}`); -}) +import cryptoFramework from "@ohos.security.cryptoFramework" + +let asyKeyPairSpec; // asyKeyPairSpec specifies full parameters contained in the private and public keys. The generation process is omitted here. +let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); +let keyGenPromise = asyKeyGeneratorBySpec.generatePubKey(); +keyGenPromise.then( pubKey => { + console.info("generatePubKey success."); +}).catch(error => { + console.error("generatePubKey error."); +}); ``` -### convertKey +## cryptoFramework.createCipher -convertKey(key : DataBlob, callback : AsyncCallback\) : void +createCipher(transformation: string): Cipher -Converts data into a symmetric key. This API uses an asynchronous callback to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). +Creates a [Cipher](#cipher) instance based on the specified algorithm.
For details about the supported specifications, see [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | -| key | [DataBlob](#datablob) | Yes | Data to convert. | -| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the symmetric key generated. Otherwise, **err** is an error object.| +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ------------------------------------------------------------ | +| transformation | string | Yes | Combination of the algorithm name (including the key length), encryption mode, and padding algorithm of the **Cipher** instance to create.
For details, see **String Parameter** in [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications).| + +> **NOTE** +> +> 1. In symmetric encryption and decryption, the implementation of PKCS #5 is the same as that of PKCS #7. PKCS #5 and PKCS #7 use the same padding length and block length. That is, data is padded with 8 bytes in 3DES and 16 bytes in AES. **noPadding** indicates that no padding is performed.
You need to understand the differences between different block cipher modes and use the correct parameter specifications. For example, padding is required for ECB and CBC. Otherwise, ensure that the plaintext length is an integer multiple of the block size. No padding is recommended for other modes. In this case, the ciphertext length is the same as the plaintext length. +> 2. If RSA is used for asymmetric encryption and decryption, two **Cipher** objects must be created to perform encryption and decryption separately. For symmetric encryption and decryption, one **cipher** object can be used to perform both encryption and decryption as long as the algorithm specifications are the same. + +**Return value** + +| Type | Description | +| ----------------- | ------------------------ | +| [Cipher](#cipher) | [Cipher](#cipher) instance created.| **Error codes** -| ID| Error Message | -| -------- | --------------------------------------------------- | -| 17620001 | memory error. | +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | +| 17620001 | memory error. | **Example** ```js -import cryptoFramework from '@ohos.security.cryptoFramework'; +import cryptoFramework from "@ohos.security.cryptoFramework" -function genKeyMaterialBlob() { - let arr = [ - 0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56, - 0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c, - 0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes) - let keyMaterial = new Uint8Array(arr); - return {data : keyMaterial}; +let cipherAlgName = '3DES192|ECB|PKCS7'; +var cipher; +try { + cipher = cryptoFramework.createCipher(cipherAlgName); + console.info(`cipher algName: ${cipher.algName}`); +} catch (error) { + console.error(`createCipher failed, ${error.code}, ${error.message}`); } - -let symAlgName = '3DES192'; -let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); -let keyMaterialBlob = genKeyMaterialBlob(); -symKeyGenerator.convertKey(keyMaterialBlob, (err, symKey) => { - if (err) { - console.error(`Convert symKey failed, ${err.code}, ${err.message}`); - } else { - console.info(`Convert symKey success, algName: ${symKey.algName}`); - } -}) ``` -### convertKey +## Cipher -convertKey(key : DataBlob) : Promise\ +Provides APIs for cipher operations. The [init()](#init-2), [update()](#update-4), and [doFinal()](#dofinal-2) APIs in this class are called in sequence to implement symmetric encryption or decryption and asymmetric encryption or decryption.
For details about the complete encryption and decryption process, see [Encryption and Decryption](../../security/cryptoFramework-guidelines.md#encryption-and-decryption). -Converts data into a symmetric key. This API uses a promise to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). +A complete symmetric encryption/decryption process is slightly different from the asymmetric encryption/decryption process. + +- Symmetric encryption and decryption: **init()** and **doFinal()** are mandatory. **update()** is optional and can be called multiple times to encrypt or decrypt big data. After **doFinal()** is called to complete an encryption or decryption operation, **init()** can be called to start a new encryption or decryption operation. +- RSA asymmetric encryption and decryption: **init()** and **doFinal()** are mandatory, and **update()** is not supported. **doFinal()** can be called multiple times to encrypt or decrypt big data. **init()** cannot be called repeatedly. If the encryption/decryption mode or padding mode is changed, a new **Cipher** object must be created. + +### Attributes **System capability**: SystemCapability.Security.CryptoFramework -**Parameters** -| Name| Type | Mandatory| Description | -| ---- | --------------------- | ---- | -------------------- | -| key | [DataBlob](#datablob) | Yes | Data to convert.| +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| algName | string | Yes | No | Algorithm.| -**Return value** +### init -| Type | Description | -| --------------------------- | --------------------------------- | -| Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.| +init(opMode: CryptoMode, key: Key, params: ParamsSpec, callback: AsyncCallback\): void + +Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback to return the result.
This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher). + +**System capability**: SystemCapability.Security.CryptoFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | +| key | [Key](#key) | Yes | Key for encryption or decryption. | +| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the initialization is successful, **err** is **undefined**. Otherwise, **err** is an error object. | **Error codes** -| ID| Error Message | -| -------- | --------------------------------------------- | -| 17620001 | memory error. | +| ID| Error Message | +| -------- | --------------------------------------------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error.| **Example** ```js import cryptoFramework from '@ohos.security.cryptoFramework'; +let symKey; // The process of generating the symmetric key is omitted here. +let cipher; // The process of creating a Cipher instance is omitted here. -function genKeyMaterialBlob() { - let arr = [ - 0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56, - 0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c, - 0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes) - let keyMaterial = new Uint8Array(arr); - return {data : keyMaterial}; -} - -let symAlgName = '3DES192'; -let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); -let keyMaterialBlob = genKeyMaterialBlob(); -symKeyGenerator.convertKey(keyMaterialBlob) -.then(symKey => { - console.info(`Convert symKey success, algName: ${symKey.algName}`); -}, error => { - console.error(`Convert symKey failed, ${error.code}, ${error.message}`); +cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null, (err, ) => { + if (err) { + console.error(`Failed to init cipher, ${err.code}, ${err.message}`); + } else { + console.info(`Init cipher success`); + // Perform subsequent operations such as update. + } }) ``` -## cryptoFramework.createAsyKeyGenerator - -createAsyKeyGenerator(algName : string) : AsyKeyGenerator +### init -Creates an **AsyKeyGenerator** instance based on the specified algorithm. +init(opMode: CryptoMode, key: Key, params: ParamsSpec): Promise\ -For details about the supported specifications, see [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications). +Initializes a [cipher](#cipher) instance. This API uses a promise to return the result.
This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | -------------------------------- | -| algName | string | Yes | Algorithm used to create the **symkeyGenerator**.| +| Name | Type | Mandatory| Description | +| ------ | ------------------------- | ---- | ------------------------------------------------------------ | +| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | +| key | [Key](#key) | Yes | Key for encryption or decryption. | +| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in.| **Return value** -| Type | Description | -| --------------- | ---------------------------- | -| [AsyKeyGenerator](#asykeygenerator) | **AsyKeyGenerator** instance created.| - -**Example** - -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" - -let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); -``` +| Type | Description | +| -------------- | -------------------------------------- | +| Promise\ | Promise that returns no value.| -## AsyKeyGenerator +**Error codes** -Provides APIs for using the **AsKeyGenerator**. Before using any API of the **AsKeyGenerator** class, you must create an **AsyKeyGenerator** instance by using **createAsyKeyGenerator()**. +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error.| -### Attributes +**Example** -**System capability**: SystemCapability.Security.CryptoFramework +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; +let symKey; // The process of generating the symmetric key is omitted here. +let cipher; // The process of creating a Cipher instance is omitted here. +cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null) +.then(() => { + console.info(`Init cipher success`); + // Perform subsequent operations such as update. +}, error => { + console.error(`Failed to init cipher, ${error.code}, ${error.message}`); +}) +``` -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | -------------------------------- | -| algName | string | Yes | No | Algorithm used by the **AsKeyGenerator**.| +### update -### generateKeyPair +update(data: DataBlob, callback: AsyncCallback\): void -generateKeyPair(callback : AsyncCallback\) : void; +Updates the data to encrypt or decrypt by segment. This API uses an asynchronous callback to return the encrypted or decrypted data.
This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](init-2). -Generates a key pair randomly. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> 1. If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update()** and **doFinal()** is null. If the result is not null, obtain the data to concatenate the complete ciphertext or plaintext. The reason is the block mode and the related specifications affect the **update()** and [doFinal()](#dofinal-2) results.
For example, in ECB and CBC modes, data is encrypted or decrypted by block no matter whether the data passed in by **update()** is an integer multiple of the block length, and the encrypted/decrypted block data generated by this **update()** is output.
That is, encrypted/decrypted data is returned as long as the data passed in by **update()** reaches the size of a block. Otherwise, **null** is returned and the data will be retained until a block is formed in the next **update()**/**doFinal()**.
When **doFinal()** is called, the data that has not been encrypted or decrypted will be padded based on the padding mode set in [createCipher](#cryptoframeworkcreatecipher) to an integer multiple of the block length, and then encrypted or decrypted.
For a mode in which a block cipher can be converted into a stream cipher, the length of the ciphertext may be the same as that of the plaintext. +> 2. **update()** may be called multiple times or may not be called ([doFinal()](#dofinal-2) is called after [init](#init-2)), depending on the size of the data to encrypt or decrypt. +> The algorithm library does not set a limit on the amount of data that can be passed in by **updated()** (once or accumulatively). For symmetric encryption and decryption of a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment. +> For details about the sample code for calling **update()** multiple times in AES, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encryption-and-decryption). +> 3. RSA asymmetric encryption and decryption do not support **update()**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | ------------------------------ | -| callback | AsyncCallback\<[KeyPair](#keypair)> | Yes | Callback invoked to return the key pair obtained.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | +| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be **null** or {data:Uint8Array (empty)}. | +| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**, and **data** is **DataBlob** (containing the encrypted or decrypted data). Otherwise, **err** is an error object.| **Error codes** -| ID| Error Message | -| -------- | ---------------------- | -| 17620001 | memory error. | +| ID| Error Message | +| -------- | ------------------------------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | **Example** -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; -let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); -asyKeyGenerator.generateKeyPair((err, keyPair) => { +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} + +let cipher; // The process of creating a Cipher instance is omitted here. +// The init() process is omitted here. +let plainText = {data: stringToUint8Array('this is test!')}; +cipher.update(plainText, (err, output) => { // Example of the encryption process. if (err) { - console.error("generateKeyPair: error."); - return; + console.error(`Failed to update cipher`); + } else { + console.info(`Update cipher success`); + if (output != null) { + // Concatenate output.data to the ciphertext. + } + // Perform subsequent operations such as doFinal(). } - console.info("generateKeyPair: success."); }) ``` +### update -### generateKeyPair +update(data: DataBlob): Promise\ -generateKeyPair() : Promise\ +Updates the data to encrypt or decrypt by segment. This API uses a promise to return the encrypted or decrypted data. -Generates a key pair randomly. This API uses a promise to return the result. +This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](init-2). + +> **NOTE** +> +> 1. If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update()** and **doFinal()** is null. If the result is not null, obtain the data to concatenate the complete ciphertext or plaintext. The reason is the block mode and the related specifications affect the **update()** and [doFinal()](#dofinal-2) results.
For example, in ECB and CBC modes, data is encrypted or decrypted by block no matter whether the data passed in by **update()** is an integer multiple of the block length, and the encrypted/decrypted block data generated by this **update()** is output.
That is, encrypted/decrypted data is returned as long as the data passed in by **update()** reaches the size of a block. Otherwise, **null** is returned and the data will be retained until a block is formed in the next **update()**/**doFinal()**.
When **doFinal()** is called, the data that has not been encrypted or decrypted will be padded based on the padding mode set in [createCipher](#cryptoframeworkcreatecipher) to an integer multiple of the block length, and then encrypted or decrypted.
For a mode in which a block cipher can be converted into a stream cipher, the length of the ciphertext may be the same as that of the plaintext. +> 2. **update()** may be called multiple times or may not be called ([doFinal()](#dofinal-2) is called after [init](#init-2)), depending on the size of the data to encrypt or decrypt. +> The algorithm library does not set a limit on the amount of data that can be passed in by **updated()** (once or accumulatively). For symmetric encryption and decryption of a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment. +> For details about the sample code for calling **update()** multiple times in AES, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encryption-and-decryption). +> 3. RSA asymmetric encryption and decryption do not support **update()**. **System capability**: SystemCapability.Security.CryptoFramework +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | --------------------- | ---- | -------------------- | +| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be **null** or {data:Uint8Array (empty)}.| + **Return value** -| Type | Description | -| ----------------- | --------------------------------- | -| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair generated.| +| Type | Description | +| ------------------------------- | ------------------------------------------------ | +| Promise\<[DataBlob](#datablob)> | Promise used to return the **DataBlob** (containing the encrypted or decrypted data).| **Error codes** -| ID| Error Message | -| -------- | ---------------------- | -| 17620001 | memory error. | +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | **Example** -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; -let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); -let keyGenPromise = asyKeyGenerator.generateKeyPair(); -keyGenPromise.then( keyPair => { - console.info("generateKeyPair success."); -}).catch(error => { - console.error("generateKeyPair error."); -}); +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} + +let cipher; // The process of creating a Cipher instance is omitted here. +// The init() process is omitted here. +let plainText = {data: stringToUint8Array('this is test!')}; +cipher.update(plainText) +.then((output) => { + console.info(`Update cipher success.`); + if (output != null) { + // Concatenate output.data to the ciphertext. + } + // Perform subsequent operations such as doFinal(). +}, error => { + console.info(`Update cipher failed.`); +}) ``` -### convertKey +### doFinal + +doFinal(data: DataBlob, callback: AsyncCallback\): void -convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\) : void +(1) Encrypts or decrypts the remaining data (generated by the block cipher mode) and the data passed in by **doFinal()** to finalize the symmetric encryption or decryption. This API uses an asynchronous callback to return the encrypted or decrypted data.
If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in data without using **update()**. If all the data has been passed in by [update()](#update-4), you can pass in **null** in **data** of **doFinal()**.
The output of **doFinal()** varies with the symmetric encryption/decryption mode in use. -Converts data into an asymmetric key. This API uses an asynchronous callback to return the result. For more information, see **Key Conversion**. +- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **null** is passed in by **data** of **doFinal()**, the result of **doFinal()** is **authTag**.
**authTag** must be [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) used for decryption. The ciphertext is the **data** passed in for decryption. +- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext. + +(2) Encrypts or decrypts the input data for RSA asymmetric encryption/decryption. This API uses an asynchronous callback to return the result. If a large amount of data needs to be encrypted/decrypted, call **doFinal()** multiple times and concatenate the result of each **doFinal()** to obtain the complete plaintext/ciphertext. + +> **NOTE** +> +> 1. In symmetric encryption or decryption, calling **doFinal()** means the end of an encryption or decryption process, and the [Cipher](#cipher) instance state will be cleared. To start a new encryption or decryption operation, you must call [init()](#init-2) to pass in a complete parameter list for initialization.
For example, if the same symmetric key is used for a **Cipher** instance to perform encryption and then decryption. After the encryption is complete, the **params** in **init** for decryption must be set instead of being **null**. +> 2. If a decryption fails, check whether the data to be encrypted and decrypted matches the parameters in **[init](#init-2)**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption. +> 3. The result of **doFinal()** may be **null**. To avoid exceptions, determine whether the result is **null** before using the **.data** field to access the **doFinal()** result. +> 4. For details about the sample code for calling **doFinal()** multiple times during RSA asymmetric encryption and decryption, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encryption-and-decryption). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------- | ---- | ------------------------------ | -| pubKey | [DataBlob](#datablob) | Yes | Public key material to convert. If no public key is required, set this parameter to **null**. | -| priKey | [DataBlob](#datablob) | Yes | Private key material to convert. If no private key is required, set this parameter to **null**. | -| callback | AsyncCallback\<[KeyPair](#keypair)> | Yes | Callback invoked to return the key pair obtained.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | +| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It can be **null** in symmetric encryption or decryption, but cannot be {data:Uint8Array(empty)}. | +| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. If the data is successfully encrypted or decrypted, **err** is **undefined**, and **data** is the **DataBlob** (encryption or decryption result of the remaining data). Otherwise, **err** is an error object.| **Error codes** -| ID| Error Message | -| -------- | ---------------------- | -| 17620001 | memory error. | +| ID| Error Message | +| -------- | ----------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | **Example** -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" -let pubKey; // Public key data in DER format complying with X.509 specifications. The data is omitted here. -let priKey; // Private key data in DER format complying with PKCS#8 specifications. The data is omitted here. -let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); -asyKeyGenerator.convertKey(pubKey, priKey, (err, keyPair) => { +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; + +let cipher; // The process of creating a Cipher instance is omitted here. +let data; // The process of preparing the data to encrypt or decrypt is omitted here. +// The init() and update() processes are omitted here. +cipher.doFinal(data, (err, output) => { if (err) { - console.error("convertKey: error."); - return; + console.error(`Failed to finalize cipher, ${err.code}, ${err.message}`); + } else { + console.info(`Finalize cipher success`); + if (output != null) { + // Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag). + } } - console.info("convertKey: success."); }) ``` -### convertKey +### doFinal + +doFinal(data: DataBlob): Promise\ + +(1) Encrypts or decrypts the remaining data (generated by the block cipher mode) and the data passed in by **doFinal()** to finalize the symmetric encryption or decryption. This API uses a promise to return the encrypted or decrypted data.
If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in data without using **update()**. If all the data has been passed in by [update()](#update-4), you can pass in **null** in **data** of **doFinal()**.
The output of **doFinal()** varies with the symmetric encryption/decryption mode in use. + +- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **null** is passed in by **data** of **doFinal()**, the result of **doFinal()** is **authTag**.
**authTag** must be [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) used for decryption. The ciphertext is the **data** passed in for decryption. +- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext. -convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\ +(2) Encrypts or decrypts the input data for RSA asymmetric encryption/decryption. This API uses a promise to return the result. If a large amount of data needs to be encrypted/decrypted, call **doFinal()** multiple times and concatenate the result of each **doFinal()** to obtain the complete plaintext/ciphertext. -Converts data into an asymmetric key. This API uses a promise to return the result. For more information, see **Key Conversion**. +> **NOTE** +> +> 1. In symmetric encryption or decryption, calling **doFinal()** means the end of an encryption or decryption process, and the [Cipher](#cipher) instance state will be cleared. To start a new encryption or decryption operation, you must call [init()](#init-2) to pass in a complete parameter list for initialization.
For example, if the same symmetric key is used for a **Cipher** instance to perform encryption and then decryption. After the encryption is complete, the **params** in **init** for decryption must be set instead of being **null**. +> 2. If a decryption fails, check whether the data to be encrypted and decrypted matches the parameters in **[init](#init-2)**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption. +> 3. The result of **doFinal()** may be **null**. To avoid exceptions, determine whether the result is **null** before using the **.data** field to access the **doFinal()** result. +> 4. For details about the sample code for calling **doFinal()** multiple times during RSA asymmetric encryption and decryption, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encryption-and-decryption). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| ------ | -------- | ---- | ---------------- | -| pubKey | DataBlob | Yes | Public key material to convert. If no public key is required, set this parameter to **null**.| -| priKey | DataBlob | Yes | Private key material to convert. If no private key is required, set this parameter to **null**.| +| Name| Type | Mandatory| Description | +| ---- | --------------------- | ---- | -------------------- | +| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It can be **null**, but cannot be {data:Uint8Array(empty)}.| **Return value** -| Type | Description | -| ----------------- | --------------------------------- | -| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair obtained. | +| Type | Description | +| ------------------------------- | ------------------------------------------------ | +| Promise\<[DataBlob](#datablob)> | Promise used to return the **DataBlob**, which is the encryption or decryption result of the remaining data.| **Error codes** -| ID| Error Message | -| -------- | ---------------------- | -| 17620001 | memory error. | +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | **Example** -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; -let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); -let pubKey; // pubKey is a public key generated by the asymmetric key generator. The generation process is omitted here. -let priKey; // priKey is a private key generated by the asymmetric key generator. The generation process is omitted here. -let keyGenPromise = asyKeyGenerator.convertKey(pubKey, priKey); -keyGenPromise.then( keyPair => { - console.info("convertKey success."); -}).catch(error => { - console.error("convertKey error."); -}); -``` - -**Key Conversion** +let cipher; // The process of creating a Cipher instance is omitted here. +let data; // The process of preparing the data to encrypt or decrypt is omitted here. +// The init() and update() processes are omitted here. +cipher.doFinal(data) +.then(output => { + console.info(`Finalize cipher success`); + if (output != null) { + // Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag). + } +}, error => { + console.error(`Failed to finalize cipher, ${error.code}, ${error.message}`); +}) +``` -- If **getEncoded()** is called to obtain a public key and a private key (RSA and ECC), binary data in X.509 format and binary data in PKCS #8 format are returned, respectively. The data can be used for cross-application transfer or persistent storage. -- When **convertKey()** is called to convert binary data into an asymmetric key pair, the public key material must comply with the ASN.1 syntax, X.509 specifications, and DER encoding format, and the private key material must comply with the ASN.1 syntax, PKCS #8 specifications, and DER encoding format. -- In **convertKey()**, you can pass in either **pubKey** or **priKey**, or both of them. If one of them is passed in, the returned **KeyPair** instance contains only the key converted from the data you passed in. +**RSA encryption example (callback)** -## cryptoFramework.createCipher +```js +import cryptoFramework from "@ohos.security.cryptoFramework" -createCipher(transformation : string) : Cipher +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} -Creates a [Cipher](#cipher) instance based on the specified algorithm. +let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); +let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); +rsaGenerator.generateKeyPair(function (err, keyPair) { + let pubKey = keyPair.pubKey; + cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null, function (err, data) { + let plainText = "this is cipher text"; + let input = {data: stringToUint8Array(plainText) }; + cipher.doFinal(input, function (err, data) { + AlertDialog.show({ message: "EncryptOutPut is " + data.data} ); + }); + }); +}); +``` -For details about the supported specifications, see [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). +**RSA encryption example (promise)** -**System capability**: SystemCapability.Security.CryptoFramework +```js +import cryptoFramework from "@ohos.security.cryptoFramework" -**Parameters** +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} -| Name | Type | Mandatory| Description | -| -------------- | ------ | ---- | ------------------------------------------------------------ | -| transformation | string | Yes | Combination of the algorithm name (including the key length), encryption mode, and padding algorithm of the **Cipher** instance to create.
For details, see **Algorithm String** in [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). | +let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); +let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); +let keyGenPromise = rsaGenerator.generateKeyPair(); +keyGenPromise.then(rsaKeyPair => { + let pubKey = rsaKeyPair.pubKey; + return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null); // Pass in the private key and DECRYPT_MODE to initialize the decryption mode. +}).then(() => { + let plainText = "this is cipher text"; + let input = { data: stringToUint8Array(plainText) }; + return cipher.doFinal(input); +}).then(dataBlob => { + console.info("EncryptOutPut is " + dataBlob.data); +}); +``` > **NOTE** -> - In symmetric encryption and decryption, the implementation of PKCS #5 is the same as that of PKCS #7. PKCS #5 and PKCS #7 use the same padding length and block length. That is, data is padded with 8 bytes in 3DES and 16 bytes in AES. **noPadding** indicates that no padding is performed.
You need to understand the differences between different block cipher modes and set parameter correctly. For example, padding is required for ECB and CBC. Otherwise, the plaintext length must be an integer multiple of the block size. No padding is recommended for other modes. In this case, the ciphertext length is the same as the plaintext length. -> - If RSA is used for asymmetric encryption and decryption, two **Cipher** objects must be created to perform encryption and decryption separately. For symmetric encryption and decryption, one **cipher** object can be used to perform both encryption and decryption as long as the algorithm specifications are the same. - -**Return value** - -| Type | Description | -| ----------------- | ------------------------ | -| [Cipher](#cipher) | [Cipher](#cipher) instance created.| - -**Example** - -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +> +> For more encryption and decryption examples, see [Encryption and Decryption](../../security/cryptoFramework-guidelines.md#encryption-and-decryption). -let cipherAlgName = '3DES192|ECB|PKCS7'; -var cipher; -try { - cipher = cryptoFramework.createCipher(cipherAlgName); - console.info(`cipher algName: ${cipher.algName}`); -} catch (error) { - console.error(`createCipher failed, ${error.code}, ${error.message}`); -} -``` +### setCipherSpec10+ -## Cipher +setCipherSpec(itemType: CipherSpecItem, itemValue: Uint8Array): void -Provides APIs for cipher operations. The [init()](#init-2), [update()](#update-4), and [doFinal()](#dofinal-2) APIs in this class are called in sequence to implement symmetric encryption/decryption and asymmetric encryption/decryption. +Sets cipher specifications. You can use this API to set cipher specifications that cannot be set by [createCipher](#cryptoframeworkcreatecipher). Currently, only the RSA is supported. -For details about the complete encryption and decryption process, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting-data). +**System capability**: SystemCapability.Security.CryptoFramework -A complete symmetric encryption/decryption process is slightly different from the asymmetric encryption/decryption process. +**Parameters** -- In symmetric encryption and decryption, **init()** and **doFinal()** are mandatory. **update()** is optional and can be called multiple times to encrypt or decrypt big data by segment. After **doFinal()** is called to complete an encryption/decryption operation, **init()** can be called to start a new encryption/decryption operation. -- In RSA asymmetric encryption and decryption, **init()** and **doFinal()** are mandatory, and **update()** is not supported. **doFinal()** can be called multiple times to encrypt or decrypt big data by segment. **init()** cannot be called repeatedly. If the encryption/decryption mode or padding mode is changed, a new **Cipher** object must be created. +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| itemType | [CipherSpecItem](#cipherspecitem10) | Yes | Cipher parameter to set.| +| itemValue | Uint8Array | Yes | Value of the parameter to set.| -### Attributes +**Error codes** -**System capability**: SystemCapability.Security.CryptoFramework +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | +**Example** -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------------- | -| algName | string | Yes | No | Algorithm.| +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; -### init +let cipher; // The process of generating the Cipher instance is omitted here. +let pSource = new Uint8Array([1,2,3,4]); +cipher.setCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR, pSource); +``` -init(opMode : CryptoMode, key : Key, params : ParamsSpec, callback : AsyncCallback\) : void +### getCipherSpec10+ -Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback to return the result. +getCipherSpec(itemType: CipherSpecItem): string | Uint8Array -This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher). +Obtains cipher specifications. Currently, only the RSA is supported. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | -| key | [Key](#key) | Yes | Key for encryption or decryption. | -| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the initialization is successful, **err** is **undefined**. Otherwise, **err** is an error object. | +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ---------- | +| itemType | [CipherSpecItem](#cipherspecitem10) | Yes | Cipher parameter to obtain.| + +**Return value** + +| Type | Description | +| -------------- | ----------- | +| string\|Uint8Array | Returns the value of the cipher parameter obtained.| **Error codes** -| ID| Error Message | -| -------- | --------------------------------------------------------- | -| 17620001 | memory error. | -| 17620002 | runtime error. | -| 17630001 | crypto operation error.| +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | **Example** ```js import cryptoFramework from '@ohos.security.cryptoFramework'; -let symKey; // The process of generating the symmetric key is omitted here. -let cipher; // The process of creating a Cipher instance is omitted here. -cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null, (err, ) => { - if (err) { - console.error(`Failed to init cipher, ${err.code}, ${err.message}`); - } else { - console.info(`Init cipher success`); - // Perform subsequent operations such as update. - } -}) +let cipher; // The process of generating the Cipher instance is omitted here. +let mdName = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MD_NAME_STR); ``` -### init - -init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\ +## cryptoFramework.createSign -Initializes a [cipher](#cipher) instance. This API uses a promise to return the result. +createSign(algName: string): Sign -This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher). +Creates a **Sign** instance. For details about the supported specifications, see [Signing and Signature Verification Specifications](../../security/cryptoFramework-overview.md#signing-and-signature-verification-specifications). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| ------ | ------------------------- | ---- | ------------------------------------------------------------ | -| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | -| key | [Key](#key) | Yes | Key for encryption or decryption. | -| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in.| +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------------------------------------ | +| algName | string | Yes | Signing algorithm, which can be RSA, ECC, or DSA.
If the RSA PKCS1 mode is used, you need to set the digest. If the RSA PSS mode is used, you need to set the digest and mask digest.| **Return value** -| Type | Description | -| -------------- | -------------------------------------- | -| Promise\ | Promise that returns no value.| +| Type| Description | +| ---- | ---------------------------------- | +| Sign | Returns the **Sign** instance created.| **Error codes** -| ID| Error Message | -| -------- | ------------------------------------------------- | -| 17620001 | memory error. | -| 17620002 | runtime error. | -| 17630001 | crypto operation error.| +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | +| 17620001 | memory error. | **Example** ```js -import cryptoFramework from '@ohos.security.cryptoFramework'; -let symKey; // The process of generating the symmetric key is omitted here. -let cipher; // The process of creating a Cipher instance is omitted here. -cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null) -.then(() => { - console.info(`Init cipher success`); - // Perform subsequent operations such as update. -}, error => { - console.error(`Failed to init cipher, ${error.code}, ${error.message}`); -}) +import cryptoFramework from "@ohos.security.cryptoFramework" + +let signer1 = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); + +let singer2 = cryptoFramework.createSign("RSA1024|PSS|SHA256|MGF1_SHA256"); + +let singer3 = cryptoFramework.createSign("ECC224|SHA256"); + +let singer4 = cryptoFramework.createSign("DSA2048|SHA256"); ``` -### update +## Sign -update(data : DataBlob, callback : AsyncCallback\) : void +Provides APIs for signing. Before using any API of the **Sign** class, you must create a **Sign** instance by using **createSign(algName: string): Sign**. Invoke **init()**, **update()**, and **sign()** in this class in sequence to complete the signing operation. For details about the sample code, see [Signing and Signature Verification](../../security/cryptoFramework-guidelines.md#signing-and-signature-verification). -Updates the data to encrypt or decrypt by segment. This API uses an asynchronous callback to return the encrypted or decrypted data. +The **Sign** class does not support repeated initialization. When a new key is used for signing, you must create a new **Sign** object and call **init()** for initialization. -This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](init-2). +The signing mode is determined in **createSign()**, and the key is set by **init()**. -> **NOTE** -> - The **update()** and [doFinal()](#dofinal-2) results vary with the block mode you use. If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update()** and **doFinal()** is null. If the result is not null, obtain the data to concatenate the complete ciphertext or plaintext.
For example, in ECB and CBC modes, data is encrypted or decrypted by block no matter whether the data passed in by **update()** is an integer multiple of the block length, and the encrypted/decrypted block data generated by this **update()** is output.
That is, data is output by **update()** as long as the input data is of the block size. Otherwise, **null** is returned and the data will be retained until a block is formed in the next **update()**/**doFinal()**.
When **doFinal()** is called, the data that has not been encrypted or decrypted will be padded based on the padding mode set in [createCipher](#cryptoframeworkcreatecipher) to an integer multiple of the block length, and then encrypted or decrypted.
For a mode in which a block cipher can be converted into a stream cipher, the length of the ciphertext may be the same as that of the plaintext. -> - **update()** can be called multiple times or not be called ([doFinal()](#dofinal-2) is called after [init](#init-2)), depending on the size of the data to encrypt or decrypt.
The algorithm library does not set a limit on the amount of data that can be passed in by **updated()** (once or accumulatively). For symmetric encryption and decryption of a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment.
For details about the sample code for calling **update()** multiple times in AES, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting-data). -> - RSA asymmetric encryption and decryption do not support **update()**. +If the data to be signed is short, you can directly call **sign()** to pass in the original data for signing after **init()**. That is, you do not need to use **update()**. + +If the data to be signed is long, you can use **update()** to pass in the data by segment, and then use **sign()** to sign the entire data. + +If **update()** is used to pass in data by segment, **data** of **sign()** can be **null**. + +### Attributes **System capability**: SystemCapability.Security.CryptoFramework -**Parameters** +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| algName | string | Yes | No | Algorithm to use.| -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | -| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be **null** or {data:Uint8Array (null)}. | -| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**, and **data** is **DataBlob** (containing the encrypted or decrypted data). Otherwise, **err** is an error object.| +### init -**Error codes** +init(priKey: PriKey, callback: AsyncCallback\): void -| ID| Error Message | -| -------- | ------------------------------------------- | -| 17620001 | memory error. | -| 17620002 | runtime error. | -| 17630001 | crypto operation error. | +Initializes a **Sign** object using a private key. This API uses an asynchronous callback to return the result. The **Sign** class does not support repeated calling of **init()**. -**Example** +**System capability**: SystemCapability.Security.CryptoFramework -```js -import cryptoFramework from '@ohos.security.cryptoFramework'; +**Parameters** -function stringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - return new Uint8Array(arr); -} +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------- | +| priKey | [PriKey](#prikey) | Yes | Private key used for the initialization.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | -let cipher; // The process of creating a Cipher instance is omitted here. -// The init() process is omitted here. -let plainText = {data : stringToUint8Array('this is test!')}; -cipher.update(plainText, (err, output) => { // Example of the encryption process. - if (err) { - console.error(`Failed to update cipher`); - } else { - console.info(`Update cipher success`); - if (output != null) { - // Concatenate output.data to the ciphertext. - } - // Perform subsequent operations such as doFinal(). - } -}) -``` +**Error codes** -### update +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | -update(data : DataBlob) : Promise\ +### init -Updates the data to encrypt or decrypt by segment. This API uses a promise to return the encrypted or decrypted data.
This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](init-2). +init(priKey: PriKey): Promise\ -> **NOTE** -> - The **update()** and [doFinal()](#dofinal-2) results vary with the block mode you use. If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update()** and **doFinal()** is null. If the result is not null, obtain the data to concatenate the complete ciphertext or plaintext.
For example, in ECB and CBC modes, data is encrypted or decrypted by block no matter whether the data passed in by **update()** is an integer multiple of the block length, and the encrypted/decrypted block data generated by this **update()** is output.
That is, data is output as long as the data passed in by **update()** is of the block size. Otherwise, **null** is returned and the data will be retained until a block is formed in the next **update()**/**doFinal()**.
When **doFinal()** is called, the data that has not been encrypted or decrypted will be padded based on the padding mode set in [createCipher](#cryptoframeworkcreatecipher) to an integer multiple of the block length, and then encrypted or decrypted.
For a mode in which a block cipher can be converted into a stream cipher, the length of the ciphertext may be the same as that of the plaintext. -> - **update()** can be called multiple times or not be called ([doFinal()](#dofinal-2) is called after [init](#init-2)), depending on the size of the data to encrypt or decrypt.
The algorithm library does not set a limit on the amount of data that can be passed in by **updated()** (once or accumulatively). For symmetric encryption and decryption of a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment. For details about the sample code for calling **update()** multiple times in AES, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting-data). -> - RSA asymmetric encryption and decryption do not support **update()**. +Initializes a **Sign** object using a private key. This API uses a promise to return the result. The **Sign** class does not support repeated calling of **init()**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ---- | --------------------- | ---- | -------------------- | -| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be **null** or {data:Uint8Array (null)}.| +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------------- | +| priKey | [PriKey](#prikey) | Yes | Private key used for the initialization.| **Return value** -| Type | Description | -| ------------------------------- | ------------------------------------------------ | -| Promise\<[DataBlob](#datablob)> | Promise used to return the **DataBlob** (containing the encrypted or decrypted data).| +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise that returns no value.| **Error codes** -| ID| Error Message | -| -------- | -------------------------------------------- | -| 17620001 | memory error. | -| 17620002 | runtime error. | -| 17630001 | crypto operation error. | +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | -**Example** +### update -```js -import cryptoFramework from '@ohos.security.cryptoFramework'; +update(data: DataBlob, callback: AsyncCallback\): void -function stringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - return new Uint8Array(arr); -} +Updates the data to be signed. This API uses a callback to complete the update.
This API can be called only after the [Sign](#sign) instance is initialized by using [init()](init-2). -let cipher; // The process of creating a Cipher instance is omitted here. -// The init() process is omitted here. -let plainText = {data : stringToUint8Array('this is test!')}; -cipher.update(plainText) -.then((output) => { - console.info(`Update cipher success.`); - if (output != null) { - // Concatenate output.data to the ciphertext. - } - // Perform subsequent operations such as doFinal(). -}, error => { - console.info(`Update cipher failed.`); -}) -``` +> **NOTE** +> +> **update()** may be called multiple times or may not be called (call [sign](#sign-1) after [init](#init-2)), depending on the size of the data.
The algorithm library does not set a limit on the amount of data to be updated (once or accumulatively). If a large amount of data needs to be signed, you are advised to use **update()** multiple times to pass in data. This can prevent too much memory from being requested at a time.
For details about the sample code for calling **update()** multiple times, see [Signing and Signature verification](../../security/cryptoFramework-guidelines.md#signing-and-signature-verification). -### doFinal +**System capability**: SystemCapability.Security.CryptoFramework -doFinal(data : DataBlob, callback : AsyncCallback\) : void +**Parameters** -(1) Encrypts or decrypts the remaining data (generated by the block ciper mode) and the data passed in by **doFinal()** to finalize the symmetric encryption or decryption. This API uses an asynchronous callback to return the encrypted or decrypted data.
If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in data without using **update()**. If all the data has been passed in by [update()](#update-4), you can pass in **null** in **data** of **doFinal()**. +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------ | +| data | [DataBlob](#datablob) | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | -The output of **doFinal()** varies with the symmetric encryption/decryption mode in use. +**Error codes** -- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **null** is passed in by **data** of **doFinal()**, the result of **doFinal()** is **authTag**.
**authTag** must be [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) used for decryption. The ciphertext is the **data** passed in for decryption. -- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext. +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | -(2) Encrypts or decrypts the input data for RSA asymmetric encryption/decryption. This API uses an asynchronous callback to return the result. If a large amount of data needs to be encrypted/decrypted, call **doFinal()** multiple times and concatenate the result of each **doFinal()** to obtain the complete plaintext/ciphertext. +### update + +update(data: DataBlob): Promise\ -> **NOTE** -> - In symmetric encryption or decryption, calling **doFinal()** means the end of an encryption or decryption process, and the [Cipher](#cipher) instance state will be cleared. To start a new encryption or decryption operation, you must call [init()](#init-2) to pass in a complete parameter list for initialization.
For example, if the same symmetric key is used for a **Cipher** instance to perform encryption and then decryption. After the encryption is complete, the **params** in **init** for decryption must be set instead of being **null**. -> - If a decryption operation fails, check whether the data to be encrypted and decrypted matches the parameters in **[init](#init-2)**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption. -> - The result of **doFinal()** may be **null**. To avoid exceptions, determine whether the result is **null** before using the **.data** field to access the **doFinal()** result. -> - For details about the sample code for calling **doFinal()** multiple times during RSA asymmetric encryption and decryption, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting-data). +Updates the data to be signed. This API uses a promise to return the result.
This API can be called only after the [Sign](#sign) instance is initialized by using [init()](#init-3). + +> **NOTE** +> +> **update()** may be called multiple times or may not be called (call [sign](#sign-2) after [init](#init-3)), depending on the size of the data.
+> The algorithm library does not set a limit on the amount of data to be updated (once or accumulatively). If a large amount of data needs to be signed, you are advised to use **update()** multiple times to pass in data. This can prevent too much memory from being requested at a time.
+> For details about the sample code for calling **update()** multiple times, see [Signing and Signature verification](../../security/cryptoFramework-guidelines.md#signing-and-signature-verification). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | -| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It can be **null** in symmetric encryption or decryption, but cannot be {data:Uint8Array(null)}. | -| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. If the data is successfully encrypted or decrypted, **err** is **undefined**, and **data** is the **DataBlob** (encryption or decryption result of the remaining data). Otherwise, **err** is an error object.| +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ---------- | +| data | [DataBlob](#datablob) | Yes | Data to pass in.| + +**Return value** + +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise that returns no value.| **Error codes** -| ID| Error Message | -| -------- | ----------------------- | -| 17620001 | memory error. | +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | | 17620002 | runtime error. | | 17630001 | crypto operation error. | -**Example** +### sign -```js -import cryptoFramework from '@ohos.security.cryptoFramework'; +sign(data: DataBlob, callback: AsyncCallback\): void -let cipher; // The process of creating a Cipher instance is omitted here. -let data; // The process of preparing the data to encrypt or decrypt is omitted here. -// The init() and update() processes are omitted here. -cipher.doFinal(data, (err, output) => { - if (err) { - console.error(`Failed to finalize cipher, ${err.code}, ${err.message}`); - } else { - console.info(`Finalize cipher success`); - if (output != null) { - // Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag). - } - } -}) -``` +Signs the data. This API uses an asynchronous callback to return the result. -### doFinal +**System capability**: SystemCapability.Security.CryptoFramework -doFinal(data : DataBlob) : Promise\ +**Parameters** -(1) Encrypts or decrypts the remaining data (generated by the block ciper mode) and the data passed in by **doFinal()** to finalize the symmetric encryption or decryption. This API uses a promise to return the encrypted or decrypted data.
If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in data without using **update()**. If all the data has been passed in by [update()](#update-4), you can pass in **null** in **data** of **doFinal()**. +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| data | [DataBlob](#datablob) | Yes | Data to pass in.| +| callback | AsyncCallback\<[DataBlob](#datablob) > | Yes | Callback invoked to return the result. | -The output of **doFinal()** varies with the symmetric encryption/decryption mode in use. +**Error codes** -- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **null** is passed in by **data** of **doFinal()**, the result of **doFinal()** is **authTag**.
**authTag** must be [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) used for decryption. The ciphertext is the **data** passed in for decryption. -- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext. +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | -(2) Encrypts or decrypts the input data for RSA asymmetric encryption/decryption. This API uses a promise to return the result. If a large amount of data needs to be encrypted/decrypted, call **doFinal()** multiple times and concatenate the result of each **doFinal()** to obtain the complete plaintext/ciphertext. +### sign -> **NOTE** -> - In symmetric encryption or decryption, calling **doFinal()** means the end of an encryption or decryption process, and the [Cipher](#cipher) instance state will be cleared. To start a new encryption or decryption operation, you must call [init()](#init-2) to pass in a complete parameter list for initialization.
For example, if the same symmetric key is used for a **Cipher** instance to perform encryption and then decryption. After the encryption is complete, the **params** in **init** for decryption must be set instead of being **null**. -> - If a decryption fails, check whether the data to be encrypted and decrypted matches the parameters in **[init](#init-2)**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption. -> - The result of **doFinal()** may be **null**. To avoid exceptions, determine whether the result is **null** before using the **.data** field to access the **doFinal()** result. -> - For details about the sample code for calling **doFinal()** multiple times during RSA asymmetric encryption and decryption, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting-data). +sign(data: DataBlob): Promise\ + +Signs the data. This API uses a promise to return the result. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ---- | --------------------- | ---- | -------------------- | -| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It can be **null**, but cannot be {data:Uint8Array(null)}.| +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ---------- | +| data | [DataBlob](#datablob) | Yes | Data to pass in.| **Return value** -| Type | Description | -| ------------------------------- | ------------------------------------------------ | -| Promise\<[DataBlob](#datablob)> | Promise used to return the **DataBlob**, which is the encryption or decryption result of the remaining data.| +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise that returns no value.| **Error codes** -| ID| Error Message | -| -------- | -------------------------------------------- | -| 17620001 | memory error. | -| 17620002 | runtime error. | -| 17630001 | crypto operation error. | +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | -**Example** +**Callback example**: ```js -import cryptoFramework from '@ohos.security.cryptoFramework'; - -let cipher; // The process of creating a Cipher instance is omitted here. -let data; // The process of preparing the data to encrypt or decrypt is omitted here. -// The init() and update() processes are omitted here. -cipher.doFinal(data) -.then(output => { - console.info(`Finalize cipher success`); - if (output != null) { - // Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag). - } -}, error => { - console.error(`Failed to finalize cipher, ${error.code}, ${error.message}`); -}) -``` - -**RSA encryption example (callback)** - -```javascript import cryptoFramework from "@ohos.security.cryptoFramework" function stringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { + var arr = []; + for (var i = 0, j = str.length; i < j; ++i) { arr.push(str.charCodeAt(i)); } - return new Uint8Array(arr); + var tmpArray = new Uint8Array(arr); + return tmpArray; } -let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); -let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); -rsaGenerator.generateKeyPair(function (err, keyPair) { - let pubKey = keyPair.pubKey; - cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null, function (err, data) { - let plainText = "this is cipher text"; - let input = {data : stringToUint8Array(plainText) }; - cipher.doFinal(input, function (err, data) { - AlertDialog.show({ message : "EncryptOutPut is " + data.data} ); +let globalKeyPair; +let SignMessageBlob; +let plan1 = "This is Sign test plan1"; // The first segment of the data. +let plan2 = "This is Sign test plan2"; // The second segment of the data. +let input1 = { data: stringToUint8Array(plan1) }; +let input2 = { data: stringToUint8Array(plan2) }; + +function signMessageCallback() { + let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); + let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); + rsaGenerator.generateKeyPair(function (err, keyPair) { + globalKeyPair = keyPair; + let priKey = globalKeyPair.priKey; + signer.init(priKey, function (err, data) { + signer.update(input1, function (err, data) { // Add the first segment of the data. + signer.sign(input2, function (err, data) { // Add the second segment of the data, and sign input1 and input2. + SignMessageBlob = data; + AlertDialog.show({message: "res" + SignMessageBlob.data}); + }); + }); }); }); -}); +} ``` -**RSA encryption example (promise)** +**Promise example**: -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" function stringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { + var arr = []; + for (var i = 0, j = str.length; i < j; ++i) { arr.push(str.charCodeAt(i)); } - return new Uint8Array(arr); + var tmpArray = new Uint8Array(arr); + return tmpArray; } -let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); -let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); -let keyGenPromise = rsaGenerator.generateKeyPair(); -keyGenPromise.then(rsaKeyPair => { - let pubKey = rsaKeyPair.pubKey; - return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null); // Pass in the private key and DECRYPT_MODE to initialize the decryption mode. -}).then(() => { - let plainText = "this is cipher text"; - let input = { data : stringToUint8Array(plainText) }; - return cipher.doFinal(input); -}).then(dataBlob => { - console.info("EncryptOutPut is " + dataBlob.data); -}); -``` - -> **NOTE**
-> For more encryption and decryption examples, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting data). +let globalKeyPair; +let SignMessageBlob; +let plan1 = "This is Sign test plan1"; // The first segment of the data. +let plan2 = "This is Sign test plan2"; // The second segment of the data. +let input1 = { data: stringToUint8Array(plan1) }; +let input2 = { data: stringToUint8Array(plan2) }; -## cryptoFramework.createSign +function signMessagePromise() { + let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); + let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); + let keyGenPromise = rsaGenerator.generateKeyPair(); + keyGenPromise.then( keyPair => { + globalKeyPair = keyPair; + let priKey = globalKeyPair.priKey; + return signer.init(priKey); + }).then(() => { + return signer.update(input1); // Add the first segment of the data. + }).then(() => { + return signer.sign(input2); // Add the second segment of the data, and sign input1 and input2. + }).then(dataBlob => { + SignMessageBlob = dataBlob; + console.info("sign output is " + SignMessageBlob.data); + AlertDialog.show({message: "output" + SignMessageBlob.data}); + }); +} +``` -createSign(algName : string) : Sign +### setSignSpec10+ -Creates a **Sign** instance. +setSignSpec(itemType: SignSpecItem, itemValue: number): void -For details about the supported specifications, see [Signing and Signature Verification Specifications](../../security/cryptoFramework-overview.md#signing-and-signature-verification-specifications). +Sets signing specifications. You can use this API to set signing parameters that cannot be set by [createSign](#cryptoframeworkcreatesign). Currently, only the RSA is supported. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------------------------------------------------------ | -| algName | string | Yes | Signing algorithm to use, which can be RSA or ECC. If RSA PKCS #1 is used, the digest must be set. If RSA PSS is used, the digest and mask digest must be set.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| itemType | [SignSpecItem](#signspecitem10) | Yes | Signing parameter to set.| +| itemValue | number | Yes | Value of the signing parameter to set.| -**Return value** +**Error codes** -| Type| Description | -| ---- | -------------------------------- | -| Sign | **Sign** instance created.| +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | **Example** -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" -let signer1 = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); - -let singer2 = cryptoFramework.createSign("RSA1024|PSS|SHA256|MGF1_SHA256") +let signer; // The process of generating the Sign instance is omitted here. +let setN = 20; +signer.setSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, setN); ``` -## Sign - -Provides APIs for signing. Before using any API of the **Sign** class, you must create a **Sign** instance by using **createSign()**. The **Sign** class does not support repeated initialization. When a new key is used for signing, you must create a new **Sign** object and call **init()** for initialization. - -The signing mode is determined in **createSign()**, and the key is set by **init()**. - -If the data to be signed is short, you can use **sign()** to pass in the data for signing after **init()**. - -If the data to be signed is long, you can use **update()** to pass in the data by segment, and then use **sign()** to sign the entire data. +### getSignSpec10+ -If **update()** is used to pass in data by segment, **data** of **sign()** can be **null**. +getSignSpec(itemType: SignSpecItem): string | number -### Attributes +Obtains signing specifications. Currently, only the RSA is supported. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------------- | -| algName | string | Yes | No | Algorithm to use.| - -### init - -init(priKey : PriKey, callback : AsyncCallback\) : void - -Initializes a **Sign** instance using a private key. This API uses an asynchronous callback to return the result. The **Sign** class does not support repeated calling of **init()**. +**Parameters** -**System capability**: SystemCapability.Security.CryptoFramework +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ---------- | +| itemType | [SignSpecItem](#signspecitem) | Yes | Signing parameter to obtain.| -**Parameters** +**Return value** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------------- | -| priKey | [PriKey](#prikey) | Yes | Private key used for the initialization.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | +| Type | Description | +| -------------- | ----------- | +| string\|number | Returns the value of the signing parameter obtained.| **Error codes** | ID| Error Message | | -------- | ---------------------- | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | | 17620001 | memory error. | -| 17620002 | runtime error. | | 17630001 | crypto operation error. | -### init +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +let signer; // The process of generating the Sign instance is omitted here. +let saltLen = signer.getSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM); +``` + +## cryptoFramework.createVerify -init(priKey : PriKey) : Promise\ +createVerify(algName: string): Verify -Initializes a **Sign** instance using a private key. This API uses a promise to return the result. The **Sign** class does not support repeated calling of **init()**. +Creates a **Verify** instance.
For details about the supported specifications, see [Signing and Signature Verification Specifications](../../security/cryptoFramework-overview.md#signing-and-signature-verification-specifications). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ---------------- | -| priKey | [PriKey](#prikey) | Yes | Private key used for the initialization.| +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------------------------------------ | +| algName | string | Yes | Signing algorithm, which can be RSA, ECC, or DSA.
If the RSA PKCS1 mode is used, you need to set the digest. If the RSA PSS mode is used, you need to set the digest and mask digest.| **Return value** -| Type | Description | -| -------------- | ----------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| ------ | ------------------------------------ | +| Verify | Returns the **Verify** instance created.| **Error codes** | ID| Error Message | | -------- | ---------------------- | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | | 17620001 | memory error. | -| 17620002 | runtime error. | -| 17630001 | crypto operation error. | -### update +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +let verifyer1 = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256"); + +let verifyer2 = cryptoFramework.createVerify("RSA1024|PSS|SHA256|MGF1_SHA256") +``` + +## Verify + +Provides APIs for signature verification. Before using any API of the **Verify** class, you must create a **Verify** instance by using **createVerify(algName: string): Verify**. Invoke **init()**, **update()**, and **sign()** in this class in sequence to complete the signature verification. For details about the sample code, see [Signing and Signature Verification](../../security/cryptoFramework-guidelines.md#signing-and-signature-verification). + +The **Verify** class does not support repeated initialization. When a new key is used for signature verification, you must create a new **Verify** object and call **init()** for initialization. + +The signature verification mode is determined in **createVerify()**, and key is set by **init()**. + +If the signed message is short, you can call **verify()** to pass in the signed message and signature (**signatureData**) for signature verification after **init()**. That is, you do not need to use **update()**. + +If the signed message is too long, you can call **update()** multiple times to pass in the signed message by segment, and then call **verify()** to verify the full text of the message. The **data** parameter of **verify()** can be null. The service can call **update()** multiple times in the loop. When the loop ends, the service calls **verify()** to pass in the signature (**signatureData**) for signature verification. + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| algName | string | Yes | No | Algorithm to be used for signature verification.| -update(data : DataBlob, callback : AsyncCallback\) : void +### init -Updates the data to be signed. This API uses an asynchronous callback to return the result. +init(pubKey: PubKey, callback: AsyncCallback\): void -> **NOTE**
-> For details about the sample code for calling **update()** multiple times, see [Generating and Verifying a Signature](../../security/cryptoFramework-guidelines.md#generating-and-verifying-a-signature). +Initializes the **Verify** instance using a public key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------- | -| data | [DataBlob](#datablob)| Yes | Data to pass in.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------ | +| pubKey | [PubKey](#pubkey) | Yes | Public key used to initialize the **Verify** instance.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | **Error codes** | ID| Error Message | | -------- | ---------------------- | +| 401 | invalid parameters. | | 17620001 | memory error. | | 17620002 | runtime error. | | 17630001 | crypto operation error. | -### update - -update(data : DataBlob) : Promise\; +### init -Updates the data to be signed. This API uses a promise to return the result. +init(pubKey: PubKey): Promise\ -> **NOTE**
-> For details about the sample code for calling **update()** multiple times, see [Generating and Verifying a Signature](../../security/cryptoFramework-guidelines.md#generating-and-verifying-a-signature). +Initializes the **Verify** instance using a public key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ------ | -------- | ---- | ---------- | -| data | [DataBlob](#datablob) | Yes | Data to pass in.| +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------------------------- | +| pubKey | [PubKey](#pubkey) | Yes | Public key used to initialize the **Verify** instance.| **Return value** -| Type | Description | -| -------------- | ----------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise that returns no value.| **Error codes** | ID| Error Message | | -------- | ---------------------- | +| 401 | invalid parameters. | | 17620001 | memory error. | | 17620002 | runtime error. | | 17630001 | crypto operation error. | -### sign +### update -sign(data : DataBlob, callback : AsyncCallback\) : void +update(data: DataBlob, callback: AsyncCallback\): void -Signs the data. This API uses an asynchronous callback to return the result. +Updates the data for signature verification. This API uses an asynchronous callback to return the result.
This API can be called only after the [Verify](#verify) instance is initialized using [init()](#init-4). + +> **NOTE** +> +> **update()** may be called multiple times or may not be called (call [verify](#verify-1) after [init](#init-4)), depending on the size of the data.
+> The algorithm library does not set a limit on the amount of data to be updated (once or accumulatively). If a large amount of data is involved in signature verification, you are advised to use **update()** multiple times to pass in data. This can prevent too much memory from being requested at a time.
+> For details about the sample code for calling **update()** multiple times, see [Signing and Signature verification](../../security/cryptoFramework-guidelines.md#signing-and-signature-verification). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------- | -| data | [DataBlob](#datablob) | Yes | Data to pass in.| -| callback | AsyncCallback\<[DataBlob](#datablob) > | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------ | +| data | [DataBlob](#datablob) | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | **Error codes** | ID| Error Message | | -------- | ---------------------- | +| 401 | invalid parameters. | | 17620001 | memory error. | | 17620002 | runtime error. | | 17630001 | crypto operation error. | -### sign +### update -sign(data : DataBlob) : Promise\ +update(data: DataBlob): Promise\ -Signs the data. This API uses a promise to return the result. +Updates the data for signature verification. This API uses a promise to return the result.
This API can be called only after the [Verify](#verify) instance is initialized using [init()](#init-5). + +> **NOTE** +> +> **update()** may be called multiple times or may not be called (call [verify](#verify-2) after [init](#init-5)), depending on the size of the data.
+> The algorithm library does not set a limit on the amount of data to be updated (once or accumulatively). If a large amount of data is involved in signature verification, you are advised to use **update()** multiple times to pass in data. This can prevent too much memory from being requested at a time.
+> For details about the sample code for calling **update()** multiple times, see [Signing and Signature verification](../../security/cryptoFramework-guidelines.md#signing-and-signature-verification). **System capability**: SystemCapability.Security.CryptoFramework @@ -2263,237 +2359,833 @@ Signs the data. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | ----------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise that returns no value.| **Error codes** | ID| Error Message | | -------- | ---------------------- | +| 401 | invalid parameters. | | 17620001 | memory error. | | 17620002 | runtime error. | | 17630001 | crypto operation error. | -**Callback example**: - -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" - -function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - var tmpArray = new Uint8Array(arr); - return tmpArray; -} +### verify -let globalKeyPair; -let SignMessageBlob; -let plan1 = "This is Sign test plan1"; // The first segment of the data. -let plan2 = "This is Sign test plan2"; // The second segment of the data. -let input1 = { data : stringToUint8Array(plan1) }; -let input2 = { data : stringToUint8Array(plan2) }; +verify(data: DataBlob, signatureData: DataBlob, callback: AsyncCallback\): void -function signMessageCallback() { - let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); - let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); - rsaGenerator.generateKeyPair(function (err, keyPair) { - globalKeyPair = keyPair; - let priKey = globalKeyPair.priKey; - signer.init(priKey, function (err, data) { - signer.update(input1, function (err, data) { // Add the first segment of the data. - signer.sign(input2, function (err, data) { // Add the second segment of the data, and sign input1 and input2. - SignMessageBlob = data; - AlertDialog.show({message : "res" + SignMessageBlob.data}); - }); - }); - }); - }); -} -``` +Verifies the signature. This API uses an asynchronous callback to return the result. -**Promise example**: +**System capability**: SystemCapability.Security.CryptoFramework -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +**Parameters** -function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - var tmpArray = new Uint8Array(arr); - return tmpArray; -} +| Name | Type | Mandatory| Description | +| ------------- | -------------------- | ---- | ---------- | +| data | [DataBlob](#datablob) | Yes | Data to pass in.| +| signatureData | [DataBlob](#datablob) | Yes | Signature data. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | -let globalKeyPair; -let SignMessageBlob; -let plan1 = "This is Sign test plan1"; // The first segment of the data. -let plan2 = "This is Sign test plan2"; // The second segment of the data. -let input1 = { data : stringToUint8Array(plan1) }; -let input2 = { data : stringToUint8Array(plan2) }; +**Error codes** -function signMessagePromise() { - let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); - let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); - let keyGenPromise = rsaGenerator.generateKeyPair(); - keyGenPromise.then( keyPair => { - globalKeyPair = keyPair; - let priKey = globalKeyPair.priKey; - return signer.init(priKey); - }).then(() => { - return signer.update(input1); // Add the first segment of the data. - }).then(() => { - return signer.sign(input2); // Add the second segment of the data, and sign input1 and input2. - }).then(dataBlob => { - SignMessageBlob = dataBlob; - console.info("sign output is " + SignMessageBlob.data); - AlertDialog.show({message : "output" + SignMessageBlob.data}); - }); -} -``` +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | -## cryptoFramework.createVerify +### verify -createVerify(algName : string) : Verify +verify(data: DataBlob, signatureData: DataBlob): Promise\ -Creates a **Verify** instance. For details about the supported specifications, see [Signing and Signature Verification Specifications](../../security/cryptoFramework-overview.md#signing-and-signature-verification-specifications). +Verifies the signature. This API uses a promise to return the result. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------------------------------------------------------ | -| algName | string | Yes | Signing algorithm to use, which can be RSA or ECC. If RSA PKCS #1 is used, the digest must be set. If RSA PSS is used, the digest and mask digest must be set.| +| Name | Type | Mandatory| Description | +| ------------- | -------- | ---- | ---------- | +| data | [DataBlob](#datablob) | Yes | Data to pass in.| +| signatureData | [DataBlob](#datablob) | Yes | Signature data. | **Return value** -| Type | Description | -| ------ | ---------------------------------- | -| Verify | **Verify** instance created.| - -**Example** - -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" - -let verifyer1 = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256"); - -let verifyer2 = cryptoFramework.createVerify("RSA1024|PSS|SHA256|MGF1_SHA256") -``` - -## Verify - -Provides APIs for signature verification. Before using any API of the **Verify** class, you must create a **Verify** instance by using **createVerify()**. - -The **Verify** class does not support repeated initialization. When a new key is used for signature verification, you must create a new **Verify** object and call **init()** for initialization. +| Type | Description | +| ----------------- | ------------------------------ | +| Promise\ | Promise used to return the result.| -The signature verification mode is determined in **createVerify()**, and key is set by **init()**. +**Error codes** -If the signature data to be verified is short, you can call **verify()** to pass in the signature data and original data after **init()**. +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | -If the signature data to be verified is long, you can use **update()** to pass in the data by segment, and then use **verify()** to verify the entire data. +**Callback example**: -If **update()** is used to pass in data by segment, **data** of **verify()** can be **null**. +```js +import cryptoFramework from "@ohos.security.cryptoFramework" -### Attributes +let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. +let input1 = null; +let input2 = null; +let signMessageBlob = null; // Signed data, which is omitted here. +let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA25"); +verifyer.init(globalKeyPair.pubKey, function (err, data) { + verifyer.update(input1, function(err, data) { + verifyer.verify(input2, signMessageBlob, function(err, data) { + console.info("verify result is " + data); + }) + }); +}) +``` -**System capability**: SystemCapability.Security.CryptoFramework +**Promise example**: -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------------- | -| algName | string | Yes | No | Algorithm to be used for signature verification.| +```js +import cryptoFramework from "@ohos.security.cryptoFramework" +let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. +let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256"); +let verifyInitPromise = verifyer.init(globalKeyPair.pubKey); +let input1 = null; +let input2 = null; +let signMessageBlob = null; // Signed data, which is omitted here. +verifyInitPromise.then(() => { + return verifyer.update(input1); +}).then(() => { + return verifyer.verify(input2, signMessageBlob); +}).then(res => { + console.log("Verify result is " + res); +}); +``` +### setVerifySpec10+ -### init +setVerifySpec(itemType: SignSpecItem, itemValue: number): void -init(pubKey : PubKey, callback : AsyncCallback\) : void +Set signature verification specifications. You can use this API to set signature verification parameters that cannot be set by [createVerify](#cryptoframeworkcreateverify). Currently, only the RSA is supported. -Initializes the **Verify** instance using a public key. This API uses an asynchronous callback to return the result. +The parameters for signature verification must be the same as those for signing. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------------------------- | -| pubKey | [PubKey](#pubkey) | Yes | Public key used for the initialization.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| itemType | [SignSpecItem](#signspecitem10) | Yes | Signature verification parameter to set.| +| itemValue | number | Yes | Value of the signature verification parameter to set.| **Error codes** | ID| Error Message | | -------- | ---------------------- | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | | 17620001 | memory error. | -| 17620002 | runtime error. | | 17630001 | crypto operation error. | -### init +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" -init(pubKey : PubKey) : Promise\ +let verifyer; //The process of generating the Verify instance is omitted here. +let setN = 20; +verifyer.setVerifySpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, setN); +``` -Initializes the **Verify** instance using a public key. This API uses a promise to return the result. +### getVerifySpec10+ + +getVerifySpec(itemType: SignSpecItem): string | number + +Obtains signature verification specifications. Currently, only the RSA is supported. + +The parameters for signature verification must be the same as those for signing. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ---------------------------- | -| pubKey | [PubKey](#pubkey) | Yes | Public key used for the initialization.| +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ---------- | +| itemType | [SignSpecItem](#signspecitem10) | Yes | Signature verification parameter to obtain.| **Return value** | Type | Description | | -------------- | ----------- | -| Promise\ | Promise used to return the result.| +| string\|number | Returns the value of the parameter obtained.| **Error codes** | ID| Error Message | | -------- | ---------------------- | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | | 17620001 | memory error. | -| 17620002 | runtime error. | | 17630001 | crypto operation error. | -### update +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" -update(data : DataBlob, callback : AsyncCallback\) : void +let verifyer; //The process of generating the Verify instance is omitted here. +let saltLen = verifyer.getSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM); +``` -Updates the data for signature verification. This API uses an asynchronous callback to return the result. +## cryptoFramework.createKeyAgreement -> **NOTE** -> For details about the sample code for calling **update()** multiple times, see [Generating and Verifying a Signature](../../security/cryptoFramework-guidelines.md#generating-and-verifying-a-signature). +createKeyAgreement(algName: string): KeyAgreement + +Creates a **KeyAgreement** instance.
For details about the supported specifications, see [Key Agreement Specifications](../../security/cryptoFramework-overview.md#key-agreement-specifications). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------- | -| data | [DataBlob](#datablob)| Yes | Data to pass in.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | --------------------------------- | +| algName | string | Yes | Key agreement algorithm to use. Currently, only the ECC is supported.| -**Error codes** +**Return value** + +| Type | Description | +| ------------ | ------------------------------------------ | +| KeyAgreement | Returns the **KeyAgreement** instance created.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | +| 17620001 | memory error. | + +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); + +``` + +## KeyAgreement + +Provides APIs for key agreement operations. Before using any API of the **KeyAgreement** class, you must create a **KeyAgreement** instance by using **createKeyAgreement(algName: string): KeyAgreement**. + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| algName | string | Yes | No | Algorithm used for key agreement.| + +### generateSecret + +generateSecret(priKey: PriKey, pubKey: PubKey, callback: AsyncCallback\): void + +Generates a shared secret. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.CryptoFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ---------------------- | +| priKey | [PriKey](#prikey) | Yes | Private key used for key agreement.| +| pubKey | [PubKey](#pubkey) | Yes | Public key used for key agreement.| +| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the shared secret.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | + +### generateSecret + +generateSecret(priKey: PriKey, pubKey: PubKey): Promise\ + +Generates a shared secret. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.CryptoFramework + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| priKey | [PriKey](#prikey) | Yes | Private key used for key agreement.| +| pubKey | [PubKey](#pubkey) | Yes | Public key used for key agreement.| + +**Return value** + +| Type | Description | +| ------------------ | -------- | +| Promise\<[DataBlob](#datablob)> | Promise used to return the shared secret.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | + +**Callback example**: + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. +let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); +keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey, function (err, secret) { + if (err) { + console.error("keyAgreement error."); + return; + } + console.info("keyAgreement output is " + secret.data); +}); +``` + +**Promise example**: + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. +let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); +let keyAgreementPromise = keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey); +keyAgreementPromise.then((secret) => { + console.info("keyAgreement output is " + secret.data); +}).catch((error) => { + console.error("keyAgreement error."); +}); +``` + +## cryptoFramework.createMd + +createMd(algName: string): Md + +Creates an **Md** instance for message digest operations.
For details about the supported specifications, see [MD Algorithm Specifications](../../security/cryptoFramework-overview.md#md-algorithm-specifications). + +**System capability**: SystemCapability.Security.CryptoFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------------------------------------ | +| algName | string | Yes | Digest algorithm. For details about the supported algorithms, see [MD Algorithm Specifications](../../security/cryptoFramework-overview.md#md-algorithm-specifications).| + +**Return value** + +| Type| Description | +| ---- | --------------------------------------- | +| Md | Returns the [Md](#md) instance created.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------ | +| 401 | invalid parameters. | +| 17620001 | memory error. | + +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var md; +try { + // Set algName based on the algorithm supported. + md = cryptoFramework.createMd("SHA256"); +} catch (error) { + console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); +} +``` + +## Md + +Provides APIs for message digest operations. Before using any API of the **Md** class, you must create an **Md** instance by using [createMd](#cryptoframeworkcreatemd). + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------- | +| algName | string | Yes | No | Digest algorithm.| + +### update + +update(input: DataBlob, callback: AsyncCallback\): void + +Updates the message digest data. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> For details about the sample code for calling **update()** multiple times, see [Generating a Digest](../../security/cryptoFramework-guidelines.md#generating-a-digest). + +**System capability**: SystemCapability.Security.CryptoFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------ | +| input | [DataBlob](#datablob) | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17630001 | crypto operation error. | + +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var md; +try { + md = cryptoFramework.createMd("SHA256"); +} catch (error) { + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +} +console.error("Md algName is: " + md.algName); + +let blob; +md.update(blob, (err,) => { + if (err) { + console.error("[Callback] err: " + err.code); + } +}); +``` + +### update + +update(input: DataBlob): Promise\ + +Updates the message digest data. This API uses a promise to return the result. + +> **NOTE** +> +> For details about the sample code for calling **update()** multiple times, see [Generating a Digest](../../security/cryptoFramework-guidelines.md#generating-a-digest). + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ------------ | +| input | DataBlob | Yes | Data to pass in.| + +**Return value** + +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise that returns no value.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17630001 | crypto operation error. | + +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var md; +try { + md = cryptoFramework.createMd("SHA256"); +} catch (error) { + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +} +console.error("Md algName is: " + md.algName); + +let blob; +var promiseMdUpdate = md.update(blob); +promiseMdUpdate.then(() => { + // do something +}).catch(error => { + console.error("[Promise]: error: " + error.message); +}); +``` + +### digest + +digest(callback: AsyncCallback\): void + +Generates a message digest. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | + +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var md; +try { + md = cryptoFramework.createMd("SHA256"); +} catch (error) { + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +} +console.error("Md algName is: " + md.algName); + +let blob; +md.update(blob, (err,) => { + if (err) { + console.error("[Callback] err: " + err.code); + } + md.digest((err1, mdOutput) => { + if (err1) { + console.error("[Callback] err: " + err1.code); + } else { + console.error("[Callback]: MD result: " + mdOutput); + } + }); +}); +``` + +### digest + +digest(): Promise\ + +Generates a message digest. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.CryptoFramework + +**Return value** + +| Type | Description | +| ------------------ | ----------- | +| Promise\<[DataBlob](#datablob)> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | + +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var md; +try { + md = cryptoFramework.createMd("SHA256"); +} catch (error) { + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +} +console.error("Md algName is: " + md.algName); + +let blob; +var promiseMdUpdate = md.update(blob); +promiseMdUpdate.then(() => { + var PromiseMdDigest = md.digest(); + return PromiseMdDigest; +}).then(mdOutput => { + console.error("[Promise]: MD result: " + mdOutput.data); +}).catch(error => { + console.error("[Promise]: error: " + error.message); +}); +``` + +### getMdLength + +getMdLength(): number + +Obtains the message digest length, in bytes. + +**System capability**: SystemCapability.Security.CryptoFramework + +**Return value** + +| Type | Description | +| ------ | -------------------------- | +| number | Returns the length of the message digest obtained.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error. | + +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var md; +try { + md = cryptoFramework.createMd("SHA256"); +} catch (error) { + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +} +console.error("Md algName is: " + md.algName); + +let blob; +var promiseMdUpdate = md.update(blob); +promiseMdUpdate.then(() => { + var PromiseMdDigest = md.digest(); + return PromiseMdDigest; +}).then(mdOutput => { + console.error("[Promise]: MD result: " + mdOutput.data); + let mdLen = md.getMdLength(); + console.error("MD len: " + mdLen); +}).catch(error => { + console.error("[Promise]: error: " + error.message); +}); +``` + +## cryptoFramework.createMac + +createMac(algName: string): Mac + +Creates a **Mac** instance for message authentication code (MAC) operations. For details about the supported specifications, see [HMAC Algorithm Specifications](../../security/cryptoFramework-overview.md#hmac-algorithm-specifications). + +**System capability**: SystemCapability.Security.CryptoFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------------------------------------ | +| algName | string | Yes | Digest algorithm. For details about the supported algorithms, see [HMAC Algorithm Specifications](../../security/cryptoFramework-overview.md#hmac-algorithm-specifications).| + +**Return value** + +| Type| Description | +| ---- | ----------------------------------------- | +| Mac | Returns the [Mac](#mac) instance created.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------ | +| 401 | invalid parameters. | +| 17620001 | memory error. | + +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var mac; +try { + // Set algName based on the algorithm supported. + mac = cryptoFramework.createMac("SHA256"); +} catch (error) { + console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); +} +``` + +## Mac + +Provides APIs for MAC operations. Before using any API of the **Mac** class, you must create a **Mac** instance by using [createMac](#cryptoframeworkcreatemac). + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------- | +| algName | string | Yes | No | Digest algorithm.| + +### init + +init(key: SymKey, callback: AsyncCallback\): void + +Initializes the MAC computation using a symmetric key. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.CryptoFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------- | +| key | [SymKey](#symkey) | Yes | Shared symmetric key.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17630001 | crypto operation error. | + +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var mac; +try { + mac = cryptoFramework.createMac("SHA256"); +} catch (error) { + console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); +} +var KeyBlob; +var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); +symKeyGenerator.convertKey(KeyBlob, (err, symKey) => { + if (err) { + console.error("[Callback] err: " + err.code); + } + mac.init(symKey, (err1, ) => { + if (err1) { + console.error("[Callback] err: " + err1.code); + } + }); +}); +``` + +### init + +init(key: SymKey): Promise\ + +Initializes the MAC computation using a symmetric key. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.CryptoFramework + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------ | +| key | [SymKey](#symkey) | Yes | Shared symmetric key.| + +**Return value** + +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise that returns no value.| + +**Error codes** | ID| Error Message | | -------- | ---------------------- | -| 17620001 | memory error. | -| 17620002 | runtime error. | +| 401 | invalid parameters. | +| 17630001 | crypto operation error. | + +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var mac; +try { + mac = cryptoFramework.createMac("SHA256"); +} catch (error) { + console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); +} +console.error("Mac algName is: " + mac.algName); + +var KeyBlob; +var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); +var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); +promiseConvertKey.then(symKey => { + var promiseMacInit = mac.init(symKey); + return promiseMacInit; +}).catch(error => { + console.error("[Promise]: error: " + error.message); +}); + +``` + +### update + +update(input: DataBlob, callback: AsyncCallback\): void + +Updates the MAC computation data. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> For details about the sample code for calling **update()** multiple times, see [Generating a MAC](../../security/cryptoFramework-guidelines.md#generating-a-mac). + +**System capability**: SystemCapability.Security.CryptoFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------ | +| input | [DataBlob](#datablob) | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | | 17630001 | crypto operation error. | +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var KeyBlob; +var mac; +try { + mac = cryptoFramework.createMac("SHA256"); +} catch (error) { + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +} +var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); +symKeyGenerator.convertKey(KeyBlob, (err, symKey) => { + if (err) { + console.error("[Callback] err: " + err.code); + } + mac.init(symKey, (err1, ) => { + if (err1) { + console.error("[Callback] err: " + err1.code); + } + let blob; + mac.update(blob, (err2, data) => { + if (err2) { + console.error("[Callback] err: " + err2.code); + } + }); + }); +}); +``` + ### update -update(data : DataBlob) : Promise\; +update(input: DataBlob): Promise\ -Updates the data for signature verification. This API uses a promise to return the result. +Updates the MAC computation data. This API uses a promise to return the result. > **NOTE** -> For details about the sample code for calling **update()** multiple times, see [Generating and Verifying a Signature](../../security/cryptoFramework-guidelines.md#generating-and-verifying-a-signature). +> +> For details about the sample code for calling **update()** multiple times, see [Generating a MAC](../../security/cryptoFramework-guidelines.md#generating-a-mac). **System capability**: SystemCapability.Security.CryptoFramework @@ -2501,237 +3193,445 @@ Updates the data for signature verification. This API uses a promise to return t | Name| Type | Mandatory| Description | | ------ | -------- | ---- | ---------- | -| data | [DataBlob](#datablob) | Yes | Data to pass in.| +| input | [DataBlob](#datablob) | Yes | Data to pass in.| **Return value** -| Type | Description | -| -------------- | ----------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise that returns no value.| **Error codes** | ID| Error Message | | -------- | ---------------------- | -| 17620001 | memory error. | -| 17620002 | runtime error. | +| 401 | invalid parameters. | +| 17630001 | crypto operation error. | + +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var mac; +try { + mac = cryptoFramework.createMac("SHA256"); +} catch (error) { + console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); +} +console.error("Mac algName is: " + mac.algName); + +var KeyBlob; +var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); +var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); +promiseConvertKey.then(symKey => { + var promiseMacInit = mac.init(symKey); + return promiseMacInit; +}).then(() => { + let blob; + var promiseMacUpdate = mac.update(blob); + return promiseMacUpdate; +}).catch(error => { + console.error("[Promise]: error: " + error.message); +}); + +``` + +### doFinal + +doFinal(callback: AsyncCallback\): void + +Finalizes the MAC computation. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.CryptoFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------- | +| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | + +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var KeyBlob; +var mac; +try { + mac = cryptoFramework.createMac("SHA256"); +} catch (error) { + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +} +var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); +symKeyGenerator.convertKey(KeyBlob, (err, symKey) => { + if (err) { + console.error("[Callback] err: " + err.code); + } + mac.init(symKey, (err1, ) => { + if (err1) { + console.error("[Callback] err: " + err1.code); + } + let blob; + mac.update(blob, (err2, ) => { + if (err2) { + console.error("[Callback] err: " + err2.code); + } + mac.doFinal((err3, macOutput) => { + if (err3) { + console.error("[Callback] err: " + err3.code); + } else { + console.error("[Promise]: HMAC result: " + macOutput); + } + }); + }); + }); +}); +``` + +### doFinal + +doFinal(): Promise\ + +Finalizes the MAC computation. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.CryptoFramework + +**Return value** + +| Type | Description | +| ------------------ | ----------- | +| Promise\<[DataBlob](#datablob)> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error. | | 17630001 | crypto operation error. | -### verify +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var mac; +try { + mac = cryptoFramework.createMac("SHA256"); +} catch (error) { + console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); +} +console.error("Mac algName is: " + mac.algName); + +var KeyBlob; +var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); +var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); +promiseConvertKey.then(symKey => { + var promiseMacInit = mac.init(symKey); + return promiseMacInit; +}).then(() => { + let blob; + var promiseMacUpdate = mac.update(blob); + return promiseMacUpdate; +}).then(() => { + var PromiseMacDoFinal = mac.doFinal(); + return PromiseMacDoFinal; +}).then(macOutput => { + console.error("[Promise]: HMAC result: " + macOutput.data); +}).catch(error => { + console.error("[Promise]: error: " + error.message); +}); +``` + +### getMacLength -verify(data : DataBlob, signatureData : DataBlob, callback : AsyncCallback\) : void +getMacLength(): number -Verifies a signature. This API uses an asynchronous callback to return the result. +Obtains the MAC length, in bytes. **System capability**: SystemCapability.Security.CryptoFramework -**Parameters** +**Return value** -| Name | Type | Mandatory| Description | -| ------------- | -------------------- | ---- | ---------- | -| data | [DataBlob](#datablob) | Yes | Data to pass in.| -| signatureData | [DataBlob](#datablob) | Yes | Signature data. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | +| Type | Description | +| ------ | --------------------------- | +| number | Returns the MAC length obtained.| **Error codes** | ID| Error Message | | -------- | ---------------------- | -| 17620001 | memory error. | -| 17620002 | runtime error. | | 17630001 | crypto operation error. | -### verify +**Example** -verify(data : DataBlob, signatureData : DataBlob) : Promise\ +```js +import cryptoFramework from "@ohos.security.cryptoFramework" -Verifies a signature. This API uses a promise to return the result. +var mac; +try { + mac = cryptoFramework.createMac("SHA256"); +} catch (error) { + console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); +} +console.error("Mac algName is: " + mac.algName); -**System capability**: SystemCapability.Security.CryptoFramework +var KeyBlob; +var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); +var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); +promiseConvertKey.then(symKey => { + var promiseMacInit = mac.init(symKey); + return promiseMacInit; +}).then(() => { + let blob; + var promiseMacUpdate = mac.update(blob); + return promiseMacUpdate; +}).then(() => { + var PromiseMacDoFinal = mac.doFinal(); + return PromiseMacDoFinal; +}).then(macOutput => { + console.error("[Promise]: HMAC result: " + macOutput.data); + let macLen = mac.getMacLength(); + console.error("MAC len: " + macLen); +}).catch(error => { + console.error("[Promise]: error: " + error.message); +}); +``` -**Parameters** +## cryptoFramework.createRandom -| Name | Type | Mandatory| Description | -| ------------- | -------- | ---- | ---------- | -| data | [DataBlob](#datablob) | Yes | Data to pass in.| -| signatureData | [DataBlob](#datablob) | Yes | Signature data. | +createRandom(): Random + +Creates a **Random** instance for generating random numbers and setting seeds.
For details about the supported specifications, see [Random Number](../../security/cryptoFramework-overview.md#random-number). + +**System capability**: SystemCapability.Security.CryptoFramework **Return value** -| Type | Description | -| ----------------- | ---------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| ------ | ----------------------------------------------- | +| Random | Returns the [Random](#random) instance created.| **Error codes** -| ID| Error Message | -| -------- | ---------------------- | -| 17620001 | memory error. | -| 17620002 | runtime error. | -| 17630001 | crypto operation error. | +| ID| Error Message | +| -------- | ------------ | +| 17620001 | memory error. | -**Callback example**: +**Example** -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" -let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. -let input1 = null; -let input2 = null; -let signMessageBlob = null; // Signed data, which is omitted here. -let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA25"); -verifyer.init(globalKeyPair.pubKey, function (err, data) { - verifyer.update(input1, function(err, data) { - verifyer.verify(input2, signMessageBlob, function(err, data) { - console.info("verify result is " + data); - }) - }); -}) +try { + var rand = cryptoFramework.createRandom(); +} catch (error) { + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +} ``` -**Promise example**: +## Random -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +Provides APIs for computing random numbers and setting seeds. Before using any API of the **Random** class, you must create a **Random** instance by using [createRandom](#cryptoframeworkcreaterandom). -let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. -let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256"); -let verifyInitPromise = verifyer.init(globalKeyPair.pubKey); -let input1 = null; -let input2 = null; -let signMessageBlob = null; // Signed data, which is omitted here. -verifyInitPromise.then(() => { - return verifyer.update(input1); -}).then(() => { - return verifyer.verify(input2, signMessageBlob); -}).then(res => { - console.log("Verify result is " + res); -}); -``` +### Attributes -## cryptoFramework.createKeyAgreement +**System capability**: SystemCapability.Security.CryptoFramework -createKeyAgreement(algName : string) : KeyAgreement +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | -------------------- | +| algName10+ | string | Yes | No | Algorithm used to generate the random number. Currently, only **CTR_DRBG** is supported.| + +### generateRandom -Creates a **KeyAgreement** instance. +generateRandom(len: number, callback: AsyncCallback\): void -For details about the supported specifications, see [Key Agreement Specifications](../../security/cryptoFramework-overview.md#key-agreement-specifications). +Generates a random number of the specified length. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------------------------- | -| algName | string | Yes | Key agreement algorithm to use. Only ECC is supported.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------- | +| len | number | Yes | Length of the random number to generate, in bytes. The value range is [1, INT_MAX].| +| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. | -**Return value** +**Error codes** -| Type | Description | -| ------------ | ---------------------------------------- | -| KeyAgreement | **KeyAgreement** instance created.| +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | **Example** -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" -let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); - +var rand; +try { + rand = cryptoFramework.createRandom(); +} catch (error) { + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +} +rand.generateRandom(12, (err, randData) => { + if (err) { + console.error("[Callback] err: " + err.code); + } else { + console.error("[Callback]: generate random result: " + randData.data); + } +}); ``` -## KeyAgreement +### generateRandom -Provides APIs for key agreement operations. Before using any API of the **KeyAgreement** class, you must create a **KeyAgreement** instance by using **createKeyAgreement()**. +generateRandom(len: number): Promise\ -### Attributes +Generates a random number of the specified length. This API uses a promise to return the result. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------------- | -| algName | string | Yes | No | Algorithm used for key agreement.| - -### generateSecret - -generateSecret(priKey : PriKey, pubKey : PubKey, callback : AsyncCallback\) : void - -Generates a shared secret. This API uses an asynchronous callback to return the result. +**Parameters** -**System capability**: SystemCapability.Security.CryptoFramework +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------ | +| len | number | Yes | Length of the random number to generate, in bytes. The value range is [1, INT_MAX].| -**Parameters** +**Return value** -| Name | Type | Mandatory| Description | -| -------- | ------------------------ | ---- | ---------------------- | -| priKey | [PriKey](#prikey) | Yes | Private key used for key agreement.| -| pubKey | [PubKey](#pubkey) | Yes | Public key used for key agreement.| -| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the shared secret.| +| Type | Description | +| ------------------ | ----------- | +| Promise\<[DataBlob](#datablob)> | Promise that returns no value.| **Error codes** | ID| Error Message | | -------- | ---------------------- | -| 17620001 | memory error. | -| 17620002 | runtime error. | +| 401 | invalid parameters. | +| 17620001 | memory error. | | 17630001 | crypto operation error. | -### generateSecret +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" -generateSecret(priKey : PriKey, pubKey : PubKey) : Promise\ +var rand; +try { + rand = cryptoFramework.createRandom(); +} catch (error) { + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +} -Generates a shared secret. This API uses a promise to return the result. +var promiseGenerateRand = rand.generateRandom(12); +promiseGenerateRand.then(randData => { + console.error("[Promise]: rand result: " + randData.data); +}).catch(error => { + console.error("[Promise]: error: " + error.message); +}); +``` + +### generateRandomSync10+ + +generateRandomSync(len: number): DataBlob + +Generates a random number of the specified length synchronously. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------------------- | -| priKey | [PriKey](#prikey) | Yes | Private key used for key agreement.| -| pubKey | [PubKey](#pubkey) | Yes | Public key used for key agreement.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------- | +| len | number | Yes | Length of the random number to generate, in bytes. The value range is [1, INT_MAX].| **Return value** -| Type | Description | -| ------------------ | -------- | -| Promise\<[DataBlob](#datablob)> | Promise used to return the shared secret.| +| Type | Description | +| ------------------ | ----------- | +|[DataBlob](#datablob) | Returns the generated random number.| **Error codes** | ID| Error Message | | -------- | ---------------------- | -| 17620001 | memory error. | -| 17620002 | runtime error. | +| 401 | invalid parameters. | +| 17620001 | memory error. | | 17630001 | crypto operation error. | -**Callback example**: +**Example** -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" -let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. -let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); -keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey, function (err, secret) { - if (err) { - console.error("keyAgreement error."); - return; +var rand; +try { + rand = cryptoFramework.createRandom(); +} catch (error) { + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +} + +try { + let randData = rand.generateRandomSync(12); + if (randData != null) { + console.info("[Sync]: rand result: " + randData.data); + } else { + console.error("[Sync]: get rand result fail!"); } - console.info("keyAgreement output is " + secret.data); -}); +} catch (error) { + console.error("[Sync]: error: " + error.message); +} ``` -**Promise example**: +### setSeed + +setSeed(seed: DataBlob): void + +Sets a seed. + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ------------ | +| seed | DataBlob | Yes | Seed to set.| + +**Error codes** -```javascript +| ID| Error Message | +| -------- | ----------------- | +| 17620001 | memory error. | + +**Example** + +```js import cryptoFramework from "@ohos.security.cryptoFramework" -let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. -let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); -let keyAgreementPromise = keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey); -keyAgreementPromise.then((secret) => { - console.info("keyAgreement output is " + secret.data); -}).catch((error) => { - console.error("keyAgreement error."); +var rand; +try { + rand = cryptoFramework.createRandom(); +} catch (error) { + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +} + +rand.generateRandom(12, (err, randData) => { + if (err) { + console.error("[Callback] err: " + err.code); + } else { + console.error("[Callback]: generate random result: " + randData.data); + try { + rand.setSeed(randData); + } catch (error) { + console.log("setSeed failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } }); ``` diff --git a/en/application-dev/reference/apis/js-apis-curve.md b/en/application-dev/reference/apis/js-apis-curve.md index bd673773b094eda6a3aa6d14c6d6ab7336120e65..dc0fdd5742cee370e7caa76bb6600fbf4b34ee98 100644 --- a/en/application-dev/reference/apis/js-apis-curve.md +++ b/en/application-dev/reference/apis/js-apis-curve.md @@ -25,9 +25,9 @@ Implements initialization for the interpolation curve, which is used to create a **Parameters** -| Name| Type | Mandatory| Default Value | Description | -| ------ | ------------------------------------------------------------ | ---- | ------------ | ---------- | -| curve | [Curve](../arkui-ts/ts-appendix-enums.md#curve) | No | Curve.Linear | Curve type.| +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------------------- | ---- | ----------------------------------- | +| curve | [Curve](../arkui-ts/ts-appendix-enums.md#curve) | No | Curve type.
Default value: **Curve.Linear**| **Return value** @@ -151,16 +151,16 @@ Creates a spring animation curve. If multiple spring animations are applied to t | Name | Type | Mandatory | Description | | --------- | ------ | ---- | ----- | -| response | number | No | Duration of one complete oscillation,
Default value: **0.55**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0.55**.| +| response | number | No | Duration of one complete oscillation.
Default value: **0.55**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0.55**.| | dampingFraction | number | No | Damping coefficient.
**0**: undamped. In this case, the spring oscillates forever.
> 0 and < 1: underdamped. In this case, the spring overshoots the equilibrium position.
**1**: critically damped.
> 1: overdamped. In this case, the spring approaches equilibrium gradually.
Default value: **0.825**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0.55**.| -| overlapDuration | number | No | Duration for animations to overlap, in seconds. When animations overlap, if the **response** values of the two animations are different, they will transit smoothly over this duration.

Default value: **0**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0**.
The spring animation curve is physics-based. Its duration depends on the **springMotion** parameters and the previous velocity, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). The time cannot be normalized. Therefore, the interpolation cannot be obtained by using the **[interpolate](#interpolate)** function of the curve.| +| overlapDuration | number | No | Duration for animations to overlap, in seconds. When animations overlap, if the **response** values of the two animations are different, they will transit smoothly over this duration.

Default value: **0**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0**.
The spring animation curve is physics-based. Its duration depends on the **springMotion** parameters and the previous velocity, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). The time cannot be normalized. Therefore, the interpolation cannot be obtained by using the **interpolate** function of the curve.| **Return value** | Type | Description | | ---------------------------------- | ---------------- | -| [ICurve](#icurve)| Curve.
**NOTE**
The spring animation curve is physics-based. Its duration depends on the **springMotion** parameters and the previous velocity, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). The time cannot be normalized. Therefore, the interpolation cannot be obtained by using the **[interpolate](#interpolate)** function of the curve.| +| [ICurve](#icurve)| Curve.
**NOTE**
The spring animation curve is physics-based. Its duration depends on the **springMotion** parameters and the previous velocity, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). The time cannot be normalized. Therefore, the interpolation cannot be obtained by using the **interpolate** function of the curve.| **Example** @@ -187,13 +187,13 @@ Creates a responsive spring animation curve. It is a special case of [springMoti | --------- | ------ | ---- | ----- | | response | number | No | See **response** in **springMotion**.
Default value: **0.15**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0.15**.| | dampingFraction | number | No | See **dampingFraction** in **springMotion**.
Default value: **0.86**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0.86**.| -| overlapDuration | number | No | See **overlapDuration** in **springMotion**.
Default value: **0.25**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0.25**.
To apply custom settings for a spring animation, you are advised to use **springMotion**. When using **responsiveSpringMotion**, you are advised to retain the default settings.
The duration of the responsive spring animation depends on the **responsiveSpringMotion** parameters and the previous velocity, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). In addition, the interpolation cannot be obtained by using the [interpolate](#interpolate) function of the curve.| +| overlapDuration | number | No | See **overlapDuration** in **springMotion**.
Default value: **0.25**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0.25**.
To apply custom settings for a spring animation, you are advised to use **springMotion**. When using **responsiveSpringMotion**, you are advised to retain the default settings.
The duration of the responsive spring animation depends on the **responsiveSpringMotion** parameters and the previous velocity, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). In addition, the interpolation cannot be obtained by using the **interpolate** function of the curve.| **Return value** | Type | Description | | ---------------------------------- | ---------------- | -| [ICurve](#icurve)| Curve.
**NOTE**
1. To apply custom settings for a spring animation, you are advised to use **springMotion**. When using **responsiveSpringMotion**, you are advised to retain the default settings.
2. The duration of the responsive spring animation depends on the **responsiveSpringMotion** parameters and the previous velocity, rather than the **duration** parameter in **animation** or **animateTo**. In addition, the interpolation cannot be obtained by using the [interpolate](#interpolate) function of the curve.| +| [ICurve](#icurve)| Curve.
**NOTE**
1. To apply custom settings for a spring animation, you are advised to use **springMotion**. When using **responsiveSpringMotion**, you are advised to retain the default settings.
2. The duration of the responsive spring animation depends on the **responsiveSpringMotion** parameters and the previous velocity, rather than the **duration** parameter in **animation** or **animateTo**. In addition, the interpolation cannot be obtained by using the [interpolate](#interpolate9) function of the curve.| **Example** @@ -260,7 +260,7 @@ import Curves from '@ohos.curves' interpolate(fraction) { return Math.sqrt(fraction); } -Curves.customCurve(this.interpolate) // Create a custom curve. +private curve = Curves.customCurve(this.interpolate) // Create a custom curve. ``` @@ -268,7 +268,7 @@ Curves.customCurve(this.interpolate) // Create a custom curve. ## ICurve -### interpolate +### interpolate9+ interpolate(fraction: number): number @@ -310,9 +310,9 @@ Implements initialization to create a curve. This API is deprecated since API ve **Parameters** -| Name| Type | Mandatory| Default Value | Description | -| ------ | ------------------------------------------------------------ | ---- | ------------ | ---------- | -| curve |[Curve](../arkui-ts/ts-appendix-enums.md#curve) | No | Curve.Linear | Curve type.| +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------------------- | ---- | ----------------------------------- | +| curve | [Curve](../arkui-ts/ts-appendix-enums.md#curve) | No | Curve type.
Default value: **Curve.Linear**| ## Curves.steps(deprecated) diff --git a/en/application-dev/reference/apis/js-apis-deque.md b/en/application-dev/reference/apis/js-apis-deque.md index 7242e7dabbf12e7e44a98fa23bc44b9ead440a1e..24a211683113a62ae975f77ea86d5139c4aeffc8 100644 --- a/en/application-dev/reference/apis/js-apis-deque.md +++ b/en/application-dev/reference/apis/js-apis-deque.md @@ -242,15 +242,15 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| -| thisArg | Object | No| Value to use when the callback is invoked.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked. The default value is this instance.| -callbackfn +callbackFn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | T | Yes| Value of the element that is currently traversed.| -| index | number | No| Position index of the element that is currently traversed.| -| deque | Deque<T> | No| Instance that invokes the **forEach** method.| +| index | number | No| Position index of the element that is currently traversed. The default value is **0**.| +| deque | Deque<T> | No| Instance that calls the **forEach** API. The default value is this instance.| **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-font.md b/en/application-dev/reference/apis/js-apis-font.md index dad280bb91d43d69f78f719cc8733fc212fec826..0a66ea708e32f95433061f082b3debd9911e753d 100644 --- a/en/application-dev/reference/apis/js-apis-font.md +++ b/en/application-dev/reference/apis/js-apis-font.md @@ -7,6 +7,10 @@ The **font** module provides APIs for registering custom fonts. > 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. +> +> The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see [UIContext](./js-apis-arkui-UIContext.md#uicontext). +> +> Since API version 10, you can use the [getFont](./js-apis-arkui-UIContext.md#getfont) API in [UIContext](./js-apis-arkui-UIContext.md#uicontext) to obtain the [Font](./js-apis-arkui-UIContext.md#font) object associated with the current UI context. ## Modules to Import @@ -165,3 +169,4 @@ struct FontExample { } } ``` + diff --git a/en/application-dev/reference/apis/js-apis-hashmap.md b/en/application-dev/reference/apis/js-apis-hashmap.md index c880644673fd9a8cd9d15ac05ec01afc9785bf3e..fc0a1e56470f7fb3a66a5feb1ad168b2c0fcea4a 100644 --- a/en/application-dev/reference/apis/js-apis-hashmap.md +++ b/en/application-dev/reference/apis/js-apis-hashmap.md @@ -459,14 +459,14 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| -| thisArg | Object | No| Value to use when the callback is invoked.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked. The default value is this instance.| -callbackfn +callbackFn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | V | No| Value of the element that is currently traversed.| -| key | K | No| Key of the element that is currently traversed.| -| map | HashMap | No| Instance that invokes the **forEach** method.| +| value | V | No| Value of the element that is currently traversed. The default value is the value of the first key-value pair.| +| key | K | No| Key of the element that is currently traversed. The default value is the key of the first key-value pair.| +| map | HashMap | No| Instance that calls the **forEach** API. The default value is this instance.| **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-hashset.md b/en/application-dev/reference/apis/js-apis-hashset.md index df65bfcb4a3167ed9c9f2292065554a505e9f4e1..e396f5e4e5256a946c508b549cb183e35b439715 100644 --- a/en/application-dev/reference/apis/js-apis-hashset.md +++ b/en/application-dev/reference/apis/js-apis-hashset.md @@ -282,14 +282,14 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| -| thisArg | Object | No| Value to use when the callback is invoked.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked. The default value is this instance.| -callbackfn +callbackFn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | No| Value of the element that is currently traversed.| -| key | T | No| Key of the element that is currently traversed (same as **value**).| -| set | HashSet<T> | No| Instance that invokes the **forEach** API.| +| value | T | No| Value of the element that is currently traversed. The default value is the value of the first key-value pair.| +| key | T | No| Key of the element that is currently traversed (same as **value**). The default value is the key of the first key-value pair.| +| set | HashSet<T> | No| Instance that calls the **forEach** API. The default value is this instance.| **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md b/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md index 6193495b7ce4aba021a6f87cfdf1622e0395db6a..6fa6435469ef0edb24b2bda81c077bef6585bf17 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md @@ -14,11 +14,13 @@ Called when the mission continuation is complete. **System capability**: SystemCapability.Ability.AbilityRuntime.Mission +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | result | number | No| Mission continuation result.| + | result | number | Yes| Mission continuation result.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md index e387ee397adb445f618c1a1df687b4f47b4d8cf5..4c84a0f8437779210bae784388d805d57b443508 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md @@ -23,7 +23,7 @@ Before using the **ServiceExtensionContext** module, you must first obtain a **F import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import formBindingData from '@ohos.app.form.formBindingData'; -class MyFormExtensionAbility extends FormExtensionAbility { +export default class MyFormExtensionAbility extends FormExtensionAbility { onAddForm(want) { let formContext = this.context; // Obtain a FormExtensionContext instance. // ... diff --git a/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md index fd791bc36fe187786aee1454612faac8c97b2131..8769c27b42aa1ceb7c75ffef98a21274932e9f3e 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md @@ -1617,8 +1617,8 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error let want = { bundleName: 'com.acts.actscalleeabilityrely', moduleName: 'entry', - abilityName: 'EntryAbility' - deviceId: '' + abilityName: 'EntryAbility', + deviceId: '', parameters: { // If the value of 'ohos.aafwk.param.callAbilityToForeground' is true, the ability is started in the foreground. If the value is false or not set, the ability is started in the background. 'ohos.aafwk.param.callAbilityToForeground': true diff --git a/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md b/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md index 63b85f46899461f7ccf6235a7ea870b933542007..6ce1025f20bcd21c0d85e366e794d882e65cad11 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md @@ -1228,7 +1228,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error // Process service logic errors. console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`); }); - } catch (error) { + } catch (err) { // Capture the synchronization parameter error. console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`); } @@ -2577,8 +2577,8 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error let want = { bundleName: 'com.acts.actscalleeabilityrely', moduleName: 'entry', - abilityName: 'EntryAbility' - deviceId: '' + abilityName: 'EntryAbility', + deviceId: '', parameters: { // If the value of 'ohos.aafwk.param.callAbilityToForeground' is true, the ability is started in the foreground. If the value is false or not set, the ability is started in the background. 'ohos.aafwk.param.callAbilityToForeground': true diff --git a/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscribeInfo.md b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscribeInfo.md index c5de47b81e6b928a7d26909a54aa9ba798078417..48c1cbf8ba92a32af0f45917ca9f03708ae6e30c 100644 --- a/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscribeInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscribeInfo.md @@ -8,7 +8,7 @@ | Name | Type | Readable| Writable| Description | | ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | -| events | Array\ | Yes | No | Name of the common event to publish. | +| events | Array\ | Yes | No | Common events to subscribe to. | | publisherPermission | string | Yes | No | Permissions required for publishers to publish the common event. | | publisherDeviceId | string | Yes | No | Device ID. The value must be the ID of a device on the same network. | | userId | number | Yes | No | User ID. The value must be an existing user ID in the system. If this parameter is not specified, the default value, which is the ID of the current user, will be used. | diff --git a/en/application-dev/reference/apis/js-apis-lightweightmap.md b/en/application-dev/reference/apis/js-apis-lightweightmap.md index ed1848ad8df12b8a5526699908347ade635a9041..af435ce52e23abbca6d5f3777f2dadc82c4701d4 100644 --- a/en/application-dev/reference/apis/js-apis-lightweightmap.md +++ b/en/application-dev/reference/apis/js-apis-lightweightmap.md @@ -724,14 +724,14 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| -| thisArg | Object | No| Value to use when the callback is invoked.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked. The default value is this instance.| -callbackfn +callbackFn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | V | No| Value of the element that is currently traversed.| -| key | K | No| Key of the element that is currently traversed.| -| map | LightWeightMap | No| Instance that invokes the **forEach** method.| +| value | V | No| Value of the element that is currently traversed. The default value is the value of the first key-value pair.| +| key | K | No| Key of the element that is currently traversed. The default value is the key of the first key-value pair.| +| map | LightWeightMap | No| Instance that calls the **forEach** API. The default value is this instance.| **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-lightweightset.md b/en/application-dev/reference/apis/js-apis-lightweightset.md index 05eba80d96783d32a427f1181bdc5b71bdab596b..7446c334dfa3022b943d1155e9bdab10e8e1e0a9 100644 --- a/en/application-dev/reference/apis/js-apis-lightweightset.md +++ b/en/application-dev/reference/apis/js-apis-lightweightset.md @@ -588,14 +588,14 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| -| thisArg | Object | No| Value to use when the callback is invoked.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked. The default value is this instance.| -callbackfn +callbackFn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | No| Value of the element that is currently traversed.| -| key| T | No| Key of the element that is currently traversed (same as **value**).| -| set | LightWeightSet<T> | No| Instance that invokes the **forEach** method.| +| value | T | No| Value of the element that is currently traversed. The default value is the value of the first key-value pair.| +| key| T | No| Key of the element that is currently traversed (same as **value**). The default value is the key of the first key-value pair.| +| set | LightWeightSet<T> | No| Instance that calls the **forEach** API. The default value is this instance.| **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-linkedlist.md b/en/application-dev/reference/apis/js-apis-linkedlist.md index 14382577e7b3fb1881e74527b8ec31ab87a89169..fa13281b52c968658e016fd7ee82be77e570fd60 100644 --- a/en/application-dev/reference/apis/js-apis-linkedlist.md +++ b/en/application-dev/reference/apis/js-apis-linkedlist.md @@ -607,15 +607,15 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| -| thisArg | Object | No| Value to use when the callback is invoked.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked. The default value is this instance.| -callbackfn +callbackFn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | T | Yes| Value of the element that is currently traversed.| -| index | number | No| Position index of the element that is currently traversed.| -| LinkedList | LinkedList<T> | No| Instance that invokes the **forEach** API.| +| index | number | No| Position index of the element that is currently traversed. The default value is **0**.| +| LinkedList | LinkedList<T> | No| Instance that calls the **forEach** API. The default value is this instance.| **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-list.md b/en/application-dev/reference/apis/js-apis-list.md index b7618d64c1d61a52324ada111347f666e7095c73..a9dd535c30efa333db867f444e28502f65ab8537 100644 --- a/en/application-dev/reference/apis/js-apis-list.md +++ b/en/application-dev/reference/apis/js-apis-list.md @@ -427,15 +427,15 @@ Replaces all elements in this container with new elements, and returns the new o | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | | callbackFn | function | Yes| Callback invoked for the replacement.| -| thisArg | Object | No| Value to use when the callback is invoked.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked. The default value is this instance.| -callbackfn +callbackFn | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | | value | T | Yes| Value of the element that is currently traversed.| -| index | number | No| Position index of the element that is currently traversed.| -| list | List<T> | No| Instance that invokes the **replaceAllElements** method.| +| index | number | No| Position index of the element that is currently traversed. The default value is **0**.| +| list | List<T> | No| Instance that calls the **replaceAllElements** API. The default value is this instance.| **Error codes** @@ -473,15 +473,15 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | | callbackFn | function | Yes| Callback invoked for the replacement.| -| thisArg | Object | No| Value to use when the callback is invoked.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked. The default value is this instance.| -callbackfn +callbackFn | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | | value | T | Yes| Value of the element that is currently traversed.| -| index | number | No| Position index of the element that is currently traversed.| -| List | List<T> | No| Instance that invokes the **forEach** method.| +| index | number | No| Position index of the element that is currently traversed. The default value is **0**.| +| List | List<T> | No| Instance that calls the **forEach** API. The default value is this instance.| **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-matrix4.md b/en/application-dev/reference/apis/js-apis-matrix4.md index b707f54df167497056052a8524ec00d7bbe11188..9c8c1a77c0150f8d820ec03701c3bd58ad9c8a17 100644 --- a/en/application-dev/reference/apis/js-apis-matrix4.md +++ b/en/application-dev/reference/apis/js-apis-matrix4.md @@ -16,7 +16,7 @@ import matrix4 from '@ohos.matrix4' ## matrix4.init -init(array: Array<number>): Matrix4Transit +init(option: [number,number,number,number,number,number,number,number,number,number,number,number,number,number,number,number]): Matrix4Transit Matrix constructor, which is used to create a 4 x 4 matrix by using the input parameter. Column-major order is used. @@ -25,17 +25,17 @@ Matrix constructor, which is used to create a 4 x 4 matrix by using the input pa **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------- | ---- | ------------------------------------------------------------ | -| array | Array<number> | Yes | A number array whose length is 16 (4 x 4). For details, see **array** parameters.
Default value:
[1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1] | +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| option | [number,number,number,number,number,number,number,number,number,number,number,number,number,number,number,number] | Yes | A number array whose length is 16 (4 x 4). For details, see **Description of a 4 x 4 matrix**.
Default value:
[1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1] | **Return value** -| Type | Description | -| -------------- | ---------------------------- | -| Matrix4Transit | 4 x 4 matrix object created based on the input parameter.| +| Type | Description | +| --------------------------------- | ---------------------------- | +| [Matrix4Transit](#matrix4transit) | 4 x 4 matrix object created based on the input parameter.| -**array** parameters +**Description of a 4 x 4 matrix** | Name | Type | Mandatory | Description | | ---- | ------ | ---- | -------------------- | @@ -91,9 +91,9 @@ Constructs an identity matrix. **Return value** -| Type | Description | -| -------------- | -------------- | -| Matrix4Transit | Identity matrix object.| +| Type | Description | +| --------------------------------- | -------------- | +| [Matrix4Transit](#matrix4transit) | Identity matrix object.| **Example** @@ -136,9 +136,9 @@ Copies this matrix object. **Return value** -| Type | Description | -| -------------- | -------------------- | -| Matrix4Transit | Copy object of the current matrix.| +| Type | Description | +| --------------------------------- | -------------------- | +| [Matrix4Transit](#matrix4transit) | Copy object of the current matrix.| **Example** @@ -171,12 +171,12 @@ struct Test { ![en-us_image_0000001219744181](figures/en-us_image_0000001219744181.png) -## Matrix4 +## Matrix4Transit ### combine -combine(matrix: Matrix4): Matrix4Transit +combine(option: Matrix4Transit): Matrix4Transit Combines the effects of two matrices to generate a new matrix object. @@ -185,15 +185,15 @@ Combines the effects of two matrices to generate a new matrix object. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------- | ---- | ------------------ | -| matrix | Matrix4 | Yes | Matrix object to be combined.| +| Name| Type | Mandatory| Description | +| ------ | --------------------------------- | ---- | ------------------ | +| option | [Matrix4Transit](#matrix4transit) | Yes | Matrix object to be combined.| **Return value** -| Type | Description | -| -------------- | ------------------ | -| Matrix4Transit | Object after matrix combination.| +| Type | Description | +| --------------------------------- | ------------------ | +| [Matrix4Transit](#matrix4transit) | Object after matrix combination.| **Example** @@ -238,9 +238,9 @@ Inverts this matrix object. **Return value** -| Type | Description | -| -------------- | ---------------------- | -| Matrix4Transit | Inverse matrix object of the current matrix.| +| Type | Description | +| --------------------------------- | ---------------------- | +| [Matrix4Transit](#matrix4transit) | Inverse matrix object of the current matrix.| **Example** @@ -273,7 +273,7 @@ struct Tests { ### translate -translate({x?: number, y?: number, z?: number}): Matrix4Transit +translate(option: TranslateOption): Matrix4Transit Translates this matrix object along the x, y, and z axes. @@ -281,17 +281,15 @@ Translates this matrix object along the x, y, and z axes. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ----------------------------------------------------------- | -| x | number | No | Translation distance along the x-axis, in px.
Default value: **0**
Value range: (-∞, +∞)| -| y | number | No | Translation distance along the y-axis, in px.
Default value: **0**
Value range: (-∞, +∞)| -| z | number | No | Translation distance along the z-axis, in px.
Default value: **0**
Value range: (-∞, +∞)| +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | -------------- | +| option | [TranslateOption](#translateoption) | Yes | Translation configuration.| **Return value** -| Type | Description | -| -------------- | ---------------------------- | -| Matrix4Transit | Matrix object after the translation effect is added.| +| Type | Description | +| --------------------------------- | ---------------------------- | +| [Matrix4Transit](#matrix4transit) | Matrix object after the translation.| **Example** @@ -319,7 +317,7 @@ struct Test { ### scale -scale({x?: number, y?: number, z?: number, centerX?: number, centerY?: number}): Matrix4Transit +scale(option: ScaleOption): Matrix4Transit Scales this matrix object along the x, y, and z axes. @@ -328,19 +326,16 @@ Scales this matrix object along the x, y, and z axes. **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------------------------------------------------------ | -| x | number | No | Scaling multiple along the x-axis. If the value is greater than 1, the image is scaled up along the x-axis. If the value is less than 1, the image is scaled down along the x-axis.
Default value: **1**
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value.| -| y | number | No | Scaling multiple along the y-axis. If the value is greater than 1, the image is scaled up along the y-axis. If the value is less than 1, the image is scaled down along the y-axis.
Default value: **1**
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value.| -| z | number | No | Scaling multiple along the z-axis. If the value is greater than 1, the image is scaled up along the z-axis. If the value is less than 1, the image is scaled down along the z-axis.
Default value: **1**
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value.| -| centerX | number | No | X coordinate of the center point.
Default value: **0**
Value range: (-∞, +∞) | -| centerY | number | No | Y coordinate of the center point.
Default value: **0**
Value range: (-∞, +∞) | +| Name| Type | Mandatory| Description | +| ------ | --------------------------- | ---- | -------------- | +| option | [ScaleOption](#scaleoption) | Yes | Scaling configuration.| + **Return value** -| Type | Description | -| -------------- | ---------------------------- | -| Matrix4Transit | Matrix object after the scaling effect is added.| +| Type | Description | +| --------------------------------- | ---------------------------- | +| [Matrix4Transit](#matrix4transit) | Matrix object after the scaling.| **Example** @@ -367,7 +362,7 @@ struct Test { ### rotate -rotate({x?: number, y?: number, z?: number, angle?: number, centerX?: Length, centerY?: Length}): Matrix4Transit +rotate(option: RotateOption): Matrix4Transit Rotates this matrix object along the x, y, and z axes. @@ -376,20 +371,16 @@ Rotates this matrix object along the x, y, and z axes. **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------------------------------------------------- | -| x | number | No | X coordinate of the rotation axis vector.
Default value: **1**
Value range: (-∞, +∞)| -| y | number | No | Y coordinate of the rotation axis vector.
Default value: **1**
Value range: (-∞, +∞)| -| z | number | No | Z coordinate of the rotation axis vector.
Default value: **1**
Value range: (-∞, +∞)| -| angle | number | No | Rotation angle.
Default value: **0** | -| centerX | number | No | X coordinate of the center point.
Default value: **0** | -| centerY | number | No | Y coordinate of the center point.
Default value: **0** | +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------- | +| option | [RotateOption](#rotateoption) | Yes | Rotation configuration.| + **Return value** -| Type | Description | -| -------------- | ---------------------------- | -| Matrix4Transit | Matrix object after the rotation effect is added.| +| Type | Description | +| --------------------------------- | ---------------------------- | +| [Matrix4Transit](#matrix4transit) | Matrix object after the rotation.| **Example** @@ -417,7 +408,7 @@ struct Test { ### transformPoint -transformPoint(point: Point): Point +transformPoint(option: [number, number]): [number, number] Applies the current transformation effect to a coordinate point. @@ -426,15 +417,15 @@ Applies the current transformation effect to a coordinate point. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----- | ---- | ------------------ | -| point | Point | Yes | Point to be transformed.| +| Name| Type | Mandatory| Description | +| ------ | ---------------- | ---- | ------------------ | +| option | [number, number] | Yes | Point to be transformed.| **Return value** -| Type | Description | -| ----- | ---------------- | -| Point | Point object after matrix transformation| +| Type | Description | +| ---------------- | --------------------------- | +| [number, number] | Point object after matrix transformation| **Example** @@ -472,3 +463,32 @@ struct Test { ``` ![en-us_image_0000001219864133](figures/en-us_image_0000001219864133.PNG) + +## TranslateOption + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------------------------------------------------------- | +| x | number | No | Translation distance along the x-axis, in px.
Default value: **0**
Value range: (-∞, +∞)| +| y | number | No | Translation distance along the y-axis, in px.
Default value: **0**
Value range: (-∞, +∞)| +| z | number | No | Translation distance along the z-axis, in px.
Default value: **0**
Value range: (-∞, +∞)| + +## ScaleOption + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------------------------------------ | +| x | number | No | Scaling multiple along the x-axis. If the value is greater than 1, the image is scaled up along the x-axis. If the value is less than 1, the image is scaled down along the x-axis.
Default value: **1**
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value.| +| y | number | No | Scaling multiple along the y-axis. If the value is greater than 1, the image is scaled up along the y-axis. If the value is less than 1, the image is scaled down along the y-axis.
Default value: **1**
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value.| +| z | number | No | Scaling multiple along the z-axis. If the value is greater than 1, the image is scaled up along the z-axis. If the value is less than 1, the image is scaled down along the z-axis.
Default value: **1**
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value.| +| centerX | number | No | X coordinate of the center point.
Default value: **0**
Value range: (-∞, +∞) | +| centerY | number | No | Y coordinate of the center point.
Default value: **0**
Value range: (-∞, +∞) | + +## RotateOption + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------------------------------- | +| x | number | No | X coordinate of the rotation axis vector.
Default value: **1**
Value range: (-∞, +∞)| +| y | number | No | Y coordinate of the rotation axis vector.
Default value: **1**
Value range: (-∞, +∞)| +| z | number | No | Z coordinate of the rotation axis vector.
Default value: **1**
Value range: (-∞, +∞)| +| angle | number | No | Rotation angle.
Default value: **0** | +| centerX | number | No | X coordinate of the center point.
Default value: **0** | +| centerY | number | No | Y coordinate of the center point.
Default value: **0** | diff --git a/en/application-dev/reference/apis/js-apis-measure.md b/en/application-dev/reference/apis/js-apis-measure.md index 55d5b70a7009b42f2a9d683566c958ad027d9eb4..4b0eac439ab60844ca48f768ed768126b01d64da 100644 --- a/en/application-dev/reference/apis/js-apis-measure.md +++ b/en/application-dev/reference/apis/js-apis-measure.md @@ -112,7 +112,7 @@ Provides attributes of the measured text. | Name | Type | Mandatory| Description | | -------------- | -------------------------------------------------------------------------------------------------- | ---- | ----------------------------------------------- | -| textContent10+ | string | Yes | Content of the measured text. | +| textContent | string | Yes | Content of the measured text. | | constraintWidth10+ | number \| string \| [Resource](../arkui-ts/ts-types.md#resource) | No | Layout width of the measured text.
The default unit is vp. | | fontSize | number \| string \| [Resource](../arkui-ts/ts-types.md#resource) | No | Font size of the measured text. If the value is of the number type, the unit fp is used.
Default value: **16fp**
**NOTE**
The value cannot be a percentage. | | fontStyle | number \| [FontStyle](../arkui-ts/ts-appendix-enums.md#fontstyle) | No | Font style of the measured text.
Default value: **FontStyle.Normal** | diff --git a/en/application-dev/reference/apis/js-apis-mediaquery.md b/en/application-dev/reference/apis/js-apis-mediaquery.md index b2b8dfd30eb68510227790c45366de315cbb856b..29f319addaadfc093be1d7da8e5eb6aecc40f98d 100644 --- a/en/application-dev/reference/apis/js-apis-mediaquery.md +++ b/en/application-dev/reference/apis/js-apis-mediaquery.md @@ -7,6 +7,10 @@ The **mediaquery** module provides different styles for different media types. > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > > This module can be used only after a component instance is created, and it cannot be used in the [UIAbility](./js-apis-app-ability-uiAbility.md). +> +> The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see [UIContext](./js-apis-arkui-UIContext.md#uicontext). +> +> Since API version 10, you can use the [getMediaQuery](./js-apis-arkui-UIContext.md#getmediaquery) API in [UIContext](./js-apis-arkui-UIContext.md#uicontext) to obtain the [MediaQuery](./js-apis-arkui-UIContext.md#mediaquery) object associated with the current UI context. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-plainarray.md b/en/application-dev/reference/apis/js-apis-plainarray.md index 14f73f6d4b11059551b376f7fcb9e56ee4e1ab84..5ce7718cc4bcb677a35f83079d9392d2b9d0ba0c 100644 --- a/en/application-dev/reference/apis/js-apis-plainarray.md +++ b/en/application-dev/reference/apis/js-apis-plainarray.md @@ -597,14 +597,14 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type | Mandatory| Description| | -------- | -------- | -------- | -------- | | callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| -| thisArg | Object | No| Value to use when the callback is invoked.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked. The default value is this instance.| -callbackfn +callbackFn | Name| Type | Mandatory| Description| | -------- | -------- | -------- | -------- | | value | T | Yes| Value of the element that is currently traversed.| -| index | number | No| Key of the element that is currently traversed.| -| PlainArray | PlainArray<T>| No| Instance that invokes the **forEach** API.| +| index | number | No| Position index of the element that is currently traversed. The default value is **0**.| +| PlainArray | PlainArray<T>| No| Instance that calls the **forEach** API. The default value is this instance.| **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-promptAction.md b/en/application-dev/reference/apis/js-apis-promptAction.md index aed51460eb6f196f07d72ee6071da53e4b052458..1624fd511a1f1fd99fb75e4aa93b3dc2a2872bd9 100644 --- a/en/application-dev/reference/apis/js-apis-promptAction.md +++ b/en/application-dev/reference/apis/js-apis-promptAction.md @@ -7,6 +7,10 @@ The **PromptAction** module provides APIs for creating and showing toasts, dialo > 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. > > This module can be used only after a component instance is created, and it cannot be used in the [UIAbility](./js-apis-app-ability-uiAbility.md). +> +> The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see [UIContext](./js-apis-arkui-UIContext.md#uicontext). +> +> Since API version 10, you can use the [getPromptAction](./js-apis-arkui-UIContext.md#getpromptaction) API in [UIContext](./js-apis-arkui-UIContext.md#uicontext) to obtain the [PromptAction](./js-apis-arkui-UIContext.md#promptaction) object associated with the current UI context. ## Modules to Import @@ -62,7 +66,7 @@ Describes the options for showing the toast. | -------- | ---------------------------------------- | ---- | ---------------------------------------- | | message | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| Yes | Text to display. | | duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used. If the value greater than 10000 ms is set, the upper limit 10000 ms is used.| -| bottom | string\| number | No | Distance between the toast border and the bottom of the screen. | +| bottom | string\| number | No | Distance between the toast border and the bottom of the screen.
Default value: **80vp** | ## promptAction.showDialog @@ -319,7 +323,7 @@ Describes the options for showing the action menu. | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| No | Title of the dialog box. | -| buttons | [[Button](#button),[Button](#button)?,[Button](#button)?,[Button](#button)?,[Button](#button)?,[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.| +| buttons | [[Button](#button),[Button](#button)?,[Button](#button)?,[Button](#button)?,[Button](#button)?,[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, only the first six buttons will be displayed.| ## ActionMenuSuccessResponse diff --git a/en/application-dev/reference/apis/js-apis-queue.md b/en/application-dev/reference/apis/js-apis-queue.md index c926b741543cd384f6c4b7649c2e8f1881883a55..ff4639e830aee3ba615858a38e3b8a84b12575a5 100644 --- a/en/application-dev/reference/apis/js-apis-queue.md +++ b/en/application-dev/reference/apis/js-apis-queue.md @@ -176,15 +176,15 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| -| thisArg | Object | No| Value to use when the callback is invoked.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked. The default value is this instance.| -callbackfn +callbackFn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | T | Yes| Value of the element that is currently traversed.| -| index | number | No| Position index of the element that is currently traversed.| -| Queue | Queue<T> | No| Instance that invokes the **forEach** method.| +| index | number | No| Position index of the element that is currently traversed. The default value is **0**.| +| Queue | Queue<T> | No| Instance that calls the **forEach** API. The default value is this instance.| **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-reminderAgent.md b/en/application-dev/reference/apis/js-apis-reminderAgent.md index 0c7fa19432c45e801f82b2892d47fa9ed384ea4e..a817d3bc82a541c9937c05aec30b2ecd0bb830ff 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgent.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgent.md @@ -371,7 +371,7 @@ reminderAgent.addNotificationSlot(mySlot).then(() => { ## reminderAgent.removeNotificationSlot(deprecated) -removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback): void +removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback\): void Removes a notification slot of a specified type. This API uses an asynchronous callback to return the result. @@ -401,7 +401,7 @@ reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION, ## reminderAgent.removeNotificationSlot(deprecated) -removeNotificationSlot(slotType: notification.SlotType): Promise +removeNotificationSlot(slotType: notification.SlotType): Promise\ Removes a notification slot of a specified type. This API uses a promise to return the result. diff --git a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md index 87a8ea3167b1cc125eb8e2bf5e30b4cfe54cc5a3..644759435975c722de9fd274b704ecd01804d2fd 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md @@ -611,7 +611,7 @@ Defines the reminder to publish. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderType | [ReminderType](#remindertype) | Yes| Type of the reminder.| -| actionButton10+ | [ActionButton](#actionbutton) | No| Button displayed for the reminder in the notification panel. For common applications, a maximum of two buttons are supported. For system applications, a maximum of two buttons are supported in API version 9, and a maximum of three buttons are supported in API version 10 and later versions.| +| actionButton | [ActionButton](#actionbutton) | No| Buttons displayed for the reminder in the notification panel.
- For common applications, a maximum of two buttons are supported.
- For system applications, a maximum of two buttons are supported in API version 9, and a maximum of three buttons are supported in API version 10 and later versions.| | wantAgent | [WantAgent](#wantagent) | No| Information about the ability that is redirected to when the reminder is clicked.| | maxScreenWantAgent | [MaxScreenWantAgent](#maxscreenwantagent) | No| Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed.| | ringDuration | number | No| Ringing duration, in seconds. The default value is **1**.| diff --git a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceStandby.md b/en/application-dev/reference/apis/js-apis-resourceschedule-deviceStandby.md similarity index 53% rename from zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceStandby.md rename to en/application-dev/reference/apis/js-apis-resourceschedule-deviceStandby.md index c7a680f3562542be9bfdfa3abb55c2f2e1192e9b..116d4af987fb061f516d6ec37053794737f65c84 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceStandby.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-deviceStandby.md @@ -1,11 +1,11 @@ -# @ohos.resourceschedule.deviceStandby(设备待机模块) -当设备长时间未被使用或通过按键,可以使设备进入待机模式。待机模式不影响应用使用,还可以延长电池续航时间。通过本模块接口,可查询设备或应用是否为待机模式,以及为应用申请或取消待机资源管控。 +# @ohos.resourceschedule.deviceStandby (Device Standby) +A device enters standby mode if it is unused for a long period of time or after the Power button is pressed. The standby mode prolongs the battery life without affecting the use of applications. The **deviceStandby** module provides APIs for you to check whether a device is in standby mode and request or cancel standby resource control for an application. -> **说明**: +> **NOTE** > -> 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
+> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. -## 导入模块 +## Modules to Import ```js import deviceStandby from '@ohos.resourceschedule.deviceStandby'; @@ -15,23 +15,23 @@ import deviceStandby from '@ohos.resourceschedule.deviceStandby'; isDeviceInStandby(callback: AsyncCallback<boolean>): void; -当前设备是否进入待机低功耗续航模式,使用Callback异步回调。 +Checks whether the device is in standby mode. This API uses an asynchronous callback to return the result. -**系统能力:** SystemCapability.ResourceSchedule.DeviceStandby +**System capability**: SystemCapability.ResourceSchedule.DeviceStandby -**需要权限:** ohos.permission.DEVICE_STANDBY_EXEMPTION +**Required permissions**: ohos.permission.DEVICE_STANDBY_EXEMPTION -**参数**: +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory | Description | | -------- | -------------------- | ---- | ------------------------------ | -| callback | AsyncCallback<boolean> | 是 | 延迟即将超时的回调函数,一般在超时前6秒通过此回调通知应用。 | +| callback | AsyncCallback<boolean> | Yes | Callback used to return whether the device is standby mode.| -**错误码**: +**Error codes** -以下错误码的详细介绍请参见[后台任务错误码](../errorcodes/errorcode-backgroundTaskMgr.md)。 +For details about the error codes, see [Background Task Management Error Codes](../errorcodes/errorcode-backgroundTaskMgr.md). -| 错误码ID | 错误信息 | +| ID | Error Message | | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | @@ -39,7 +39,7 @@ isDeviceInStandby(callback: AsyncCallback<boolean>): void; | 9800004 | System service operation failed. | | 18700001 | Caller information verification failed. | -**示例**: +**Example** ```js try{ @@ -59,23 +59,23 @@ console.log('DEVICE_STANDBY isDeviceInStandby throw error, code is: ' + error.co isDeviceInStandby(): Promise<boolean> -当前设备是否进入待机低功耗续航模式,使用Promise异步回调。 +Checks whether the device is in standby mode. This API uses a promise to return the result. -**系统能力:** SystemCapability.ResourceSchedule.DeviceStandby +**System capability**: SystemCapability.ResourceSchedule.DeviceStandby -**需要权限:** ohos.permission.DEVICE_STANDBY_EXEMPTION +**Required permissions**: ohos.permission.DEVICE_STANDBY_EXEMPTION -**返回值**: +**Return value** -| 类型 | 说明 | +| Type | Description | | --------------------- | ---------------------------------------- | -| Promise<boolean> | 指定的Promise回调方法,返回是否进入待机低功耗续航模式。| +| Promise<boolean> | Promise used to return whether the device is in standby mode.| -**错误码**: +**Error codes** -以下错误码的详细介绍请参见[后台任务错误码](../errorcodes/errorcode-backgroundTaskMgr.md)。 +For details about the error codes, see [Background Task Management Error Codes](../errorcodes/errorcode-backgroundTaskMgr.md). -| 错误码ID | 错误信息 | +| ID | Error Message | | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | @@ -83,7 +83,7 @@ isDeviceInStandby(): Promise<boolean> | 9800004 | System service operation failed. | | 18700001 | Caller information verification failed. | -**示例**: +**Example** ```js try{ @@ -101,26 +101,26 @@ console.log('DEVICE_STANDBY isDeviceInStandby throw error, code is: ' + error.co getExemptedApps(resourceTypes: number, callback: AsyncCallback): void; -获取进入待机模式的应用名单,使用Callback异步回调。 +Obtains the list of applications that can still use resources of the specified types when the device is in standby mode. This API uses an asynchronous callback to return the result. -**系统能力:** SystemCapability.ResourceSchedule.DeviceStandby +**System capability**: SystemCapability.ResourceSchedule.DeviceStandby -**需要权限:** ohos.permission.DEVICE_STANDBY_EXEMPTION +**Required permissions**: ohos.permission.DEVICE_STANDBY_EXEMPTION -**系统API:** 此接口为系统接口。 +**System API**: This is a system API. -**参数**: +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory | Description | | -------- | -------------------- | ---- | ------------------------------ | -| [ResourceTypes](#resourcetype)|number | 是 | 资源类型。 | -| callback | AsyncCallback | 是 |豁免应用信息 。| +| [ResourceTypes](#resourcetype)|number | Yes | Types of resources that can be used.| +| callback | AsyncCallback | Yes |Callback used to return the exempted application information.| -**错误码**: +**Error codes** -以下错误码的详细介绍请参见[后台任务错误码](../errorcodes/errorcode-backgroundTaskMgr.md)。 +For details about the error codes, see [Background Task Management Error Codes](../errorcodes/errorcode-backgroundTaskMgr.md). -| 错误码ID | 错误信息 | +| ID | Error Message | | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | @@ -128,7 +128,7 @@ getExemptedApps(resourceTypes: number, callback: AsyncCallback; -获取进入待机模式的应用名单,使用Promise异步回调。 +Obtains the list of applications that can still use resources of the specified type when the device is in standby mode. This API uses a promise to return the result. -**系统能力:** SystemCapability.ResourceSchedule.DeviceStandby +**System capability**: SystemCapability.ResourceSchedule.DeviceStandby -**需要权限:** ohos.permission.DEVICE_STANDBY_EXEMPTION +**Required permissions**: ohos.permission.DEVICE_STANDBY_EXEMPTION -**系统API:** 此接口为系统接口。 +**System API**: This is a system API. -**参数**: +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory | Description | | -------- | -------------------- | ---- | ------------------------------ | -| [ResourceTypes](#resourcetype)|number | 是 |资源类型。| +| [ResourceTypes](#resourcetype)|number | Yes |Types of resources that can be used.| -**返回值**: +**Return value** -| 类型 | 说明 | +| Type | Description | | --------------------- | ---------------------------------------- | -| Promise | 豁免应用信息。 | +| Promise | Promise used to return the exempted application information.| -**错误码**: +**Error codes** -以下错误码的详细介绍请参见[后台任务错误码](../errorcodes/errorcode-backgroundTaskMgr.md)。 +For details about the error codes, see [Background Task Management Error Codes](../errorcodes/errorcode-backgroundTaskMgr.md). -| 错误码ID | 错误信息 | +| ID | Error Message | | ---- | --------------------- | | 201 | Permission denied. | | 202 | Not System App. | @@ -186,7 +186,7 @@ getExemptedApps(resourceTypes: number): Promise; | 9800004 | System service operation failed. | | 18700001 | Caller information verification failed. | -**示例**: +**Example** ```js try{ @@ -207,25 +207,25 @@ console.log('DEVICE_STANDBY getExemptedApps throw error, code is: ' + error.code requestExemptionResource(request: ResourceRequest): void; -应用订阅申请豁免,使应用临时不进入待机管控。 +Requests exemption, so that the application can use restricted resources when the device is in standby mode. -**系统能力:** SystemCapability.ResourceSchedule.DeviceStandby.Exemption +**System capability**: SystemCapability.ResourceSchedule.DeviceStandby.Exemption -**需要权限:** ohos.permission.DEVICE_STANDBY_EXEMPTION +**Required permissions**: ohos.permission.DEVICE_STANDBY_EXEMPTION -**系统API:** 此接口为系统接口。 +**System API**: This is a system API. -**参数**: +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory | Description | | -------- | -------------------- | ---- | ------------------------------ | -| request |[ResourceRequest](#resourcerequest)| 是 | 资源请求。 | +| request |[ResourceRequest](#resourcerequest)| Yes | Request body.| -**错误码**: +**Error codes** -以下错误码的详细介绍请参见[后台任务错误码](../errorcodes/errorcode-backgroundTaskMgr.md)。 +For details about the error codes, see [Background Task Management Error Codes](../errorcodes/errorcode-backgroundTaskMgr.md). -| 错误码ID | 错误信息 | +| ID | Error Message | | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | @@ -233,7 +233,7 @@ requestExemptionResource(request: ResourceRequest): void; | 9800004 | System service operation failed. | | 18700001 | Caller information verification failed. | -**示例**: +**Example** ```js let resRequest = { @@ -243,7 +243,7 @@ let resRequest = { duration:10, reason:"apply", }; -// 异步方法promise方式 +// Promise mode try{ deviceStandby.requestExemptionResource(resRequest).then( () => { console.log('DEVICE_STANDBY requestExemptionResource promise succeeded.'); @@ -254,7 +254,7 @@ deviceStandby.requestExemptionResource(resRequest).then( () => { console.log('DEVICE_STANDBY requestExemptionResource throw error, code is: ' + error.code + ',message is: ' + error.message); } -// 异步方法callback方式 +// Asynchronous callback mode try{ deviceStandby.requestExemptionResource(resRequest, (err) => { if (err) { @@ -272,25 +272,25 @@ console.log('DEVICE_STANDBY requestExemptionResource throw error, code is: ' + e releaseExemptionResource(request: ResourceRequest): void; -取消应用订阅申请豁免。 +Cancels exemption for the application. -**系统能力:** SystemCapability.ResourceSchedule.DeviceStandby.Exemption +**System capability**: SystemCapability.ResourceSchedule.DeviceStandby.Exemption -**需要权限:** ohos.permission.DEVICE_STANDBY_EXEMPTION +**Required permissions**: ohos.permission.DEVICE_STANDBY_EXEMPTION -**系统API:** 此接口为系统接口。 +**System API**: This is a system API. -**参数**: +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory | Description | | -------- | -------------------- | ---- | ------------------------------ | -| request |[ResourceRequest](#resourcerequest)| 是 | 资源请求 。| +| request |[ResourceRequest](#resourcerequest)| Yes | Request body.| -**错误码**: +**Error codes** -以下错误码的详细介绍请参见[后台任务错误码](../errorcodes/errorcode-backgroundTaskMgr.md)。 +For details about the error codes, see [Background Task Management Error Codes](../errorcodes/errorcode-backgroundTaskMgr.md). -| 错误码ID | 错误信息 | +| ID | Error Message | | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | @@ -298,7 +298,7 @@ releaseExemptionResource(request: ResourceRequest): void; | 9800004 | System service operation failed. | | 18700001 | Caller information verification failed. | -**示例**: +**Example** ```js let resRequest = { @@ -308,7 +308,7 @@ let resRequest = { duration:10, reason:"unapply", }; -// 异步方法promise方式 +// Promise mode try{ deviceStandby.releaseExemptionResource(resRequest).then( () => { console.log('DEVICE_STANDBY releaseExemptionResource promise succeeded.'); @@ -319,7 +319,7 @@ deviceStandby.releaseExemptionResource(resRequest).then( () => { console.log('DEVICE_STANDBY releaseExemptionResource throw error, code is: ' + error.code + ',message is: ' + error.message); } -// 异步方法callback方式 +// Asynchronous callback mode try{ deviceStandby.releaseExemptionResource(resRequest, (err) => { if (err) { @@ -335,48 +335,48 @@ console.log('DEVICE_STANDBY releaseExemptionResource throw error, code is: ' + e ## ResourceType -非待机应用资源枚举。 +Enumerates the types of resources that can be used by exempted applications. -**需要权限:** ohos.permission.DEVICE_STANDBY_EXEMPTION +**Required permissions**: ohos.permission.DEVICE_STANDBY_EXEMPTION -**系统API:** 此接口为系统接口。 +**System API**: This is a system API. -|名称 |值 |说明| +|Name |Value |Description| | ------------ | ------------ |--------------| -|NETWORK |1 |网络访问资源| -|RUNNING_LOCK |2 |cpu-runninglock资源| -|TIMER |4 | timer任务资源| -|WORK_SCHEDULER |8 | work任务资源| -|AUTO_SYNC |16 | 自动同步的资源 | -|PUSH |32 | pushkit资源| -|FREEZE |64 | 冻结应用资源| +|NETWORK |1 |Network access resource.| +|RUNNING_LOCK |2 |CPU running lock resource.| +|TIMER |4 | Timer task resource.| +|WORK_SCHEDULER |8 | Work task resource.| +|AUTO_SYNC |16 | Automatic synchronization resource.| +|PUSH |32 | Push kit resource.| +|FREEZE |64 | Freezing application resource.| ## ExemptedAppInfo -豁免应用信息,未进入待机管控的应用信息。 +Defines the information about an exempted application. -**需要权限:** ohos.permission.DEVICE_STANDBY_EXEMPTION +**Required permissions**: ohos.permission.DEVICE_STANDBY_EXEMPTION -**系统API:** 此接口为系统接口。 +**System API**: This is a system API. -|名称 |类型 | 必填 |说明 | +|Name |Type | Mandatory |Description | | ------------ | ------------ |------------ | ------------ | -|[resourceTypes](#resourcetype) | number | 是 |应用的资源类型 | -|name |string | 是 | 应用名 | -|duration | number | 是 | 豁免时长 | +|[resourceTypes](#resourcetype) | number | Yes |Types of resources that can be used. | +|name |string | Yes | Name of the application. | +|duration | number | Yes | Exemption duration.| ## ResourceRequest -待机资源请求体。 +Defines the message used to request to be an exempted application. -**需要权限:** ohos.permission.DEVICE_STANDBY_EXEMPTION +**Required permissions**: ohos.permission.DEVICE_STANDBY_EXEMPTION -**系统API:** 此接口为系统接口。 +**System API**: This is a system API. -|名称 |类型 | 必填 |说明 | +|Name |Type | Mandatory |Description | | ------------ | ------------ |------------| ------------ | -|[resourceTypes](#resourcetype) | number | 是 |应用的资源类型 | -|uid | number | 是 |应用uid | -|name |string | 是 | 应用名称 | -|duration | number | 是 | 豁免时长 | -|reason |string | 是 | 申请原因 | \ No newline at end of file +|[resourceTypes](#resourcetype) | number | Yes |Types of resources that can be used. | +|uid | number | Yes |UID of the application. | +|name |string | Yes | Name of the application. | +|duration | number | Yes | Exemption duration.| +|reason |string | Yes | Reason for the request. | diff --git a/en/application-dev/reference/apis/js-apis-router.md b/en/application-dev/reference/apis/js-apis-router.md index 2020f98279bc94e3ba292ced7d156cc963f46dd6..4319de28861f4056ca47657cf72a4af526b886f6 100644 --- a/en/application-dev/reference/apis/js-apis-router.md +++ b/en/application-dev/reference/apis/js-apis-router.md @@ -7,6 +7,10 @@ The **Router** module provides APIs to access pages through URLs. You can use th > - 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. > > - Page routing APIs can be invoked only after page rendering is complete. Do not call these APIs in **onInit** and **onReady** when the page is still in the rendering phase. +> +> - The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see [UIContext](./js-apis-arkui-UIContext.md#uicontext). +> +> - Since API version 10, you can use the [getRouter](./js-apis-arkui-UIContext.md#getrouter) API in [UIContext](./js-apis-arkui-UIContext.md#uicontext) to obtain the [Router](./js-apis-arkui-UIContext.md#router) object associated with the current UI context. ## Modules to Import @@ -46,7 +50,7 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc **Example** -```js +```ts router.pushUrl({ url: 'pages/routerpage2', params: { @@ -91,7 +95,7 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc **Example** -```js +```ts router.pushUrl({ url: 'pages/routerpage2', params: { @@ -141,7 +145,7 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc **Example** -```js +```ts router.pushUrl({ url: 'pages/routerpage2', params: { @@ -187,7 +191,7 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc **Example** -```js +```ts router.pushUrl({ url: 'pages/routerpage2', params: { @@ -236,7 +240,7 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc **Example** -```js +```ts router.replaceUrl({ url: 'pages/detail', params: { @@ -277,7 +281,7 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc **Example** -```js +```ts router.replaceUrl({ url: 'pages/detail', params: { @@ -325,7 +329,7 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc **Example** -```js +```ts router.replaceUrl({ url: 'pages/detail', params: { @@ -367,7 +371,7 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc **Example** -```js +```ts router.replaceUrl({ url: 'pages/detail', params: { @@ -383,6 +387,375 @@ router.replaceUrl({ ``` +## router.pushNamedRoute10+ + +pushNamedRoute(options: NamedRouterOptions): Promise<void> + +Navigates to a page using the named route. This API uses a promise to return the result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | --------- | +| options | [NamedRouterOptions](#namedrouteroptions10) | Yes | Page routing parameters.| + +**Return value** + +| Type | Description | +| ------------------- | --------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found. | +| 100003 | if the pages are pushed too much. | +| 100004 | if the named route is not exist. | + +**Example** + +```ts +router.pushNamedRoute({ + name: 'myPage', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + } + } +}) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); + }) +``` + +## router.pushNamedRoute10+ + +pushNamedRoute(options: NamedRouterOptions, callback: AsyncCallback<void>): void + +Navigates to a page using the named route. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | --------- | +| options | [NamedRouterOptions](#namedrouteroptions10) | Yes | Page routing parameters.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found. | +| 100003 | if the pages are pushed too much. | +| 100004 | if the named route is not exist. | + +**Example** + +```ts +router.pushNamedRoute({ + name: 'myPage', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + } + } +}, (err) => { + if (err) { + console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('pushNamedRoute success'); +}) +``` +## router.pushNamedRoute10+ + +pushNamedRoute(options: NamedRouterOptions, mode: RouterMode): Promise<void> + +Navigates to a page using the named route. This API uses a promise to return the result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------- | +| options | [NamedRouterOptions](#namedrouteroptions10) | Yes | Page routing parameters. | +| mode | [RouterMode](#routermode9) | Yes | Routing mode.| + +**Return value** + +| Type | Description | +| ------------------- | --------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found. | +| 100003 | if the pages are pushed too much. | +| 100004 | if the named route is not exist. | + +**Example** + +```ts +router.pushNamedRoute({ + name: 'myPage', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + } + } +}, router.RouterMode.Standard) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); + }) +``` + +## router.pushNamedRoute10+ + +pushNamedRoute(options: NamedRouterOptions, mode: RouterMode, callback: AsyncCallback<void>): void + +Navigates to a page using the named route. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------- | +| options | [NamedRouterOptions](#namedrouteroptions10) | Yes | Page routing parameters. | +| mode | [RouterMode](#routermode9) | Yes | Routing mode.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found. | +| 100003 | if the pages are pushed too much. | +| 100004 | if the named route is not exist. | + +**Example** + +```ts +router.pushNamedRoute({ + name: 'myPage', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + } + } +}, router.RouterMode.Standard, (err) => { + if (err) { + console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('pushNamedRoute success'); +}) +``` + +## router.replaceNamedRoute10+ + +replaceNamedRoute(options: NamedRouterOptions): Promise<void> + +Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | ------------------ | +| options | [NamedRouterOptions](#namedrouteroptions10) | Yes | Description of the new page.| + +**Return value** + +| Type | Description | +| ------------------- | --------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found. | +| 100004 | if the named route is not exist. | + +**Example** + +```ts +router.replaceNamedRoute({ + name: 'myPage', + params: { + data1: 'message' + } +}) + .then(() => { + // success + }) + .catch(err => { + console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); + }) +``` + +## router.replaceNamedRoute10+ + +replaceNamedRoute(options: NamedRouterOptions, callback: AsyncCallback<void>): void + +Replaces the current page with another one using the named route and destroys the current page. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | ------------------ | +| options | [NamedRouterOptions](#namedrouteroptions10) | Yes | Description of the new page.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found. | +| 100004 | if the named route is not exist. | + +**Example** + +```ts +router.replaceNamedRoute({ + name: 'myPage', + params: { + data1: 'message' + } +}, (err) => { + if (err) { + console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('replaceNamedRoute success'); +}) +``` + +## router.replaceNamedRoute10+ + +replaceNamedRoute(options: NamedRouterOptions, mode: RouterMode): Promise<void> + +Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------- | +| options | [NamedRouterOptions](#namedrouteroptions10) | Yes | Description of the new page. | +| mode | [RouterMode](#routermode9) | Yes | Routing mode.| + + +**Return value** + +| Type | Description | +| ------------------- | --------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if can not get the delegate. | +| 100004 | if the named route is not exist. | + +**Example** + +```ts +router.replaceNamedRoute({ + name: 'myPage', + params: { + data1: 'message' + } +}, router.RouterMode.Standard) + .then(() => { + // success + }) + .catch(err => { + console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); + }) +``` + +## router.replaceNamedRoute10+ + +replaceNamedRoute(options: NamedRouterOptions, mode: RouterMode, callback: AsyncCallback<void>): void + +Replaces the current page with another one using the named route and destroys the current page. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------- | +| options | [NamedRouterOptions](#namedrouteroptions10) | Yes | Description of the new page. | +| mode | [RouterMode](#routermode9) | Yes | Routing mode.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | if UI execution context not found. | +| 100004 | if the named route is not exist. | + +**Example** + +```ts +router.replaceNamedRoute({ + name: 'myPage', + params: { + data1: 'message' + } +}, router.RouterMode.Standard, (err) => { + if (err) { + console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('replaceNamedRoute success'); +}); + +``` + ## router.back back(options?: RouterOptions ): void @@ -399,7 +772,7 @@ Returns to the previous page or a specified page. **Example** -```js +```ts router.back({url:'pages/detail'}); ``` @@ -413,7 +786,7 @@ Clears all historical pages in the stack and retains only the current page at th **Example** -```js +```ts router.clear(); ``` @@ -433,7 +806,7 @@ Obtains the number of pages in the current stack. **Example** -```js +```ts let size = router.getLength(); console.log('pages stack size = ' + size); ``` @@ -454,7 +827,7 @@ Obtains state information about the current page. **Example** -```js +```ts let page = router.getState(); console.log('current index = ' + page.index); console.log('current name = ' + page.name); @@ -497,15 +870,15 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc **Example** - ```js +```ts try { - router.showAlertBeforeBackPage({ - message: 'Message Info' + router.showAlertBeforeBackPage({ + message: 'Message Info' }); } catch(error) { console.error(`showAlertBeforeBackPage failed, code is ${error.code}, message is ${error.message}`); } - ``` +``` ## EnableAlertOptions Describes the confirm dialog box. @@ -526,7 +899,7 @@ Disables the display of a confirm dialog box before returning to the previous pa **Example** -```js +```ts router.hideAlertBeforeBackPage(); ``` @@ -563,7 +936,6 @@ Describes the page routing options. > **NOTE** - > > The page routing stack supports a maximum of 32 pages. ## RouterMode9+ @@ -577,11 +949,22 @@ Enumerates the routing modes. | Standard | Multi-instance mode. It is the default routing mode.
The target page is added to the top of the page stack, regardless of whether a page with the same URL exists in the stack.
**NOTE**
If the routing mode is not used, the page is redirected to in multi-instance mode.| | Single | Singleton mode.
If the URL of the target page already exists in the page stack, the page closest to the top of the stack is moved to the top and becomes a new page.
If the URL of the target page does not exist in the page stack, the page is redirected to in multi-instance mode.| +## NamedRouterOptions10+ + +Describes the named route options. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| name | string | Yes | Name of the target named route.| +| params | object | No | Data that needs to be passed to the target page during redirection. The target page can use **router.getParams()** to obtain the passed parameters, for example, **this.keyValue** (**keyValue** is the value of a key in **params**). In the web-like paradigm, these parameters can be directly used on the target page. If the field specified by **key** already exists on the target page, the passed value of the key will be displayed.| + ## Examples ### JavaScript-based Web-like Development Paradigm -```js +```ts // Current page export default { pushPage() { @@ -594,7 +977,7 @@ export default { } } ``` -```js +```ts // detail page export default { onInit() { @@ -704,7 +1087,7 @@ This API is deprecated since API version 9. You are advised to use [pushUrl **Example** -```js +```ts router.push({ url: 'pages/routerpage2', params: { @@ -734,7 +1117,7 @@ This API is deprecated since API version 9. You are advised to use [replaceUrl(deprecated) @@ -779,6 +1162,6 @@ This API is deprecated since API version 9. You are advised to use [hideAlertBef **Example** -```js -router.disableAlertBeforeBackPage(); +```ts +router.disableAlertBeforeBackPage(); ``` diff --git a/en/application-dev/reference/apis/js-apis-screen-lock.md b/en/application-dev/reference/apis/js-apis-screen-lock.md index e633bf43d4a8879701dd4d3f63f66f51a0f20425..c1136e75989e9dd2cfe00de84a9dee9c23bfb3cd 100644 --- a/en/application-dev/reference/apis/js-apis-screen-lock.md +++ b/en/application-dev/reference/apis/js-apis-screen-lock.md @@ -220,7 +220,7 @@ screenlock.lock().then((data) => { onSystemEvent(callback: Callback<SystemEvent>): boolean -Registers a callback for system events related to screen locking. This API can be called only by system screen lock applications. +Registers a callback for system events related to screen locking. This API can be called only by screen lock applications. **System capability**: SystemCapability.MiscServices.ScreenLock @@ -264,7 +264,7 @@ try { sendScreenLockEvent(event: String, parameter: number, callback: AsyncCallback<boolean>): void -Sends an event to the screen lock service. This API uses an asynchronous callback to return the result. +Sends an event to the screen lock service. This API can be called only by screen lock applications. It uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.ScreenLock @@ -304,7 +304,7 @@ screenlock.sendScreenLockEvent('unlockScreenResult', 0, (err, result) => { sendScreenLockEvent(event: String, parameter: number): Promise<boolean> -Sends an event to the screen lock service. This API uses a promise to return the result. +Sends an event to the screen lock service. This API can be called only by screen lock applications. It uses a promise to return the result. **System capability**: SystemCapability.MiscServices.ScreenLock diff --git a/en/application-dev/reference/apis/js-apis-socket.md b/en/application-dev/reference/apis/js-apis-socket.md index 39f79224b6d4514a91ef34967dd06ba90adee457..4cea6beaaec94d89b21a3e59743e54cb3d7b87d8 100644 --- a/en/application-dev/reference/apis/js-apis-socket.md +++ b/en/application-dev/reference/apis/js-apis-socket.md @@ -1766,7 +1766,7 @@ promise.then(() => { setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\): void -Sets other properties of the TCPSocket connection after successful binding of the local IP address and port number of the TLSSocket connection. This API uses an asynchronous callback to return the result. +Sets other properties of the TCPSocket connection after successful binding of the local IP address and port number of the connection. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Communication.NetStack @@ -1818,7 +1818,7 @@ tls.setExtraOptions({ setExtraOptions(options: TCPExtraOptions): Promise\ -Sets other properties of the TCPSocket connection after successful binding of the local IP address and port number of the TLSSocket connection. This API uses a promise to return the result. +Sets other properties of the TCPSocket connection after successful binding of the local IP address and port number of the connection. This API uses a promise to return the result. **System capability**: SystemCapability.Communication.NetStack diff --git a/en/application-dev/reference/apis/js-apis-stack.md b/en/application-dev/reference/apis/js-apis-stack.md index 9ecf69bced25271e1c68299bb78e2a19bbaab756..998d202a759c605a87b43997132a023a68188373 100644 --- a/en/application-dev/reference/apis/js-apis-stack.md +++ b/en/application-dev/reference/apis/js-apis-stack.md @@ -214,15 +214,15 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| -| thisArg | Object | No| Value to use when the callback is invoked.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked. The default value is this instance.| -callbackfn +callbackFn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | T | Yes| Value of the element that is currently traversed.| -| index | number | No| Position index of the element that is currently traversed.| -| stack | Stack<T> | No| Instance that invokes the **forEach** method.| +| index | number | No| Position index of the element that is currently traversed. The default value is **0**.| +| stack | Stack<T> | No| Instance that calls the **forEach** API. The default value is this instance.| **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-stationary.md b/en/application-dev/reference/apis/js-apis-stationary.md index 7f732445123bce8a0fafde50b26a36548be0eb8e..4e563fc6c366e5296dc9966cfa8ec292f632af1f 100644 --- a/en/application-dev/reference/apis/js-apis-stationary.md +++ b/en/application-dev/reference/apis/js-apis-stationary.md @@ -123,7 +123,7 @@ Unsubscribes from the device status. | -------------------- | -------------------------------------------------- | ---- | ---------------------------- | | activity | [ActivityType](#activitytype) | Yes | Device status type. | | event | [ActivityEvent](#activityevent) | Yes | Event type. | -| callback | Callback<[ActivityResponse](#activityresponse)\> | No | Callback used to receive reported data. If this parameter is not passed, all callbacks associated with the specified event in the process will be unregistered. | +| callback | Callback:\<[ActivityResponse](#activityresponse)> | No | Callback used to receive reported data, If the callback parameter is not passed or the type passed is undefined, all callbacks associated with the specified event in the process will be unregistered. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-system-battery.md b/en/application-dev/reference/apis/js-apis-system-battery.md index 8eef0562cdedb91214d4eb9e688445eb6d8ff9b8..ec63058c998fcbaeb278a7a7c3ef7fcbc4620f2d 100644 --- a/en/application-dev/reference/apis/js-apis-system-battery.md +++ b/en/application-dev/reference/apis/js-apis-system-battery.md @@ -21,7 +21,7 @@ getStatus(options?: GetStatusOptions): void; Obtains the current charging state and battery level. -**System capability**: SystemCapability.PowerManager.BatteryManager.Core +**System capability**: SystemCapability.PowerManager.BatteryManager.Lite **Parameters** @@ -46,7 +46,7 @@ battery.getStatus({ Object that contains the API calling result. -**System capability**: SystemCapability.PowerManager.BatteryManager.Core +**System capability**: SystemCapability.PowerManager.BatteryManager.Lite | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | @@ -58,7 +58,7 @@ Object that contains the API calling result. Defines a response that returns the charging status and remaining power of the device. -**System capability**: SystemCapability.PowerManager.BatteryManager.Core +**System capability**: SystemCapability.PowerManager.BatteryManager.Lite | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-system-brightness.md b/en/application-dev/reference/apis/js-apis-system-brightness.md index 01a1defec2d87411735e0ffcf30b08beb93faccf..55b0bdee44b6f421863162c3d078bd092fcfb95a 100644 --- a/en/application-dev/reference/apis/js-apis-system-brightness.md +++ b/en/application-dev/reference/apis/js-apis-system-brightness.md @@ -22,7 +22,7 @@ getValue(options?: GetBrightnessOptions): void Obtains the current screen brightness. -**System capability**: SystemCapability.PowerManager.DisplayPowerManager +**System capability**: SystemCapability.PowerManager.DisplayPowerManager.Lite **Parameters** @@ -50,7 +50,7 @@ setValue(options?: SetBrightnessOptions): void Sets the screen brightness. -**System capability**: SystemCapability.PowerManager.DisplayPowerManager +**System capability**: SystemCapability.PowerManager.DisplayPowerManager.Lite **Parameters** @@ -79,7 +79,7 @@ getMode(options?: GetBrightnessModeOptions): void Obtains the screen brightness adjustment mode. -**System capability**: SystemCapability.PowerManager.DisplayPowerManager +**System capability**: SystemCapability.PowerManager.DisplayPowerManager.Lite **Parameters** @@ -107,7 +107,7 @@ setMode(options?: SetBrightnessModeOptions): void Sets the screen brightness adjustment mode. -**System capability**: SystemCapability.PowerManager.DisplayPowerManager +**System capability**: SystemCapability.PowerManager.DisplayPowerManager.Lite **Parameters** | Name| Type| Mandatory| Description| @@ -137,7 +137,7 @@ setKeepScreenOn(options?: SetKeepScreenOnOptions): void Sets whether to always keep the screen on. Call this API in **onShow()**. -**System capability**: SystemCapability.PowerManager.DisplayPowerManager +**System capability**: SystemCapability.PowerManager.DisplayPowerManager.Lite **Parameters** @@ -162,7 +162,7 @@ Sets whether to always keep the screen on. Call this API in **onShow()**. Defines the options for obtaining the screen brightness. -**System capability**: SystemCapability.PowerManager.DisplayPowerManager +**System capability**: SystemCapability.PowerManager.DisplayPowerManager.Lite | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | @@ -174,7 +174,7 @@ Defines the options for obtaining the screen brightness. Defines the options for setting the screen brightness. -**System capability**: SystemCapability.PowerManager.DisplayPowerManager +**System capability**: SystemCapability.PowerManager.DisplayPowerManager.Lite | Name | Type | Mandatory| Description | | -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | @@ -187,7 +187,7 @@ Defines the options for setting the screen brightness. Defines a response that returns the screen brightness. -**System capability**: SystemCapability.PowerManager.DisplayPowerManager +**System capability**: SystemCapability.PowerManager.DisplayPowerManager.Lite | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -197,7 +197,7 @@ Defines a response that returns the screen brightness. Defines the options for obtaining the screen brightness mode. -**System capability**: SystemCapability.PowerManager.DisplayPowerManager +**System capability**: SystemCapability.PowerManager.DisplayPowerManager.Lite | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | @@ -209,7 +209,7 @@ Defines the options for obtaining the screen brightness mode. Defines the options for setting the screen brightness mode. -**System capability**: SystemCapability.PowerManager.DisplayPowerManager +**System capability**: SystemCapability.PowerManager.DisplayPowerManager.Lite | Name | Type | Mandatory| Description | | -------- | ------------------------------------ | ---- | ------------------------------------------------------ | @@ -222,7 +222,7 @@ Defines the options for setting the screen brightness mode. Defines a response that returns the screen brightness mode. -**System capability**: SystemCapability.PowerManager.DisplayPowerManager +**System capability**: SystemCapability.PowerManager.DisplayPowerManager.Lite | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -232,7 +232,7 @@ Defines a response that returns the screen brightness mode. Defines the options for setting the screen to be steady on. -**System capability**: SystemCapability.PowerManager.DisplayPowerManager +**System capability**: SystemCapability.PowerManager.DisplayPowerManager.Lite | Name | Type | Mandatory| Description | | ------------ | ------------------------------------ | ---- | ------------------------------------------------------ | diff --git a/en/application-dev/reference/apis/js-apis-system-parameter.md b/en/application-dev/reference/apis/js-apis-system-parameter.md index fceb893eb40373ad0f4cff2faa34c10018ccb3b8..aab6d05c91656e7b386499302e2ab11b021ba937 100644 --- a/en/application-dev/reference/apis/js-apis-system-parameter.md +++ b/en/application-dev/reference/apis/js-apis-system-parameter.md @@ -30,13 +30,13 @@ Obtains the value of the system parameter with the specified key. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | string | Yes| Key of the system parameter.| -| def | string | No| Default value of the system parameter.
It works only when the system parameter does not exist.
The value can be **undefined** (in which case an empty string will be returned) or any custom value.| +| def | string | No| Default value of the system parameter.
It works only when the system parameter does not exist.
The value can be **undefined** or any custom value. | **Return value** | Type| Description| | -------- | -------- | -| string | Value of the system parameter. If the specified key does not exist, the default value is returned. If no default value has been set, an empty string will be returned.| +| string | Value of the system parameter.
If the specified key exists, the set value is returned.
If the specified key does not exist and **def** is set to a valid value, the set value is returned. If the specified key does not exist and **def** is set to an invalid value (such as **undefined**) or is not set, an empty string is returned. | **Example** @@ -44,7 +44,7 @@ Obtains the value of the system parameter with the specified key. try { var info = systemparameter.getSync("const.ohos.apiversion"); console.log(JSON.stringify(info)); -}catch(e){ +} catch(e) { console.log("getSync unexpected error: " + e); } ``` @@ -74,7 +74,7 @@ try { } else { console.log(" get test.parameter.key value err:" + err.code) }}); -}catch(e){ +} catch(e) { console.log("get unexpected error: " + e); } ``` @@ -106,7 +106,7 @@ try { console.log(" get test.parameter.key value err:" + err.code) } }); -}catch(e){ +} catch(e) { console.log("get unexpected error:" + e) } ``` @@ -124,7 +124,7 @@ Obtains the value of the system parameter with the specified key. This API uses | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | string | Yes| Key of the system parameter.| -| def | string | No| Default value of the system parameter.
It works only when the system parameter does not exist.
The value can be **undefined** (in which case an empty string will be returned) or any custom value.| +| def | string | No| Default value of the system parameter.
It works only when the system parameter does not exist.
The value can be **undefined** or any custom value. | **Return value** @@ -142,7 +142,7 @@ try { }).catch(function (err) { console.log("get test.parameter.key error: " + err.code); }); -}catch(e){ +} catch(e) { console.log("get unexpected error: " + e); } ``` @@ -172,7 +172,7 @@ Sets a value for the system parameter with the specified key. ```ts try { systemparameter.setSync("test.parameter.key", "default"); -}catch(e){ +} catch(e) { console.log("set unexpected error: " + e); } ``` @@ -207,7 +207,7 @@ try { } else { console.log("set test.parameter.key value err:" + err.code) }}); -}catch(e){ +} catch(e) { console.log("set unexpected error: " + e); } ``` @@ -247,7 +247,7 @@ try { }).catch(function (err) { console.log(" set test.parameter.key error: " + err.code); }); -}catch(e){ +} catch(e) { console.log("set unexpected error: " + e); } ``` diff --git a/en/application-dev/reference/apis/js-apis-system-parameterEnhance.md b/en/application-dev/reference/apis/js-apis-system-parameterEnhance.md index 12f2d8448418cac174e471bee660900ceee0b8de..dabeb1bad7572458974e0330990f745c285bae0e 100644 --- a/en/application-dev/reference/apis/js-apis-system-parameterEnhance.md +++ b/en/application-dev/reference/apis/js-apis-system-parameterEnhance.md @@ -29,13 +29,13 @@ Obtains the value of the system parameter with the specified key. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | string | Yes| Key of the system parameter.| -| def | string | No| Default value of the system parameter.
It works only when the system parameter does not exist.
The value can be **undefined** (in which case an empty string will be returned) or any custom value.| +| def | string | No| Default value of the system parameter.
It works only when the system parameter does not exist.
The value can be **undefined** or any custom value. | **Return value** | Type| Description| | -------- | -------- | -| string | Value of the system parameter. If the specified key does not exist, the default value is returned. If no default value has been set, an empty string will be returned.| +| string | Value of the system parameter.
If the specified key exists, the set value is returned.
If the specified key does not exist and **def** is set to a valid value, the set value is returned. If the specified key does not exist and **def** is set to an invalid value (such as **undefined**) or is not set, an exception is thrown. | **Example** @@ -43,7 +43,7 @@ Obtains the value of the system parameter with the specified key. try { var info = systemparameter.getSync("const.ohos.apiversion"); console.log(JSON.stringify(info)); -}catch(e){ +} catch(e) { console.log("getSync unexpected error: " + e); } ``` @@ -73,7 +73,7 @@ try { } else { console.log(" get test.parameter.key value err:" + err.code) }}); -}catch(e){ +} catch(e) { console.log("get unexpected error: " + e); } ``` @@ -105,7 +105,7 @@ try { console.log(" get test.parameter.key value err:" + err.code) } }); -}catch(e){ +} catch(e) { console.log("get unexpected error:" + e) } ``` @@ -123,7 +123,7 @@ Obtains the value of the system parameter with the specified key. This API uses | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | string | Yes| Key of the system parameter.| -| def | string | No| Default value of the system parameter.
It works only when the system parameter does not exist.
The value can be **undefined** (in which case an empty string will be returned) or any custom value.| +| def | string | No| Default value of the system parameter.
It works only when the system parameter does not exist.
The value can be **undefined** or any custom value. | **Return value** @@ -141,7 +141,7 @@ try { }).catch(function (err) { console.log("get test.parameter.key error: " + err.code); }); -}catch(e){ +} catch(e) { console.log("get unexpected error: " + e); } ``` @@ -166,7 +166,7 @@ Sets a value for the system parameter with the specified key. ```ts try { systemparameter.setSync("test.parameter.key", "default"); -}catch(e){ +} catch(e) { console.log("set unexpected error: " + e); } ``` @@ -197,7 +197,7 @@ try { } else { console.log("set test.parameter.key value err:" + err.code) }}); -}catch(e){ +} catch(e) { console.log("set unexpected error: " + e); } ``` @@ -233,7 +233,7 @@ try { }).catch(function (err) { console.log(" set test.parameter.key error: " + err.code); }); -}catch(e){ +} catch(e) { console.log("set unexpected error: " + e); } ``` diff --git a/en/application-dev/reference/apis/js-apis-system-router.md b/en/application-dev/reference/apis/js-apis-system-router.md index e2e2ef013c53ec132fd73a54f6a171d84063b161..0813fbd568ea310b81ab0ed9868e0ad0302aba7c 100644 --- a/en/application-dev/reference/apis/js-apis-system-router.md +++ b/en/application-dev/reference/apis/js-apis-system-router.md @@ -343,8 +343,8 @@ Defines the page routing parameters. | Name | Type| Mandatory| Description | | ------ | -------- | ---- | ------------------------------------------------------------ | -| uri7+ | string | Yes | URI of the target page, in either of the following formats:
1. Absolute path, which is provided by the **pages** list in the **config.json** file. Example:
- pages/index/index
- pages/detail/detail
2. Specific path. If the URI is a slash (/), the home page is displayed.| -| params7+ | object | No | Data that needs to be passed to the target page during redirection. The target page can use **router.getParams()** to obtain the passed parameters, for example, **this.keyValue** (**keyValue** is the value of a key in **params**). In the web-like paradigm, these parameters can be directly used on the target page. If the field specified by **key** already exists on the target page, the passed value of the key will be displayed.| +| uri | string | Yes | URI of the target page, in either of the following formats:
1. Absolute path, which is provided by the **pages** list in the **config.json** file. Example:
- pages/index/index
- pages/detail/detail
2. Specific path. If the URI is a slash (/), the home page is displayed.| +| params | object | No | Data that needs to be passed to the target page during redirection. The target page can use **router.getParams()** to obtain the passed parameters, for example, **this.keyValue** (**keyValue** is the value of a key in **params**). In the web-like paradigm, these parameters can be directly used on the target page. If the field specified by **key** already exists on the target page, the passed value of the key will be displayed.| ## BackRouterOptions diff --git a/en/application-dev/reference/apis/js-apis-treemap.md b/en/application-dev/reference/apis/js-apis-treemap.md index f05edc6533e92d21c49cf1dd2c91b7e9aa12ff0a..38f3d0525c9d7a35b33a808e0ae8fd38ea58bf4d 100644 --- a/en/application-dev/reference/apis/js-apis-treemap.md +++ b/en/application-dev/reference/apis/js-apis-treemap.md @@ -48,7 +48,7 @@ A constructor used to create a **TreeMap** instance. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| comparator | function | No| Custom comparator.| +| comparator | function | No| Custom comparator. The default value is **hole** (a blank placeholder), indicating that no comparator. is provided.| **Error codes** @@ -611,14 +611,14 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| -| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked. The default value is this instance.| -callbackfn +callbackFn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | V | No| Value of the element that is currently traversed.| -| key | K | No| Key of the element that is currently traversed.| -| map | TreeMap | No| Instance that invokes the **forEach** method.| +| value | V | No| Value of the element that is currently traversed. The default value is the value of the first key-value pair.| +| key | K | No| Key of the element that is currently traversed. The default value is the key of the first key-value pair.| +| map | TreeMap | No| Instance that calls the **forEach** API. The default value is this instance.| **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-treeset.md b/en/application-dev/reference/apis/js-apis-treeset.md index b3259d3ccbf19fab20c027accad98c6519bf7f52..fafe6553d2469bd19badd9ec5ce0814b12b02299 100644 --- a/en/application-dev/reference/apis/js-apis-treeset.md +++ b/en/application-dev/reference/apis/js-apis-treeset.md @@ -44,7 +44,7 @@ A constructor used to create a **TreeSet** instance. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| comparator | function | No| Custom comparator.| +| comparator | function | No| Custom comparator. The default value is **hole** (a blank placeholder), indicating that no comparator. is provided.| **Error codes** @@ -484,14 +484,14 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| -| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked. The default value is this instance.| -callbackfn +callbackFn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | No| Value of the element that is currently traversed.| -| key | T | No| Key of the element that is currently traversed.| -| set | TreeSet<T> | No| Instance that invokes the **forEach** method.| +| value | T | No| Value of the element that is currently traversed. The default value is the value of the first key-value pair.| +| key | T | No| Key of the element that is currently traversed. The default value is the key of the first key-value pair.| +| set | TreeSet<T> | No| Instance that calls the **forEach** API. The default value is this instance.| **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md index 6600939a007d9ac3abd1ad964f3270445cec3a7e..c049c8f2a2a4a3cc3a37bc47c5672da9cb4bb3fe 100755 --- a/en/application-dev/reference/apis/js-apis-util.md +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -586,7 +586,7 @@ result = textEncoder.encodeInto("\uD800¥¥"); ### encodeIntoUint8Array9+ -encodeIntoUint8Array(input: string, dest: Uint8Array, ): { read: number; written: number } +encodeIntoUint8Array(input: string, dest: Uint8Array): { read: number; written: number } Stores the UTF-8 encoded text. @@ -617,7 +617,7 @@ result = that.encodeIntoUint8Array('abcd', dest) ### encodeInto(deprecated) -encodeInto(input: string, dest: Uint8Array, ): { read: number; written: number } +encodeInto(input: string, dest: Uint8Array): { read: number; written: number } Stores the UTF-8 encoded text. @@ -1100,7 +1100,7 @@ A constructor used to create a **LruCache** instance. The default capacity of th | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ---------------------------- | -| capacity | number | No | Capacity of the **LruCache** to create.| +| capacity | number | No | Capacity of the **LruCache** to create. The default value is **64**.| **Example** @@ -3400,7 +3400,7 @@ A constructor used to create a **LruBuffer** instance. The default capacity of t | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| capacity | number | No| Capacity of the **LruBuffer** to create.| +| capacity | number | No| Capacity of the **LruBuffer** to create. The default value is **64**.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-vector.md b/en/application-dev/reference/apis/js-apis-vector.md index 7e59a7685b38a014a76065ee04255b106c9d8133..137cf7bfffa33bc4035ec80d10c7e09075b00ae1 100644 --- a/en/application-dev/reference/apis/js-apis-vector.md +++ b/en/application-dev/reference/apis/js-apis-vector.md @@ -304,15 +304,15 @@ Replaces all elements in this container with new elements, and returns the new o | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callbackFn | function | Yes| Callback invoked for replacement.| -| thisArg | Object | No| Value to use when the callback is invoked.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked. The default value is this instance.| -callbackfn +callbackFn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | T | Yes| Value of the element that is currently traversed.| -| index | number | No| Position index of the element that is currently traversed.| -| vector | Vector<T> | No| Instance that invokes the **replaceAllElements** API.| +| index | number | No| Position index of the element that is currently traversed. The default value is **0**.| +| vector | Vector<T> | No| Instance that calls the **replaceAllElements** API. The default value is this instance.| **Example** @@ -342,15 +342,15 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callbackFn | function | Yes| Callback invoked for replacement.| -| thisArg | Object | No| Value to use when the callback is invoked.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked. The default value is this instance.| -callbackfn +callbackFn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | T | Yes| Value of the element that is currently traversed.| -| index | number | No| Position index of the element that is currently traversed.| -| vector | Vector<T> | No| Instance that invokes the **forEach** API.| +| index | number | No| Position index of the element that is currently traversed. The default value is **0**.| +| vector | Vector<T> | No| Instance that calls the **forEach** API. The default value is this instance.| **Example** @@ -378,7 +378,7 @@ Sorts elements in this container. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| comparator | function | No| Callback invoked for sorting.| +| comparator | function | No| Callback invoked for sorting. The default value is this instance.| comparator diff --git a/en/application-dev/reference/apis/js-apis-vibrator.md b/en/application-dev/reference/apis/js-apis-vibrator.md index 46e6f69db5327502add3c26ba6fd6b897868fc0c..c0e2de3e09ae03dfb4a5e76c0e727e37856e807c 100644 --- a/en/application-dev/reference/apis/js-apis-vibrator.md +++ b/en/application-dev/reference/apis/js-apis-vibrator.md @@ -460,8 +460,9 @@ Describes the vibration effect. | Type | Description | | -------------------------------- | ------------------------------ | -| [VibrateTime](#vibratetime9) | Triggers vibration with the specified duration. This API uses a promise to return the result.| +| [VibrateTime](#vibratetime9) | Vibration with the specified duration.| | [VibratePreset](#vibratepreset9) | Vibration with a preset effect.| +| [VibrateFromFile10+](#vibratefromfile10) | Vibration according to a custom vibration configuration file.| ## VibrateTime9+ @@ -469,10 +470,10 @@ Describes the vibration with the specified duration. **System capability**: SystemCapability.Sensors.MiscDevice -| Name | Value| Description | -| -------- | ------ | ------------------------------ | -| type | "time" | Vibration with the specified duration.| -| duration | - | Vibration duration, in ms. | +| Name | Type | Mandatory| Description | +| -------- | ------ | ----- | ------------------------------ | +| type | string | Yes | The value **time** means vibration with the specified duration.| +| duration | number | Yes | Vibration duration, in ms. | ## VibratePreset9+ @@ -480,11 +481,34 @@ Describes the vibration with a preset effect. **System capability**: SystemCapability.Sensors.MiscDevice -| Name | Value | Description | -| -------- | -------- | ------------------------------ | -| type | "preset" | Vibration with the specified effect.| -| effectId | - | Preset vibration effect ID. | -| count | - | Number of vibrations to repeat. | +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- |------------------------------ | +| type | string | Yes | The value **preset** means vibration with the specified effect.| +| effectId | string | Yes | Preset vibration effect ID. | +| count | number | Yes | Number of vibrations to repeat. | + +## VibrateFromFile10+ + +Describes the custom vibration type, which is supported only by certain devices. + +**System capability**: SystemCapability.Sensors.MiscDevice + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------ | +| type | string | Yes | The value **file** means vibration according to a vibration configuration file.| +| hapticFd | [HapticFileDescriptor](#hapticfiledescriptor10) | Yes| File descriptor (FD) of the vibration configuration file.| + +## HapticFileDescriptor10+ + +Describes the FD of a custom vibration configuration file. Ensure that the file is available, and the parameters in it can be obtained from the sandbox path through the [file management API](js-apis-file-fs.md#fsopen) or from the HAP resource through the [resource management API](js-apis-resource-manager.md#getrawfd9). The use case is as follows: The system triggers vibration according to the sequence set in a configuration file, based on the specified offset and length. For details about the storage format of the vibration sequence, see [Custom Vibration Format](../../device/vibrator-guidelines.md#custom-vibration-format). + +**System capability**: SystemCapability.Sensors.MiscDevice + +| Name | Type | Mandatory | Description | +| -------- | -------- |--------| ------------------------------| +| fd | number | Yes | FD of the custom vibration configuration file. | +| offset | number | No | Offset from the start position of the file, in bytes. The default value is the start position of the file, and the value cannot exceed the valid range of the file.| +| length | number | No | Resource length, in bytes. The default value is the length from the offset position to the end of the file, and the value cannot exceed the valid range of the file.| ## VibrateAttribute9+ @@ -492,10 +516,10 @@ Describes the vibration attribute. **System capability**: SystemCapability.Sensors.MiscDevice -| Name | Value| Description | -| ----- | ------ | -------------- | -| id | 0 | Vibrator ID. | -| usage | - | Vibration scenario.| +| Name | Type| Mandatory| Description | +| ----- | ------ | ---- | -------------- | +| id | number | No| Vibrator ID. The default value is 0. | +| usage | [Usage](#usage9) | Yes| Vibration scenario.| ## Usage9+ diff --git a/en/application-dev/reference/apis/js-apis-wantAgent.md b/en/application-dev/reference/apis/js-apis-wantAgent.md index f30132640cd3a5a5832df9761c2a7e659e9dfa59..0ebee19d694e73ad71e6c3a1f54edfb7108c7378 100644 --- a/en/application-dev/reference/apis/js-apis-wantAgent.md +++ b/en/application-dev/reference/apis/js-apis-wantAgent.md @@ -159,7 +159,7 @@ WantAgent.getWantAgent(wantAgentInfo).then((data) => { getWantAgent(info: WantAgentInfo, callback: AsyncCallback\): void -Obtains a **WantAgent** object. This API uses an asynchronous callback to return the result. If the creation fails, a null **WantAgent** object is returned. +Creates a **WantAgent** object. This API uses an asynchronous callback to return the result. If the creation fails, a null **WantAgent** object is returned. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -167,7 +167,7 @@ Obtains a **WantAgent** object. This API uses an asynchronous callback to return | Name | Type | Mandatory| Description | | -------- | -------------------------- | ---- | ----------------------- | -| info | [WantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) | Yes | Information about the **WantAgent** object to obtain. | +| info | [WantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) | Yes | Information about the **WantAgent** object. | | callback | AsyncCallback\ | Yes | Callback used to return the **WantAgent** object.| **Example** @@ -218,7 +218,7 @@ WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); getWantAgent(info: WantAgentInfo): Promise\ -Obtains a **WantAgent** object. This API uses a promise to return the result. If the creation fails, a null **WantAgent** object is returned. +Creates a **WantAgent** object. This API uses a promise to return the result. If the creation fails, a null **WantAgent** object is returned. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -226,7 +226,7 @@ Obtains a **WantAgent** object. This API uses a promise to return the result. If | Name| Type | Mandatory| Description | | ---- | ------------- | ---- | ------------- | -| info | [WantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) | Yes | Information about the **WantAgent** object to obtain.| +| info | [WantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) | Yes | Information about the **WantAgent** object.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-webview.md b/en/application-dev/reference/apis/js-apis-webview.md index 956f922e5414eb058e15ac7f52daba1c8d8db8cf..a5334a26084d30eafb4f914ea3f7fe8d457267f7 100644 --- a/en/application-dev/reference/apis/js-apis-webview.md +++ b/en/application-dev/reference/apis/js-apis-webview.md @@ -63,42 +63,6 @@ struct WebComponent { Implements a **WebMessagePort** object to send and receive messages. -### close - -close(): void - -Closes this message port. - -**System capability**: SystemCapability.Web.Webview.Core - -**Example** - -```ts -// xxx.ets -import web_webview from '@ohos.web.webview' - -@Entry -@Component -struct WebComponent { - controller: web_webview.WebviewController = new web_webview.WebviewController(); - msgPort: web_webview.WebMessagePort[] = null; - - build() { - Column() { - Button('close') - .onClick(() => { - if (this.msgPort && this.msgPort[1]) { - this.msgPort[1].close(); - } else { - console.error("msgPort is null, Please initialize first"); - } - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } -} -``` - ### postMessageEvent postMessageEvent(message: WebMessage): void @@ -364,6 +328,7 @@ struct WebComponent { } ``` +HTML file to be loaded: ```html @@ -448,6 +413,56 @@ function postStringToApp() { } ``` +### close + +close(): void + +Closes this message port. To use this API, a message port must first be created using [createWebMessagePorts](#createwebmessageports). + +**System capability**: SystemCapability.Web.Webview.Core + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + msgPort: web_webview.WebMessagePort[] = null; + + build() { + Column() { + // Use createWebMessagePorts to create a message port. + Button('createWebMessagePorts') + .onClick(() => { + try { + this.msgPort = this.controller.createWebMessagePorts(); + console.log("createWebMessagePorts size:" + this.msgPort.length) + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Button('close') + .onClick(() => { + try { + if (this.msgPort && this.msgPort.length == 2) { + this.msgPort[1].close(); + } else { + console.error("msgPort is null, Please initialize first"); + } + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + ## WebviewController Implements a **WebviewController** to control the behavior of the **\** component. A **WebviewController** can control only one **\** component, and the APIs (except static APIs) in the **WebviewController** can be invoked only after it has been bound to the target **\** component. @@ -473,7 +488,6 @@ export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { console.log("EntryAbility onCreate") web_webview.WebviewController.initializeWebEngine() - globalThis.abilityWant = want console.log("EntryAbility onCreate done") } } @@ -516,30 +530,11 @@ export default class EntryAbility extends UIAbility { } ``` -### Creating an Object - -```ts -// xxx.ets -import web_webview from '@ohos.web.webview'; - -@Entry -@Component -struct WebComponent { - controller: web_webview.WebviewController = new web_webview.WebviewController(); - - build() { - Column() { - Web({ src: 'www.example.com', controller: this.controller }) - } - } -} -``` - ### setWebDebuggingAccess static setWebDebuggingAccess(webDebuggingAccess: boolean): void -Sets whether to enable web debugging. +Sets whether to enable web debugging. For details, see [Debugging Frontend Pages by Using DevTools](../../web/web-debugging-with-devtools.md). **System capability**: SystemCapability.Web.Webview.Core @@ -656,70 +651,73 @@ struct WebComponent { ``` There are three methods for loading local resource files: -1. Using $rawfile -```ts -// xxx.ets -import web_webview from '@ohos.web.webview' -@Entry -@Component -struct WebComponent { - controller: web_webview.WebviewController = new web_webview.WebviewController(); +1. Using $rawfile + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('loadUrl') + .onClick(() => { + try { + // Load a local resource file through $rawfile. + this.controller.loadUrl($rawfile('index.html')); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } + } + ``` - build() { - Column() { - Button('loadUrl') - .onClick(() => { - try { - // Load a local resource file through $rawfile. - this.controller.loadUrl($rawfile('xxx.html')); - } catch (error) { - console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); - } - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } -} -``` 2. Using the resources protocol -```ts -// xxx.ets -import web_webview from '@ohos.web.webview' - -@Entry -@Component -struct WebComponent { - controller: web_webview.WebviewController = new web_webview.WebviewController(); - - build() { - Column() { - Button('loadUrl') - .onClick(() => { - try { - // Load a local resource file through the resource protocol. - this.controller.loadUrl("resource://rawfile/xxx.html"); - } catch (error) { - console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); - } - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } -} -``` + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('loadUrl') + .onClick(() => { + try { + // Load a local resource file through the resource protocol. + this.controller.loadUrl("resource://rawfile/index.html"); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } + } + ``` 3. Using a sandbox path. For details, see the example of loading local resource files in the sandbox in [Web](../arkui-ts/ts-basic-components-web.md#web). -```html - - - - -

Hello World

- - -``` + HTML file to be loaded: + ```html + + + + +

Hello World

+ + + ``` ### loadData @@ -1343,6 +1341,24 @@ struct Index { } ``` +HTML file to be loaded: +```html + + + + + + Hello world! + + + +``` + ### runJavaScript runJavaScript(script: string, callback : AsyncCallback\): void @@ -1406,6 +1422,24 @@ struct WebComponent { } ``` +HTML file to be loaded: +```html + + + + + + Hello world! + + + +``` + ### runJavaScript runJavaScript(script: string): Promise\ @@ -1444,11 +1478,9 @@ import web_webview from '@ohos.web.webview' @Component struct WebComponent { controller: web_webview.WebviewController = new web_webview.WebviewController(); - @State webResult: string = ''; build() { Column() { - Text(this.webResult).fontSize(20) Web({ src: $rawfile('index.html'), controller: this.controller }) .javaScriptAccess(true) .onPageEnd(e => { @@ -1470,6 +1502,23 @@ struct WebComponent { } ``` +HTML file to be loaded: +```html + + + + + + Hello world! + + + +``` ### runJavaScriptExt10+ @@ -1569,8 +1618,11 @@ struct WebComponent { } } } +``` -//index.html +HTML file to be loaded: +```html + @@ -1681,8 +1733,11 @@ struct WebComponent { } } } +``` -//index.html +HTML file to be loaded: +```html + @@ -2178,14 +2233,15 @@ struct WebComponent { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); } }) - Web({ src: $rawfile('xxx.html'), controller: this.controller }) + Web({ src: $rawfile('index.html'), controller: this.controller }) } } } ``` +HTML file to be loaded: ```html - + @@ -2973,14 +3029,15 @@ struct WebComponent { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); } }) - Web({ src: 'www.example.com', controller: this.controller }) + Web({ src: $rawfile('index.html'), controller: this.controller }) } } } ``` +HTML file to be loaded: ```html - + @@ -3045,14 +3102,15 @@ struct WebComponent { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); } }) - Web({ src: 'www.example.com', controller: this.controller }) + Web({ src: $rawfile('index.html'), controller: this.controller }) } } } ``` +HTML file to be loaded: ```html - + @@ -3117,14 +3175,15 @@ struct WebComponent { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); } }) - Web({ src: 'www.example.com', controller: this.controller }) + Web({ src: $rawfile('index.html'), controller: this.controller }) } } } ``` +HTML file to be loaded: ```html - + @@ -3640,7 +3699,7 @@ struct WebComponent { .onClick(() => { try { let state = this.controller.serializeWebState(); - // Obtain the value of globalThis.cacheDir from MainAbility.ts. + // globalThis.cacheDir is obtained from EntryAbility.ts. let path = globalThis.cacheDir; path += '/WebState'; // Synchronously open a file. @@ -3657,14 +3716,14 @@ struct WebComponent { } ``` -2. Modify **MainAbility.ts**. +2. Modify the **EntryAbility.ts** file. Obtain the path of the application cache file. ```ts // xxx.ts import UIAbility from '@ohos.app.ability.UIAbility'; import web_webview from '@ohos.web.webview'; -export default class MainAbility extends UIAbility { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { // Bind cacheDir to the globalThis object to implement data synchronization between the UIAbility component and the page. globalThis.cacheDir = this.context.cacheDir; @@ -3712,7 +3771,7 @@ struct WebComponent { Button('RestoreWebState') .onClick(() => { try { - // Obtain the value of globalThis.cacheDir from MainAbility.ts. + // globalThis.cacheDir is obtained from EntryAbility.ts. let path = globalThis.cacheDir; path += '/WebState'; // Synchronously open a file. @@ -3739,14 +3798,14 @@ struct WebComponent { } ``` -2. Modify **MainAbility.ts**. +2. Modify the **EntryAbility.ts** file. Obtain the path of the application cache file. ```ts // xxx.ts import UIAbility from '@ohos.app.ability.UIAbility'; import web_webview from '@ohos.web.webview'; -export default class MainAbility extends UIAbility { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { // Bind cacheDir to the globalThis object to implement data synchronization between the UIAbility component and the page. globalThis.cacheDir = this.context.cacheDir; @@ -6230,6 +6289,9 @@ Describes the mode in which the **\** component uses HTTPDNS. | Name | Value| Description | | ------------- | -- |----------------------------------------- | -| Off | 0 |HTTPDNS is not used. This value can be used to revoke the previously used HTTPDNS configuration.| -| Auto | 1 |HTTPDNS is used in automatic mode. When the specified HTTPDNS server is unavailable for resolution, the component will fall back to the system DNS server.| -| SecureOnly | 2 |The specified HTTPDNS server is forcibly used for DNS resolution.| +| Off(deprecated) | 0 |HTTPDNS is not used. This value can be used to revoke the previously used HTTPDNS configuration.
This API is deprecated since API version 10. You are advised to use **OFF** instead.| +| Auto(deprecated) | 1 |HTTPDNS is used in automatic mode. When the specified HTTPDNS server is unavailable for resolution, the component will fall back to the system DNS server.
This API is deprecated since API version 10. You are advised to use **AUTO** instead.| +| SecureOnly(deprecated) | 2 |The specified HTTPDNS server is forcibly used for DNS resolution.
This API is deprecated since API version 10. You are advised to use **SECURE_ONLY** instead.| +| OFF | 0 |HTTPDNS is not used. This value can be used to revoke the previously used HTTPDNS configuration.| +| AUTO | 1 |HTTPDNS is used in automatic mode. When the specified HTTPDNS server is unavailable for resolution, the component will fall back to the system DNS server.| +| SECURE_ONLY | 2 |The specified HTTPDNS server is forcibly used for DNS resolution.| diff --git a/en/application-dev/reference/apis/js-apis-xml.md b/en/application-dev/reference/apis/js-apis-xml.md index f8e8f0fff5917b56be67e1f3ab0b21ac949e7ee3..9554f5b07dd9f131c81c7ef8e30df9813cc303e9 100644 --- a/en/application-dev/reference/apis/js-apis-xml.md +++ b/en/application-dev/reference/apis/js-apis-xml.md @@ -381,6 +381,7 @@ Creates and returns an **XmlPullParser** object. **Example** ```js +import util from '@ohos.util'; let strXml = '' + ']>' + @@ -432,6 +433,7 @@ Parses XML information. **Example** ```js +import util from '@ohos.util'; let strXml = '' + '' + @@ -499,6 +501,7 @@ Obtains the column line number, starting from 1. **Example** ```js +import util from '@ohos.util'; let strXml = '' + '' + @@ -542,6 +545,7 @@ Obtains the depth of this element. **Example** ```js +import util from '@ohos.util'; let strXml = '' + '' + @@ -588,6 +592,7 @@ Obtains the current line number, starting from 1. **Example** ```js +import util from '@ohos.util'; let strXml = '' + '' + @@ -631,6 +636,7 @@ Obtains the name of this element. **Example** ```js +import util from '@ohos.util'; let strXml = '' + '' + @@ -673,6 +679,7 @@ Obtains the namespace of this element. **Example** ```js +import util from '@ohos.util'; let strXml = '' + '' + @@ -715,6 +722,7 @@ Obtains the prefix of this element. **Example** ```js +import util from '@ohos.util'; let strXml = '' + '' + @@ -758,6 +766,7 @@ Obtains the text of the current event. **Example** ```js +import util from '@ohos.util'; let strXml = '' + '' + @@ -800,6 +809,7 @@ Checks whether the current element is empty. **Example** ```js +import util from '@ohos.util'; let strXml = '' + '' + @@ -842,6 +852,7 @@ Checks whether the current text event contains only whitespace characters. **Example** ```js +import util from '@ohos.util'; let strXml = '' + '' + @@ -883,6 +894,7 @@ Obtains the number of attributes for the current start tag. **Example** ```js +import util from '@ohos.util'; let strXml = '' + '' + diff --git a/en/application-dev/reference/arkui-ts/Readme-EN.md b/en/application-dev/reference/arkui-ts/Readme-EN.md index a1408eba5cdd14511f6f1be10288e9c641bd8522..73185af7a0eab5d5f6de27b0d28589d28baed876 100644 --- a/en/application-dev/reference/arkui-ts/Readme-EN.md +++ b/en/application-dev/reference/arkui-ts/Readme-EN.md @@ -152,6 +152,7 @@ - [ImageBitmap](ts-components-canvas-imagebitmap.md) - [ImageData](ts-components-canvas-imagedata.md) - [Matrix2D](ts-components-canvas-matrix2d.md) + - [OffscreenCanvas](ts-components-offscreencanvas.md) - [OffscreenCanvasRenderingContext2D](ts-offscreencanvasrenderingcontext2d.md) - [Path2D](ts-components-canvas-path2d.md) - Animation diff --git a/en/application-dev/reference/arkui-ts/figures/DataPickerDialog.gif b/en/application-dev/reference/arkui-ts/figures/DataPickerDialog.gif new file mode 100644 index 0000000000000000000000000000000000000000..e447f0d8916e19385da7f38e1c4b15334e4a6a70 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/DataPickerDialog.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/TextPickerDialog.gif b/en/application-dev/reference/arkui-ts/figures/TextPickerDialog.gif new file mode 100644 index 0000000000000000000000000000000000000000..de15f47d3d9e9f18794c7fe92ce060bf2aa135e8 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/TextPickerDialog.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/TimePickerDialog.gif b/en/application-dev/reference/arkui-ts/figures/TimePickerDialog.gif new file mode 100644 index 0000000000000000000000000000000000000000..44fe3a771a01e9fec2e155663c1f2f552d202b68 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/TimePickerDialog.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/arkts-progress.png b/en/application-dev/reference/arkui-ts/figures/arkts-progress.png new file mode 100644 index 0000000000000000000000000000000000000000..8e16510ddae266f037cce57857c3dc2ecc14ce2e Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/arkts-progress.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/deleteListItem.gif b/en/application-dev/reference/arkui-ts/figures/deleteListItem.gif new file mode 100644 index 0000000000000000000000000000000000000000..5c2c529ef670b83df2e4bd261bbddfe6bca7e7ef Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/deleteListItem.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_1501929990650.jpg b/en/application-dev/reference/arkui-ts/figures/en-us_image_1501929990650.jpg deleted file mode 100644 index ca0ec86c6c71b6c6daa60bf3ee43795f33568c64..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_1501929990650.jpg and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/progress.png b/en/application-dev/reference/arkui-ts/figures/progress.png deleted file mode 100644 index d50f4b47628b425b09f93bc9a44853ad79e12631..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/progress.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/radio.gif b/en/application-dev/reference/arkui-ts/figures/radio.gif index 23e0e828f6ea0a1953ef754fc8623523c99114de..cef6af5813afd7dbdb8a5ee3efa692f00a625237 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/radio.gif and b/en/application-dev/reference/arkui-ts/figures/radio.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/searchButton.gif b/en/application-dev/reference/arkui-ts/figures/searchButton.gif new file mode 100644 index 0000000000000000000000000000000000000000..531dac026db8144d4f87f70f593c4193a4e870bc Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/searchButton.gif differ diff --git a/en/application-dev/reference/arkui-ts/ts-appendix-enums.md b/en/application-dev/reference/arkui-ts/ts-appendix-enums.md index 35b8c458af2de6981fb47703039e07ee47b3a6b1..0753b4ab4dc8028e3747f8905b1032f2a099bcfc 100644 --- a/en/application-dev/reference/arkui-ts/ts-appendix-enums.md +++ b/en/application-dev/reference/arkui-ts/ts-appendix-enums.md @@ -557,3 +557,10 @@ This API is supported in ArkTS widgets. | LIGHT | Small area (light)| Spring effect, with stiffness of 410, damping of 38, and initial velocity of 1.| 90% | | MIDDLE | Medium area (stable)| Spring effect, with stiffness of 350, damping of 35, and initial velocity of 0.5.| 95% | | HEAVY | Large area (heavy)| Spring effect, with stiffness of 240, damping of 28, and initial velocity of 0.| 95% | + +## TextContentStyle10+ + +| Name | Description | +| ------- | ------------------------------------------------------------ | +| DEFAULT | Default style. The caret width is fixed at 1.5 vp, and the caret height is subject to the background height and font size of the selected text.| +| INLINE | Inline input style. The background height of the selected text is the same as the height of the text box. | diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md b/en/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md index e5aa84e29ece1a1a11f91a0a66fc6526bdc1b2ab..bb8c77dd981948116af501bcd05378fd75503200 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md @@ -30,12 +30,12 @@ Creates a date picker in the given date range. In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name | Type | Description | -| -------------------------------- | ---------------------------------------- | ---------------------------------------- | -| lunar | boolean | Whether to display the lunar calendar.
- **true**: Display the lunar calendar.
- **false**: Do not display the lunar calendar.
Default value: **false**| -| disappearTextStyle10+ | [PickerTextStyle](#pickertextstyle10) | Font color, font size, and font width for the top and bottom items. | -| textStyle10+ | [PickerTextStyle](#pickertextstyle10) | Font color, font size, and font width of all items except the top, bottom, and selected items. | -| selectedTextStyle10+ | [PickerTextStyle](#pickertextstyle10) | Font color, font size, and font width of the selected item. | +| Name | Type | Description | +| -------------------------------- | --------------------------------------------- | ------------------------------------------------------------ | +| lunar | boolean | Whether to display the lunar calendar.
- **true**: Display the lunar calendar.
- **false**: Do not display the lunar calendar.
Default value: **false**| +| disappearTextStyle10+ | [PickerTextStyle](#pickertextstyle10) | Font color, font size, and font width for the top and bottom items.
Default value:
{
color: '#ff182431',
font: {
size: '14fp',
weight: FontWeight.Regular
}
} | +| textStyle10+ | [PickerTextStyle](#pickertextstyle10) | Font color, font size, and font width of all items except the top, bottom, and selected items.
Default value:
{
color: '#ff182431',
font: {
size: '16fp',
weight: FontWeight.Regular
}
} | +| selectedTextStyle10+ | [PickerTextStyle](#pickertextstyle10) | Font color, font size, and font width of the selected item.
Default value:
{
color: '#ff007dff',
font: {
size: '20vp',
weight: FontWeight.Medium
}
} | ## PickerTextStyle10+ diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-divider.md b/en/application-dev/reference/arkui-ts/ts-basic-components-divider.md index f2c85939598b88cf371efdb21c6f7389992e7ee5..7428f4d9be2f17a6c591527137341fcbb46be3aa 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-divider.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-divider.md @@ -26,7 +26,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | ----------- | ---------- | ------------------ | | vertical | boolean | Whether a vertical divider is used. **false**: A horizontal divider is used.
**true**: A vertical divider is used.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| | color | [ResourceColor](ts-types.md#resourcecolor) | Color of the divider.
Default value: **'\#33182431'**
Since API version 9, this API is supported in ArkTS widgets.| -| strokeWidth | number \| string | Width of the divider.
Default value: **1**
Unit: vp
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute cannot be set to a percentage. The priority of this attribute is lower than that of the universal attribute [height](ts-universal-attributes-size.md). If the value of this attribute is greater than that of the universal attribute, cropping is performed based on the universal attribute settings.| +| strokeWidth | number \| string | Width of the divider.
Default value: **1px**
Unit: vp
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute cannot be set to a percentage. The priority of this attribute is lower than that of the universal attribute [height](ts-universal-attributes-size.md). If the value of this attribute is greater than that of the universal attribute, cropping is performed based on the universal attribute settings.| | lineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | Cap style of the divider.
Default value: **LineCapStyle.Butt**
Since API version 9, this API is supported in ArkTS widgets.| diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-image.md b/en/application-dev/reference/arkui-ts/ts-basic-components-image.md index ad23abd051a1cae666be7b4038e86fba30147fcc..2a0e870a9d2be12b1202e3ed36d53f7e22480a49 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-image.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-image.md @@ -21,7 +21,7 @@ Not supported Image(src: PixelMap | ResourceStr | DrawableDescriptor) -Obtains an image from the specified source for subsequent rendering and display. +Obtains an image from the specified source for subsequent rendering and display. If the **\** component fails to obtain the image or the obtained image size is 0, the **\** component is automatically resized to 0 and does not follow the layout constraints of its parent component. Since API version 9, this API is supported in ArkTS widgets. @@ -29,7 +29,7 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Description | | ---- | ---------------------------------------- | ---- | ---------------------------------------- | -| src | [PixelMap](../apis/js-apis-image.md#pixelmap7) \| ResourceStr\| [DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor) | Yes | Image source. Both local and online images are supported.
When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **\** component cannot be called across bundles or modules. Therefore, you are advised to use **\$r** to reference image resources that need to be used globally.
- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.
\- Base64 strings are supported. The value format is data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], where [base64 data] is a Base64 string.
\- Strings with the **datashare://** prefix are supported, which are used to access the image path provided by a Data ability.
\- Strings with the **file:///data/storage** prefix are supported, which are used to read image resources in the **files** folder in the installation directory of the current application. Ensure that the application has the read permission to the files in the specified path.
\- [DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor) objects are supported.
- For details, see [Displaying Images](../../ui/arkts-graphics-display.md).
**NOTE**
- ArkTS widgets support GIF animations, but the animations only play once on display.
- ArkTS widgets do not support the strings with the **http://**, **datashare://**, or **file:///data/storage** prefix.
- ArkTS widgets do not support the [PixelMap](../apis/js-apis-image.md#pixelmap7) type.| +| src | [PixelMap](../apis/js-apis-image.md#pixelmap7) \|ResourceStr\| [DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor) | Yes | Image source. Both local and online images are supported.
When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **\** component cannot be called across bundles or modules. Therefore, you are advised to use **\$r** to reference image resources that need to be used globally.
- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.
\- Base64 strings are supported. The value format is data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], where [base64 data] is a Base64 string.
\- Strings with the **datashare://** prefix are supported, which are used to access the image path provided by a Data ability.
\- Strings with the **file:///data/storage** prefix are supported, which are used to read image resources in the **files** folder in the installation directory of the current application. Ensure that the application has the read permission to the files in the specified path.
\- [DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor) objects are supported.
- For details, see [Displaying Images](../../ui/arkts-graphics-display.md).
**NOTE**
- ArkTS widgets support GIF animations, but the animations only play once on display.
- ArkTS widgets do not support the strings with the **http://**, **datashare://**, or **file:///data/storage** prefix.
- ArkTS widgets do not support the [PixelMap](../apis/js-apis-image.md#pixelmap7) type.| ## Attributes @@ -50,7 +50,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | syncLoad8+ | boolean | Whether to load the image synchronously. By default, the image is loaded asynchronously. During synchronous loading, the UI thread is blocked and the placeholder diagram is not displayed.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| | copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether the image can be copied. (SVG images cannot be copied.)
When **copyOption** is set to a value other than **CopyOptions.None**, the image can be copied in various manners, such as long pressing, right-clicking, or pressing Ctrl+C.
Default value: **CopyOptions.None**
This API is supported in ArkTS widgets.| | colorFilter9+ | [ColorFilter](ts-types.md#colorfilter9) | Color filter of the image.
This API is supported in ArkTS widgets. | -| draggable9+ | boolean | Whether the image is draggable. This attribute cannot be used together with the [onDragStart](ts-universal-events-drag-drop.md) event.
Default value: **false**
This API is supported in ArkTS widgets.| +| draggable(deprecated) | boolean | Whether the image is draggable. This attribute cannot be used together with the [onDragStart](ts-universal-events-drag-drop.md) event.
Default value: **false**
This API is supported in ArkTS widgets.
**NOTE**
This API is supported since API version 8 and deprecated since API version 10. You are advised to use the universal attribute [draggable](ts-universal-events-drag-drop.md) instead.| > **NOTE** > diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-progress.md b/en/application-dev/reference/arkui-ts/ts-basic-components-progress.md index 459984f79d30f81c7d9d276077038972f743a201..ef810a8be61e6dc14a8ccba62714a3f8bbe1b06e 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-progress.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-progress.md @@ -1,6 +1,6 @@ # Progress -The **\** component is used to provide a progress indicator that displays the progress of content loading or an operation. +The **\** component represents a progress indicator that displays the progress of content loading or an operation. > **NOTE** > @@ -22,47 +22,77 @@ Since API version 9, this API is supported in ArkTS widgets. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | number | Yes| Current progress. If the value is less than 0, the value **0** is used. If the value is greater than that of **total**, the value of **total** is used.
Since API version 9, this API is supported in ArkTS widgets.| -| total | number | No| Total progress.
Default value: **100**
Since API version 9, this API is supported in ArkTS widgets.| -| type8+ | [ProgressType](#progresstype) | No| Style the progress indicator.
Default value: **ProgressType.Linear**
Since API version 9, this API is supported in ArkTS widgets.| -| styledeprecated | [ProgressStyle](#progressstyle) | No| Type of the progress indicator.
This parameter is deprecated since API version 8. You are advised to use **type** instead.
Default value: **ProgressStyle.Linear**| +| Name | Type | Mandatory | Description | +| -------------------------- | ----------------------------------- | ---- | ---------------------------------------- | +| value | number | Yes | Current progress. If the value is less than 0, the value **0** is used. If the value is greater than that of **total**, the value of **total** is used.
Since API version 9, this API is supported in ArkTS widgets.| +| total | number | No | Total progress.
Default value: **100**
Since API version 9, this API is supported in ArkTS widgets.| +| type8+ | [ProgressType](#progresstype) | No | Style of the progress indicator.
Default value: **ProgressType.Linear**
Since API version 9, this API is supported in ArkTS widgets.| +| styledeprecated | [ProgressStyle](#progressstyle) | No | Style of the progress indicator.
This parameter is deprecated since API version 8. You are advised to use **type** instead.
Default value: **ProgressStyle.Linear**| ## ProgressType Since API version 9, this API is supported in ArkTS widgets. -| Name| Description| -| -------- | -------- | -| Linear | Linear type. Since API version 9, the progress indicator adaptively switches to vertical layout if the height is greater than the width.| -| Ring8+ | Indeterminate ring type. The ring fills up as the progress increases.| -| Eclipse8+ | Eclipse type, which visualizes the progress in a way similar to the moon waxing from new to full.| -| ScaleRing8+ | Determinate ring type, which is similar to the clock scale. Since API version 9, when the outer circles of scales overlap, the progress indicator is automatically converted to the **Ring** type.| -| Capsule8+ | Capsule type. At both ends, the progress indicator works in a same manner as the eclipse type. In the middle part of the capsule, the progress indicator works in a same manner as the linear type. If the height is greater than the width, the progress indicator adaptively switches to vertical layout.| +| Name | Description | +| ---------------------- | ---------------------------------------- | +| Linear | Linear style. Since API version 9, the progress indicator adaptively switches to vertical layout if the height is greater than the width. | +| Ring8+ | Indeterminate ring style. The ring fills up as the progress increases. | +| Eclipse8+ | Eclipse style, which visualizes the progress in a way similar to the moon waxing from new to full. | +| ScaleRing8+ | Determinate ring style, which is similar to the clock scale. Since API version 9, when the outer circles of scales overlap, the progress indicator is automatically converted to the **Ring** style.| +| Capsule8+ | Capsule style. At both ends, the progress indicator works in a same manner as the eclipse style. In the middle part of the capsule, the progress indicator works in a same manner as the linear style. If the height is greater than the width, the progress indicator adaptively switches to vertical layout.| ## ProgressStyle Since API version 9, this API is supported in ArkTS widgets. -| Name | Description | -| --------- | ------------------------------------------------------------ | -| Linear | Linear type.| -| Ring | Indeterminate ring type. The ring fills up as the progress increases.| -| Eclipse | Eclipse type, which visualizes the progress in a way similar to the moon waxing from new to full.| -| ScaleRing | Determinate ring type, which is similar to the clock scale.| -| Capsule | Capsule type. At both ends, the progress indicator works in a same manner as the eclipse type. In the middle part of the capsule, the progress indicator works in a same manner as the linear type. If the height is greater than the width, the progress indicator adaptively switches to vertical layout.| +| Name | Description | +| --------- | ---------------------------------------- | +| Linear | Linear style. | +| Ring | Indeterminate ring style. The ring fills up as the progress increases. | +| Eclipse | Eclipse style, which visualizes the progress in a way similar to the moon waxing from new to full. | +| ScaleRing | Determinate ring style, which is similar to the clock scale. | +| Capsule | Capsule style. At both ends, the progress indicator works in a same manner as the eclipse style. In the middle part of the capsule, the progress indicator works in a same manner as the linear style. If the height is greater than the width, the progress indicator adaptively switches to vertical layout.| ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name| Type| Description| -| -------- | -------- | -------- | -| value | number | Current progress. If the value is less than 0, the value **0** is used. If the value is greater than that of **total**, the value of **total** is used. Invalid values do not take effect.
Since API version 9, this API is supported in ArkTS widgets.| -| color | [ResourceColor](ts-types.md#resourcecolor) | Background color of the progress indicator.
Default value: **'\#ff007dff'**
Since API version 9, this API is supported in ArkTS widgets.| -| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the progress indicator.
Default value: **'\#19182431'**

Since API version 9, this API is supported in ArkTS widgets.| -| style8+ | {
strokeWidth?: [Length](ts-types.md#length),
scaleCount?: number,
scaleWidth?: [Length](ts-types.md#length)
} | Component style.
- **strokeWidth**: stroke width of the progress indicator. It cannot be set in percentage. Since API version 9, if the stroke width of the ring progress bar is greater than or equal to the radius, the width is changed to half of the radius.
Default value: **4.0Vp**
- **scaleCount**: number of divisions on the determinate ring-type process indicator.
Default value: **120**
- **scaleWidth**: scale width of the ring progress bar. It cannot be set in percentage. If it is greater than the value of **strokeWidth**, the default scale width is used.
Default value: **2.0Vp**
Since API version 9, this API is supported in ArkTS widgets.| +| Name | Type | Description | +| ------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | +| value | number | Current progress. If the value is less than 0, the value **0** is used. If the value is greater than that of **total**, the value of **total** is used. Invalid values do not take effect.
Since API version 9, this API is supported in ArkTS widgets.| +| color | [ResourceColor](ts-types.md#resourcecolor) \| [LinearGradient10+](ts-basic-components-datapanel.md#lineargradient10) | Background color of the progress indicator. Since API version 10, this attribute can be set to **LinearGradient** for the **Ring** style.
Default value (API version 9): **'\#ff007dff'**
Default value (API version 10):
- Capsule: **'\#33006cde'**
- Ring: starting point: **'\#ff3b61f7'**, ending point: **'\#ff6591bf'**
- Other styles: **'\#ff007dff'**
Since API version 9, this API is supported in ArkTS widgets, except that **LinearGradient** is not supported.| +| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the progress indicator.
Default value (API version 9): **'\#19182431'**
Default value (API version 10):
- Capsule: **'\#33ffffff'**
- Ring: **'\#08182431'**
- Other styles: **'\#19182431'**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
The settings of the universal attribute [backgroundColor](./ts-universal-attributes-background.md) applies to the progress indicator instead of the entire **\** component.| +| style8+ | [ProgressStyleOptions](#progressstyleoptions) \| [CapsuleStyleOptions10+](#capsulestyleoptions10) \| [RingStyleOptions10+](#ringstyleoptions10) | Component style. Since API version 10, this attribute can be set to **CapsuleStyleOptions** or **RingStyleOptions**.
- **CapsuleStyleOptions** is available for the **Capsule** style.
- **RingStyleOptions** is available for the **Ring** style.
- **ProgressStyleOptions** is available for other styles.
Since API version 9, this API is supported in ArkTS widgets, except that **CapsuleStyleOptions** and **RingStyleOptions** are not supported.| + +## ProgressStyleOptions +| Name | Type | Mandatory| Description | +| ------------ | ---------------------------- | ---- | ------------------------------------------------------------------------------------------ | +| strokeWidth | [Length](ts-types.md#length) | No | Stroke width of the progress indicator. It cannot be set in percentage.
Default value: **4.0Vp** | +| scaleCount | number | No | Number of divisions on the ring-style process indicator.
Default value: **120** | +| scaleWidth | [Length](ts-types.md#length) | No | Scale width of the ring-style progress bar. It cannot be set in percentage. If it is greater than the value of **strokeWidth**, the default scale width is used.
Default value: **2.0Vp**| + +## CapsuleStyleOptions10+ +| Name | Type| Mandatory| Description| +| ------------- | ------- | ---- | -------- | +| borderColor | [ResourceColor](ts-types.md#resourcecolor) | No| Border color.
Default value: **'\#33006cde'**| +| borderWidth | [Length](ts-types.md#length) | No| Border width. It cannot be set in percentage.
Default value: **1 Vp**| +| content | string | No| Text content, which can be customized .| +| font | [Font](ts-types.md#font) | No| Text style.
Default value:
- Font size (cannot be set in percentage): **12Fp**
- Other attributes: following the settings of the **\** component.| +| fontColor | [ResourceColor](ts-types.md#resourcecolor) | No| Font color.
Default value: **'\#ff182431'**| +| enableScanEffect | boolean | No| Whether to enable the scan effect.
Default value: **false**| + +## RingStyleOptions10+ +| Name | Type | Mandatory| Description | +| ------------- | ---------------------------- | ---- | ------------------------------------------------------------------------------------------ | +| strokeWidth | [Length](ts-types.md#length) | No | Stroke width of the progress indicator. It cannot be set in percentage. A value greater than or equal to the radius evaluates to half of the radius.
Default value: **4Vp**| +| shadow | boolean | No | Whether to enable the shadow effect.
Default value: **false** | +| status | [ProgressStatus10+](#progressstatus10) | No| Status of the progress indicator. When this parameter is set to **LOADING**, the **value** settings do not take effect.
Default value: **ProgressStatus.PROGRESSING**| + +## ProgressStatus10+ +| Name | Description | +| ----------------------- | ---------------- | +| LOADING10+ | Loading.| +| PROGRESSING10+ | The progress is being updated.| ## Events @@ -111,7 +141,7 @@ struct ProgressExample { Progress({ value: 10, type: ProgressType.Ring }).width(100) Progress({ value: 20, total: 150, type: ProgressType.Ring }) .color(Color.Grey).value(50).width(100) - .style({ strokeWidth: 20, scaleCount: 30, scaleWidth: 20 }) + .style({ strokeWidth: 20 }) } Text('Capsule Progress').fontSize(9).fontColor(0xCCCCCC).width('90%') @@ -128,4 +158,4 @@ struct ProgressExample { } ``` -![progress](figures/progress.png) +![progress](figures/arkts-progress.png) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-rating.md b/en/application-dev/reference/arkui-ts/ts-basic-components-rating.md index efc15c08f744eb3cf89c534a2bc21d8397d729b2..73221ce76c2b1d2f0767cdb440fefe4f7bef5542 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-rating.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-rating.md @@ -28,10 +28,10 @@ Since API version 9, this API is supported in ArkTS widgets. ## Attributes -| Name | Type | Description | -| --------- | ---------------------------------------- | ---------------------------------------- | -| stars | number | Total number of ratings.
Default value: **5**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
A value less than 0 evaluates to the default value.| -| stepSize | number | Step of an operation.
Default value: **0.5**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
A value less than 0 evaluates to the default value.
Value range: [0.1, stars]| +| Name | Type | Description | +| --------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| stars | number | Total number of ratings.
Default value: **5**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
A value less than or equal to 0 evaluates to the default value.| +| stepSize | number | Step of an operation.
Default value: **0.5**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
A value less than 0 evaluates to the default value.
Value range: [0.1, stars]| | starStyle | {
backgroundUri: string,
foregroundUri: string,
secondaryUri?: string
} | Star style.
**backgroundUri**: image path for the unselected star. You can use the default system image or a custom image.
**foregroundUri**: image path for the selected star. You can use the default system image or a custom image.
**secondaryUir**: image path for the partially selected star. You can use the default system image or a custom image.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
For details about the image types supported by the **startStyle** attribute, see [Image](ts-basic-components-image.md).
Local and online images are supported, but not **PixelMap** and **Resource** objects.
By default, the image is loaded in asynchronous mode. Synchronous loading is not supported.
If this parameter is set to **undefined** or an empty string, the **\** component loads the default star image source.| > **NOTE** diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-search.md b/en/application-dev/reference/arkui-ts/ts-basic-components-search.md index 16a4df18ac1ff7b20ba22b935418ddeb710f3bab..733bb8ba86927926bad9188b371a17c6c0fdddd0 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-search.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-search.md @@ -39,7 +39,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | cancelButton10+ | {
style? : [CancelButtonStyle](#cancelbuttonstyle10)
icon?: [IconOptions](#iconoptions10)
} | Style of the Cancel button on the right. | | fontColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Font color of the input text. | | caretStyle10+ | [CaretStyle](#caretstyle10) | Caret style. | - +| enableKeyboardOnFocus10+ | boolean | Whether to enable the input method when the component obtains focus.
Default value: **true** | +| selectionMenuHidden10+ | boolean | Whether to display the text selection menu when the text box is long-pressed or right-clicked.
Default value: **false**| ## IconOptions10+ | Name| Type | Mandatory| Description | @@ -66,21 +67,23 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name | Description | | ----------------------- | ---------------- | -| CONSTANT10+ | The Cancel button is always displayed.| -| INVISIBLE10+ | The Cancel button is always hidden.| -| INPUT10+ | The Cancel button is displayed when there is text input.| +| CONSTANT | The Cancel button is always displayed.| +| INVISIBLE | The Cancel button is always hidden.| +| INPUT | The Cancel button is displayed when there is text input.| ## Events In addition to the [universal events](ts-universal-events-click.md), the following events are supported. -| Name | Description | -| ---------------------------------------- | ---------------------------------------- | -| onSubmit(callback: (value: string) => void) | Invoked when users click the search icon or the search button, or touch the search button on a soft keyboard.
- **value**: current text input.| -| onChange(callback: (value: string) => void) | Invoked when the input in the text box changes.
- **value**: current text input. | -| onCopy(callback: (value: string) => void) | Invoked when data is copied to the pasteboard, which is displayed when the search text box is long pressed.
- **value**: text copied. | -| onCut(callback: (value: string) => void) | Invoked when data is cut from the pasteboard, which is displayed when the search text box is long pressed.
- **value**: text cut. | -| onPaste(callback: (value: string) => void) | Invoked when data is pasted from the pasteboard, which is displayed when the search text box is long pressed.
-**value**: text pasted. | +| Name | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| onSubmit(callback: (value: string) => void) | Triggered when users click the search icon or the search button, or touch the search button on a soft keyboard.
- **value**: current text input.| +| onChange(callback: (value: string) => void) | Triggered when the input in the text box changes.
- **value**: current text input.| +| onCopy(callback: (value: string) => void) | Triggered when data is copied to the pasteboard, which is displayed when the search text box is long pressed.
- **value**: text copied.| +| onCut(callback: (value: string) => void) | Triggered when data is cut from the pasteboard, which is displayed when the search text box is long pressed.
- **value**: text cut.| +| onPaste(callback: (value: string) => void) | Triggered when data is pasted from the pasteboard, which is displayed when the search text box is long pressed.
-**value**: text pasted.| +| onTextSelectionChange(callback: (selectionStart: number, selectionEnd: number) => void)10+ | Triggered when the text selection position changes.
**selectionStart**: start position of the text selection area. The start position of text in the text box is **0**.
**selectionEnd**: end position of the text selection area.| +| onContentScroll(callback: (totalOffsetX: number, totalOffsetY: number) => void)10+ | Triggered when the text content is scrolled.
**totalOffsetX**: X coordinate offset of the text in the content area.
**totalOffsetY**: Y coordinate offset of the text in the content area.| ## SearchController @@ -102,8 +105,16 @@ Sets the position of the caret. | ------ | -------- | ---- | ---------------------------------- | | value | number | Yes | Length from the start of the character string to the position where the caret is located.| +### stopEditing10+ + +stopEditing(): void + +Exits the editing state. + ## Example +### Example 1 + ```ts // xxx.ets @Entry @@ -119,7 +130,7 @@ struct SearchExample { Text('onChange:' + this.changeValue).fontSize(18).margin(15) Search({ value: this.changeValue, placeholder: 'Type to search...', controller: this.controller }) .searchButton('SEARCH') - .width(400) + .width('95%') .height(40) .backgroundColor('#F5F5F5') .placeholderColor(Color.Grey) @@ -143,3 +154,43 @@ struct SearchExample { ``` ![search](figures/search.gif) + +### Example 2 + +```ts +// xxx.ets +@Entry +@Component +struct SearchButtoonExample { + @State submitValue: string = '' + + build() { + Column() { + Text('onSubmit:' + this.submitValue).fontSize(18).margin(15) + Search({ placeholder: 'Type to search...' }) + .searchButton('SEARCH') + .searchIcon({ + src: $r('app.media.search') + }) + .cancelButton({ + style: CancelButtonStyle.CONSTANT, + icon: { + src: $r('app.media.cancel') + } + }) + .width('90%') + .height(40) + .backgroundColor('#F5F5F5') + .placeholderColor(Color.Grey) + .placeholderFont({ size: 14, weight: 400 }) + .textFont({ size: 14, weight: 400 }) + .onSubmit((value: string) => { + this.submitValue = value + }) + .margin(20) + }.width('100%') + } +} +``` + +![searchButton](figures/searchButton.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md b/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md index 4958173d84c8894bd661ddfd0cdfd05f9041b251..cab18d856b6dc0e86a5d49b75b7bb56afc7b7ca7 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md @@ -22,7 +22,7 @@ Since API version 9, this API is supported in ArkTS widgets. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | number | No| Current progress.
Default value: min
Since API version 10, this parameter supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.| +| value | number | No| Current progress.
Default value: value of **min**
Since API version 10, this parameter supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.| | min | number | No| Minimum value.
Default value: **0**| | max | number | No| Maximum value.
Default value: **100**
**NOTE**
If the value of **min** is greater than or equal to the value of **max**, the default value **0** is used for **min** and the default value **100** is used for **max**.
If the value is not within the [min, max] range, the value of **min** or **max**, whichever is closer.| | step | number | No| Step of the slider.
Default value: **1**
Value range: [0.01, max]
**NOTE**
If this parameter is set to a value less than 0 or a percentage, the default value is used.| @@ -47,7 +47,7 @@ Except touch target attributes, the universal attributes are supported. | trackColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the slider.
Since API version 9, this API is supported in ArkTS widgets.| | selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the selected part of the slider track.
Since API version 9, this API is supported in ArkTS widgets.| | showSteps | boolean | Whether to display the current step.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| -| showTips | boolean | Whether to display a bubble to indicate the percentage when the user drags the slider.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When **direction** is set to **Axis.Horizontal**, the bubble is displayed right above the slider. When **direction** is set to **Axis.Vertical**, the bubble is displayed on the left of the slider.
The drawing area of the bubble is the overlay of the slider.
If no margin is set for the slider or the margin is not large enough, the bubble will be clipped.| +| showTips | value: boolean,
content10+?: [ResourceStr](ts-types.md#resourcestr) | **value**: whether to display a tooltip when the user drags the slider.
Default value: **false**
**content**: text content of the tooltip. The default value is the current percentage.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When **direction** is set to **Axis.Horizontal**, the tooltip is displayed right above the slider. When **direction** is set to **Axis.Vertical**, the tooltip is displayed on the left of the slider.
The drawing area of the tooltip is the overlay of the slider.
If no margin is set for the slider or the margin is not large enough, the tooltip will be clipped.| | trackThickness | [Length](ts-types.md#length) | Track thickness of the slider.
Default value: **4.0vp** when **style** is set to **[SliderStyle](#sliderstyle).OutSet**; **20.0vp** when **style** is set to **[SliderStyle](#sliderstyle).InSet**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
A value less than 0 evaluates to the default value.| | blockBorderColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Border color of the slider in the block direction.| | blockBorderWidth10+ | [Length](ts-types.md#length) | Border width of the slider in the block direction.| diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-span.md b/en/application-dev/reference/arkui-ts/ts-basic-components-span.md index 53cdf20f46f1458ec62c6fafccf50e81514e4e00..41565994b98dbaa17af0697226c1571bdefac2c9 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-span.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-span.md @@ -36,6 +36,7 @@ In addition to the [universal text style](ts-universal-attributes-text-style.md) | decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | Style and color of the text decorative line.
Default value: {
type: TextDecorationType.None
color: Color.Black
}
Since API version 9, this API is supported in ArkTS widgets.| | letterSpacing | number \| string | Letter spacing. A negative value tightens the spacing; a positive value loosens the spacing, and the letters are spread farther apart with the value.
Since API version 9, this API is supported in ArkTS widgets. | | textCase | [TextCase](ts-appendix-enums.md#textcase) | Text case.
Default value: **TextCase.Normal**
Since API version 9, this API is supported in ArkTS widgets.| +| font10+ | [Font](ts-types.md#font) | Text style, covering the font size, font width, Font family, and font style.| ## Events diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-text.md b/en/application-dev/reference/arkui-ts/ts-basic-components-text.md index 9a52243939d77e88ba48b793830784aa51ebc608..0b559a3c66a086b77036b3d9f60a2adb7d61f92c 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-text.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-text.md @@ -31,20 +31,21 @@ In addition to the [universal attributes](ts-universal-attributes-size.md) and [ | Name | Type | Description | | ----------------------- | ----------------------------------- | ------------------------------------------- | | textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment mode of the text.
Default value: **TextAlign.Start**
**NOTE**
The text takes up the full width of the **\** component. To set vertical alignment for the text, use the [align](ts-universal-attributes-location.md) attribute. The **align** attribute alone does not control the horizontal position of the text. In other words, **Alignment.TopStart**, **Alignment.Top**, and **Alignment.TopEnd** produce the same effect, top-aligning the text; **Alignment.Start**, **Alignment.Center**, and **Alignment.End** produce the same effect, centered-aligning the text vertically; **Alignment.BottomStart**, **Alignment.Bottom**, and **Alignment.BottomEnd** produce the same effect, bottom-aligning the text. Yet, it can work with the **textAlign** attribute to jointly determine the horizontal position of the text.
Since API version 9, this API is supported in ArkTS widgets.| -| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | Display mode when the text is too long.
Default value: **{overflow: TextOverflow.Clip}**
**NOTE**
Text is clipped at the transition between words. To clip text in the middle of a word, add **\u200B** between characters.
If **overflow** is set to **TextOverflow.None**, **TextOverflow.Clip**, or **TextOverflow.Ellipsis**, this attribute must be used with **maxLines**. Otherwise, the setting does not take effect. **TextOverflow.None** produces the same effect as **TextOverflow.Clip**. If **overflow** is set to **TextOverflow.Marquee**, the text scrolls in a line, and neither **maxLines** nor **copyOption** takes effect.
Since API version 9, this API is supported in ArkTS widgets.| +| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | Display mode when the text is too long.
Default value: **{overflow: TextOverflow.Clip}**
**NOTE**
Text is clipped at the transition between words. To clip text in the middle of a word, add **\u200B** between characters.
If **overflow** is set to **TextOverflow.None**, **TextOverflow.Clip**, or **TextOverflow.Ellipsis**, this attribute must be used with **maxLines**. Otherwise, the setting does not take effect. **TextOverflow.None** produces the same effect as **TextOverflow.Clip**. If **overflow** is set to **TextOverflow.Marquee**, the text scrolls in a line, and neither **maxLines** nor **copyOption** takes effect.
Since API version 9, this API is supported in ArkTS widgets. | | maxLines | number | Maximum number of lines in the text.
Default value: **Infinity**
**NOTE**
By default, text is automatically folded. If this attribute is specified, the text will not exceed the specified number of lines. If there is extra text, you can use **textOverflow** to specify how it is displayed.
Since API version 9, this API is supported in ArkTS widgets. | | lineHeight | string \| number \| [Resource](ts-types.md#resource) | Text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value of the number type, the unit fp is used.
Since API version 9, this API is supported in ArkTS widgets.| | decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | Style and color of the text decorative line.
Default value: {
type: TextDecorationType.None,
color: Color.Black
}
Since API version 9, this API is supported in ArkTS widgets.| | baselineOffset | number \| string | Baseline offset of the text. The default value is **0**.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**

If this attribute is set to a percentage, the default value is used.| -| letterSpacing | number \| string | Letter spacing.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
If this attribute is set to a percentage, the default value is used.
If this attribute is set to a negative value, the letters will overlap each other. | +| letterSpacing | number \| string | Letter spacing.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
If this attribute is set to a percentage, the default value is used.
If this attribute is set to a negative value, the letters will overlap each other.| | minFontSize | number \| string \| [Resource](ts-types.md#resource) | Minimum font size.
For the setting to take effect, this attribute must be used together with **maxFontSize**, **maxLines**, or layout constraint settings.
Since API version 9, this API is supported in ArkTS widgets. | | maxFontSize | number \| string \| [Resource](ts-types.md#resource) | Maximum font size.
For the setting to take effect, this attribute must be used together with **minFontSize**, **maxLines**, or layout constraint settings.
Since API version 9, this API is supported in ArkTS widgets. | | textCase | [TextCase](ts-appendix-enums.md#textcase) | Text case.
Default value: **TextCase.Normal**
Since API version 9, this API is supported in ArkTS widgets.| | copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
Default value: **CopyOptions.None**
This API is supported in ArkTS widgets.| -| draggable9+ | boolean | Drag effect of the selected text.
This attribute cannot be used with the [onDragStart](ts-universal-events-drag-drop.md) event.
It must be used with **copyOption** to enable the selected text to be dragged and copied.
Default value: **false**| +| draggable(deprecated) | boolean | Drag effect of the selected text.
This attribute cannot be used with the [onDragStart](ts-universal-events-drag-drop.md) event.
It must be used with **copyOption** to enable the selected text to be dragged and copied.
Default value: **false**
**NOTE**
This API is supported since API version 8 and deprecated since API version 10. You are advised to use the universal attribute [draggable](ts-universal-events-drag-drop.md) instead. | | textShadow10+ | [ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions) | Text shadow.| -| heightAdaptivePolicy10+ | [TextHeightAdaptivePolicy](ts-appendix-enums.md#textheightadaptivepolicy10) | How the adaptive height is determined for the text.
Default value: **TextHeightAdaptivePolicy.MAX_LINES_FIRST**
**NOTE**
When this attribute is set to **TextHeightAdaptivePolicy.MAX_LINES_FIRST**, the **maxLines** attribute takes precedence for adjusting the text height. If the **maxLines** setting results in a layout beyond the layout constraints, the text will shrink to a font size between `minFontSize` and `maxFontSize` to allow for more content to be shown.
When this attribute is set to **TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST**, the **minFontSize** attribute takes precedence for adjusting the text height. If the text can fit in one line with the `minFontSize` setting, the text will enlarge to the largest possible font size between `minFontSize` and `maxFontSize`.
When this attribute is set to **TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST**, the layout constraints take precedence for adjusting the text height. If the resultant layout is beyond the layout constraints, the text will shrink to a font size between `minFontSize` and `maxFontSize` to respect the layout constraints. If the layout still exceeds the layout constraints after the font size is reduced to **minFontSize**, the lines that exceed the layout constraints are deleted. | +| heightAdaptivePolicy10+ | [TextHeightAdaptivePolicy](ts-appendix-enums.md#textheightadaptivepolicy10) | How the adaptive height is determined for the text.
Default value: **TextHeightAdaptivePolicy.MAX_LINES_FIRST**
**NOTE**
When this attribute is set to **TextHeightAdaptivePolicy.MAX_LINES_FIRST**, the **maxLines** attribute takes precedence for adjusting the text height. If the **maxLines** setting results in a layout beyond the layout constraints, the text will shrink to a font size between `minFontSize` and `maxFontSize` to allow for more content to be shown.
When this attribute is set to **TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST**, the **minFontSize** attribute takes precedence for adjusting the text height. If the text can fit in one line with the **minFontSize** setting, the text will enlarge to the largest possible font size between **minFontSize** and **maxFontSize**.
When this attribute is set to **TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST**, the layout constraints take precedence for adjusting the text height. If the resultant layout is beyond the layout constraints, the text will shrink to a font size between **minFontSize** and **maxFontSize** to respect the layout constraints. If the layout still exceeds the layout constraints after the font size is reduced to **minFontSize**, the lines that exceed the layout constraints are deleted. | | textIndent10+ | number \| string | Indentation of the first line.
Default value: **0**| +| font10+ | [Font](ts-types.md#font) | Text style, covering the font size, font width, Font family, and font style.| > **NOTE** > diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md index f3af7b67cb3eb17ada3be85777566ce874b1a72e..cd906dd3c5c5e12cd2b2b4b9ab65e76fb255143c 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md @@ -20,29 +20,33 @@ TextArea(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Tex | Name | Type | Mandatory | Description | | ----------------------- | ---------------------------------------- | ---- | -------------- | -| placeholder | [ResourceStr](ts-types.md#resourcestr) | No | Placeholder text displayed when there is no input. It is not displayed once there is any input. | +| placeholder | [ResourceStr](ts-types.md#resourcestr) | No | Placeholder text displayed when no text input is set.
When only the **placeholder** attribute is set, the text selection handle is still available; the caret stays at the beginning of the placeholder text when the handle is released. | | text | [ResourceStr](ts-types.md#resourcestr) | No | Current text input.
If the component has [stateStyles](ts-universal-attributes-polymorphic-style.md) or any other attribute that may trigger updating configured, you are advised to bind the state variable to the text in real time through the **onChange** event,
so as to prevent display errors when the component is updated.
Since API version 10, this parameter supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.| | controller8+ | [TextAreaController](#textareacontroller8) | No | Text area controller.| ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. - -| Name | Type | Description | -| ------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | -| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color. | -| placeholderFont | [Font](ts-types.md#font) | Placeholder text style, including the font size, font width, font family, and font style. Currently, only the default font family is supported.| -| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment of the text.
Default value: **TextAlign.Start**| -| caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box. | -| inputFilter8+ | {
value: [ResourceStr](ts-types.md#resourcestr),
error?: (value: string) => void
} | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The specified regular expression can match single characters, but not strings.
- **value**: regular expression to set.
- **error**: filtered-out content to return when regular expression matching fails.| -| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
If this attribute is set to **CopyOptions.None**, the paste operation is allowed, but the copy and cut operations are not.| +Among the [universal attributes](ts-universal-attributes-size.md) and [universal text attributes](ts-universal-attributes-text-style.md), **fontColor**, **fontSize**, **fontStyle**, **fontWeight**, and **fontFamily** are supported. In addition, the following attributes are supported. + +| Name | Type | Description | +| ------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color.
The default value follows the theme. | +| placeholderFont | [Font](ts-types.md#font) | Placeholder text style, including the font size, font width, font family, and font style. Currently, only the default font family is supported.| +| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment of the text.
Default value: **TextAlign.Start**
**NOTE**
Available options are **TextAlign.Start**, **TextAlign.Center**, and **TextAlign.End**.
To set vertical alignment for the text, use the [align](ts-universal-attributes-location.md) attribute. The **align** attribute alone does not control the horizontal position of the text. In other words, **Alignment.TopStart**, **Alignment.Top**, and **Alignment.TopEnd** produce the same effect, top-aligning the text; **Alignment.Start**, **Alignment.Center**, and **Alignment.End** produce the same effect, centered-aligning the text vertically; **Alignment.BottomStart**, **Alignment.Bottom**, and **Alignment.BottomEnd** produce the same effect, bottom-aligning the text.| +| caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box.
Default value: **'#007DFF'** | +| inputFilter8+ | {
value: [ResourceStr](ts-types.md#resourcestr),
error?: (value: string) => void
} | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The specified regular expression can match single characters, but not strings.
- **value**: regular expression to set.
- **error**: filtered-out content to return when regular expression matching fails.| +| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
Default value: **CopyOptions.LocalDevice**
If this attribute is set to **CopyOptions.None**, the paste operation is allowed, but the copy and cut operations are not.| +| maxLength10+ | number | Maximum number of characters in the text input.
By default, there is no maximum number of characters.| +| showCounter10+ | boolean | Whether to show the number of entered characters when **maxLength** is set.
Default value: **false** | +| style10+ | [TextContentStyle](ts-appendix-enums.md#textcontentstyle10) | Style of the component.
Default value: **TextContentStyle.DEFAULT** | +| enableKeyboardOnFocus10+ | boolean | Whether to enable the input method when the component obtains focus.
Default value: **true** | +| selectionMenuHidden10+ | boolean | Whether to display the text selection menu when the text box is long-pressed or right-clicked.
Default value: **false**| > **NOTE** > > The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows:
{
top: 8 vp,
right: 16 vp,
bottom: 8 vp,
left: 16 vp
} - ## Events In addition to the [universal events](ts-universal-events-click.md), the following events are supported. @@ -54,6 +58,8 @@ In addition to the [universal events](ts-universal-events-click.md), the followi | onCopy8+(callback:(value: string) => void) | Triggered when the copy button on the pasteboard, which displays when the text box is long pressed, is clicked.
- **value**: text to be copied.| | onCut8+(callback:(value: string) => void) | Triggered when the cut button on the pasteboard, which displays when the text box is long pressed, is clicked.
- **value**: text to be cut.| | onPaste8+(callback:(value: string) => void) | Triggered when the paste button on the pasteboard, which displays when the text box is long pressed, is clicked.
- **value**: text to be pasted.| +| onTextSelectionChange(callback: (selectionStart: number, selectionEnd: number) => void)10+ | Triggered when the text selection position changes.
**selectionStart**: start position of the text selection area. The start position of text in the text box is **0**.
**selectionEnd**: end position of the text selection area.| +| onContentScroll(callback: (totalOffsetX: number, totalOffsetY: number) => void)10+ | Triggered when the text content is scrolled.
**totalOffsetX**: X coordinate offset of the text in the content area.
**totalOffsetY**: Y coordinate offset of the text in the content area.| ## TextAreaController8+ @@ -90,6 +96,12 @@ Sets the text selection range and highlights the selected text when the componen | selectionStart | number | Yes | Start position of the text selection range. The start position of text in the text box is 0.
A value less than 0 evaluates to the value **0**. A value greater than the maximum text length evaluates to the maximum text length.
| | selectionEnd | number | Yes | End position of the text selection range.
A value less than 0 evaluates to the value **0**. A value greater than the maximum text length evaluates to the maximum text length.
| +### stopEditing10+ + +stopEditing(): void + +Exits the editing state. + ## Example ```ts diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md index 588f88057abe66a553dd25dc8337503b8786e65a..f0f381f1abcab994b9851d1ddf8eecf5a54f7d07 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md @@ -21,30 +21,36 @@ TextInput(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Te | Name | Type | Mandatory | Description | | ----------------------- | ---------------------------------------- | ---- | --------------- | | placeholder | [ResourceStr](ts-types.md#resourcestr) | No | Placeholder text displayed when there is no input. | -| text | [ResourceStr](ts-types.md#resourcestr) | No | Current text input.
If the component has [stateStyles](ts-universal-attributes-polymorphic-style.md) or any other attribute that may trigger updating configured, you are advised to bind the state variable to the text in real time through the **onChange** event,
so as to prevent display errors when the component is updated.
Since API version 10, this parameter supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.| +| text | [ResourceStr](ts-types.md#resourcestr) | No | Current text input.
If the component has [stateStyles](ts-universal-attributes-polymorphic-style.md) or any other attribute that may trigger updating configured, you are advised to bind the state variable to the text in real time through the **onChange** event, so as to prevent display errors when the component is updated.
Since API version 10, this parameter supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.| | controller8+ | [TextInputController](#textinputcontroller8) | No | Text input controller.| ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +Among the [universal attributes](ts-universal-attributes-size.md) and [universal text attributes](ts-universal-attributes-text-style.md), **fontColor**, **fontSize**, **fontStyle**, **fontWeight**, and **fontFamily** are supported. In addition, the following attributes are supported. | Name | Type | Description | | ------------------------ | ---------------------------------------- | ---------------------------------------- | | type | [InputType](#inputtype) | Input box type.
Default value: **InputType.Normal** | -| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color.| +| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color.
The default value follows the theme. | | placeholderFont | [Font](ts-types.md#font) | Placeholder text font.| | enterKeyType | [EnterKeyType](#enterkeytype) | Type of the Enter key. Currently, only the default value is supported.
Default value: **EnterKeyType.Done**| -| caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box. | +| caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box.
Default value: **'#007DFF'** | | maxLength | number | Maximum number of characters in the text input. | | inputFilter8+ | {
value: [ResourceStr](ts-types.md#resourcestr),
error?: (value: string) => void
} | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The regular expression can match single characters, but not strings.
- **value**: regular expression to set.
- **error**: filtered-out content to return when regular expression matching fails.| -| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
If this attribute is set to **CopyOptions.None**, the paste operation is allowed, but not the copy or cut operation.| -| showPasswordIcon9+ | boolean | Whether to display the show password icon at the end of the password text box.
Default value: **true**| -| style9+ | [TextInputStyle](#textinputstyle9) | Text input style.
Default value: **TextInputStyle.Default**| -| textAlign9+ | [TextAlign](ts-appendix-enums.md#textalign) | Alignment mode of the text in the text box.
Default value: **TextAlign.Start** | +| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
Default value: **CopyOptions.LocalDevice**
If this attribute is set to **CopyOptions.None**, the paste operation is allowed, but not the copy or cut operation.| +| showPasswordIcon9+ | boolean | Whether to display the password icon at the end of the password text box.
Default value: **true**| +| style9+ | [TextInputStyle](#textinputstyle9) \| [TextContentStyle](ts-appendix-enums.md#textcontentstyle10) | Text input style.
Default value: **TextInputStyle.Default**| +| textAlign9+ | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment of the text.
Default value: **TextAlign.Start**
**NOTE**
Available options are **TextAlign.Start**, **TextAlign.Center**, and **TextAlign.End**.
To set vertical alignment for the text, use the [align](ts-universal-attributes-location.md) attribute. The **align** attribute alone does not control the horizontal position of the text. In other words, **Alignment.TopStart**, **Alignment.Top**, and **Alignment.TopEnd** produce the same effect, top-aligning the text; **Alignment.Start**, **Alignment.Center**, and **Alignment.End** produce the same effect, centered-aligning the text vertically; **Alignment.BottomStart**, **Alignment.Bottom**, and **Alignment.BottomEnd** produce the same effect, bottom-aligning the text. | | selectedBackgroundColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Background color of the selected text.
If the opacity is not set, the color is opaque. For example, **0x80000000** indicates black with 50% opacity.| | caretStyle10+ | {
width: [Length](ts-types.md#length)
} | Caret style. | | caretPosition10+ | number | Caret position.| +| showUnit10+ | [CustomBuilder](ts-types.md#CustomBuilder8) | Unit for content in the component.
By default, there is no unit.| +| showError10+ | string \| undefined | Error text displayed when an error occurs.
By default, no error text is displayed.| +| showUnderline10+ | boolean | Whether to show an underline.
Default value: **false**| +| passwordIcon10+ | [PasswordIcon](#passwordicon10) | Password icon to display at the end of the password text box.
By default, the system-provided icon is used.| +| enableKeyboardOnFocus10+ | boolean | Whether to enable the input method when the component obtains focus.
Default value: **true** | +| selectionMenuHidden10+ | boolean | Whether to display the text selection menu when the text box is long-pressed or right-clicked.
Default value: **false**| > **NOTE** > @@ -77,6 +83,13 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Default | Default style. The caret width is fixed at 1.5 vp, and the caret height is subject to the background height and font size of the selected text. | | Inline | Inline input style. The background height of the selected text is the same as the height of the text box. | +## PasswordIcon10+ + +| Name | Type | Mandatory| Description | +| ---------- | -------------------------------------------------- | ---- | -------------------------------------------------- | +| onIconSrc | string \|[Resource](ts-types.md#resource)| No | Icon that can be used to hide the password in password input mode.| +| offIconSrc | string \|[Resource](ts-types.md#resource)| No | Icon that can be used to show the password in password input mode.| + ## Events In addition to the [universal events](ts-universal-events-click.md), the following events are supported. @@ -90,6 +103,8 @@ In addition to the [universal events](ts-universal-events-click.md), the followi | onCopy(callback:(value: string) => void)8+ | Triggered when the copy button on the pasteboard, which displays when the text box is long pressed, is clicked.
**value**: text to be copied.| | onCut(callback:(value: string) => void)8+ | Triggered when the cut button on the pasteboard, which displays when the text box is long pressed, is clicked.
**value**: text to be cut.| | onPaste(callback:(value: string) => void)8+ | Triggered when the paste button on the pasteboard, which displays when the text box is long pressed, is clicked.
**value**: text to be pasted.| +| onTextSelectionChange(callback: (selectionStart: number, selectionEnd: number) => void)10+ | Triggered when the text selection position changes.
**selectionStart**: start position of the text selection area. The start position of text in the text box is **0**.
**selectionEnd**: end position of the text selection area.| +| onContentScroll(callback: (totalOffsetX: number, totalOffsetY: number) => void)10+ | Triggered when the text content is scrolled.
**totalOffsetX**: X coordinate offset of the text in the content area.
**totalOffsetY**: Y coordinate offset of the text in the content area.| ## TextInputController8+ @@ -123,6 +138,12 @@ Sets the text selection area, which will be highlighted. | selectionStart | number | Yes | Start position of the text selection area. The start position of the text in the text box is 0.| | selectionEnd | number | Yes | End position of the text selection area.| +### stopEditing10+ + +stopEditing(): void + +Exits the editing state. + ## Example ```ts diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textpicker.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textpicker.md index 5f88febc197d777bfdea733e3e94530d5f181cf4..ac4939dac0b575bc416c3fa85a2d1c777a43947e 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textpicker.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textpicker.md @@ -14,7 +14,7 @@ Not supported ## APIs -TextPicker(options?: {range: string[]|Resource|TextPickerRangeContent[], selected?: number, value?: string}) +TextPicker(options?: {range: string[] | string[][] | Resource | TextPickerRangeContent[] | TextCascadePickerRangeContent[], selected?: number, value?: string}) Creates a text picker based on the selection range specified by **range**. @@ -22,9 +22,9 @@ Creates a text picker based on the selection range specified by **range**. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| range | string[] \| [Resource](ts-types.md#resource) \| [TextPickerRangeContent](#textpickerrangecontent10)[]10+ | Yes| Data selection range of the picker. This parameter cannot be set to an empty array. If set to an empty array, it will not be displayed. If it is dynamically changed to an empty array, the current value remains displayed.| -| selected | number | No| Index of the default item in the range.
Default value: **0**
Since API version 10, this parameter supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.| -| value | string | No| Value of the default item in the range. The priority of this parameter is lower than that of **selected**.
Default value: value of the first item
**NOTE**
This parameter works only for a text list. It does not work for an image list or a list consisting of text and images.
Since API version 10, this parameter supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables. | +| range | string[] \| string[][]10+ \| [Resource](ts-types.md#resource) \|
[TextPickerRangeContent](#textpickerrangecontent10)[]10+ \| [TextCascadePickerRangeContent](#textcascadepickerrangecontent10)[]10+ | Yes| Data selection range of the picker. This parameter cannot be set to an empty array. If set to an empty array, it will not be displayed. If it is dynamically changed to an empty array, the current value remains displayed.
**NOTE**
For a single-column picker, use a value of the string[], Resource, or TextPickerRangeContent[] type.
For a multi-column picker, use a value of the string[] type.
For a multi-column linked picker, use a value of the TextCascadePickerRangeContent[] type.
The Resource type supports only [strarray.json](../../quick-start/resource-categories-and-access.md#resource-group-subdirectories).| +| selected | number \| number[]10+ | No| Index of the default item in the range.
Default value: **0**
**NOTE**
For a single-column picker, use a value of the number type.
For a multi-column (linked) picker, use a value of the number[] type.
Since API version 10, this parameter supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.| +| value | string \| string[]10+ | No| Value of the default item in the range. The priority of this parameter is lower than that of **selected**.
Default value: value of the first item
**NOTE**
This parameter works only when the picker contains text only.
For a single-column picker, use a value of the string type.
For a multi-column (linked) picker, use a value of the string[] type.
Since API version 10, this parameter supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables. | ## TextPickerRangeContent10+ @@ -33,6 +33,13 @@ Creates a text picker based on the selection range specified by **range**. | icon | string \| [Resource](ts-types.md#resource) | Yes | Image resource.| | text | string \| [Resource](ts-types.md#resource) | No | Text information.| +## TextCascadePickerRangeContent10+ + +| Name| Type | Mandatory| Description | +| ------ | -------------------------------------------------------- | ---- | ---------- | +| text | string \| [Resource](ts-types.md#resource) | Yes | Text information.| +| children | [TextCascadePickerRangeContent](#textcascadepickerrangecontent10)[] | No | Linkage data.| + ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. @@ -40,9 +47,10 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | | defaultPickerItemHeight | number \| string | Height of each item in the picker.| -| disappearTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Font color, font size, and font width for the top and bottom items.| -| textStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Font color, font size, and font width of all items except the top, bottom, and selected items.| -| selectedTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Font color, font size, and font width of the selected item.| +| disappearTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Font color, font size, and font width for the top and bottom items.
Default value:
{
color: '#ff182431',
font: {
size: '14fp',
weight: FontWeight.Regular
}
} | +| textStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Font color, font size, and font width of all items except the top, bottom, and selected items.
Default value:
{
color: '#ff182431',
font: {
size: '16fp',
weight: FontWeight.Regular
}
} | +| selectedTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Font color, font size, and font width of the selected item.
Default value:
{
color: '#ff007dff',
font: {
size: '20vp',
weight: FontWeight.Medium
}
} | +| selectedIndex10+ | number \| number[] | Sets the index value of the default selected item in the array. The priority is higher than that of the selected value in options.
**NOTE**
For a single-column picker, use a value of the number type. For a multi-column (linked) picker, use a value of the number[] type.| ## Events @@ -50,9 +58,9 @@ In addition to the [universal events](ts-universal-events-click.md), the followi | Name| Description| | -------- | -------- | -| onAccept(callback: (value: string, index: number) => void) | Triggered when the OK button in the dialog box is clicked.

- **value**: value of the selected item.
- **index**: index of the selected item.
**NOTE**
This event can be triggered only in the [text picker dialog box](ts-methods-textpicker-dialog.md).| -| onCancel(callback: () => void) | Triggered when the Cancel button in the dialog box is clicked.
**NOTE**
This event can be triggered only in the [text picker dialog box](ts-methods-textpicker-dialog.md).| -| onChange(callback: (value: string, index: number) => void) | Triggered when an item in the picker is selected.
- **value**: value of the selected item.
**NOTE**
For a text list or a list consisting of text and images, **value** indicates the text value of the selected item. For an image list, **value** is empty.
- **index**: index of the selected item.| +| onAccept(callback: (value: string, index: number) => void)(deprecated) | Triggered when the OK button in the dialog box is clicked.
- **value**: value of the selected item.
- **index**: index of the selected item.
This API is deprecated since API version 10.
**NOTE**
This event can be triggered only in the [text picker dialog box](ts-methods-textpicker-dialog.md).| +| onCancel(callback: () => void)(deprecated) | Triggered when the Cancel button in the dialog box is clicked.
This API is deprecated since API version 10.
**NOTE**
This event can be triggered only in the [text picker dialog box](ts-methods-textpicker-dialog.md).| +| onChange(callback: (value: string \| string[]10+, index: number \| number[]10+) => void) | Triggered when an item in the picker is selected.
- **value**: value of the selected item. (For a multi-column picker, **value** is of the array type.)
- **index**: index of the selected item. (For a multi-column picker, **index** is of the array type.)
**NOTE**
When the picker contains text only or both text and imagery, **value** indicates the text value of the selected item.When the picker contains imagery only, **value** is empty.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md b/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md index 633e92d812e4aca2db4c68842a0e6745732c52b1..6a48af10416c622cbf2726655a82711202093e56 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md @@ -28,12 +28,12 @@ Creates a time picker, which is in 24-hour format by default. In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name | Type | Description | -| -------------------------------- | ---------------------------------------- | ----------------------------------- | -| useMilitaryTime | boolean | Whether to display time in 24-hour format. The value cannot be modified dynamically.
Default value: **false**| -| disappearTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Font color, font size, and font width for the top and bottom items. | -| textStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Font color, font size, and font width of all items except the top, bottom, and selected items. | -| selectedTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Font color, font size, and font width of the selected item. | +| Name | Type | Description | +| -------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| useMilitaryTime | boolean | Whether the display time is in 24-hour format.
Default value: **false** | +| disappearTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Font color, font size, and font width for the top and bottom items.
Default value:
{
color: '#ff182431',
font: {
size: '14fp',
weight: FontWeight.Regular
}
} | +| textStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Font color, font size, and font width of all items except the top, bottom, and selected items.
Default value:
{
color: '#ff182431',
font: {
size: '16fp',
weight: FontWeight.Regular
}
} | +| selectedTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Font color, font size, and font width of the selected item.
Default value:
{
color: '#ff007dff',
font: {
size: '20vp',
weight: FontWeight.Medium
}
} | ## Events diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-web.md b/en/application-dev/reference/arkui-ts/ts-basic-components-web.md index 5e2e776bf3784794349d7b2a61db2171f7a00313..2d6b3bab8f6c8dfeef3c2b65b3068d1546d4b652 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-web.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-web.md @@ -87,28 +87,28 @@ Web(options: { src: ResourceStr, controller: WebviewController | WebController}) Example of loading local resource files in the sandbox: - 1. Use [globalthis](../../application-models/uiability-data-sync-with-ui.md#using-globalthis-between-uiability-and-page) to obtain the path of the sandbox. - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - let url = 'file://' + globalThis.filesDir + '/xxx.html' - - @Entry - @Component - struct WebComponent { - controller: web_webview.WebviewController = new web_webview.WebviewController() - build() { - Column() { - // Load the files in the sandbox. - Web({ src: url, controller: this.controller }) - } - } - } - ``` + 1. Use [globalthis](../../application-models/uiability-data-sync-with-ui.md#using-globalthis-between-uiability-and-ui-page) to obtain the path of the sandbox. + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + let url = 'file://' + globalThis.filesDir + '/index.html' - 2. Modify the **MainAbility.ts** file. - - The following uses **filesDir** as an example to describe how to obtain the path of the sandbox. For details about how to obtain other paths, see [Obtaining the Application Development Path](../../application-models/application-context-stage.md#obtaining-the-application-development-path). + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + build() { + Column() { + // Load the files in the sandbox. + Web({ src: url, controller: this.controller }) + } + } + } + ``` + + 2. Modify the **EntryAbility.ts** file. + + The following uses **filesDir** as an example to describe how to obtain the path of the sandbox. For details about how to obtain other paths, see [Obtaining Application File Paths](../../application-models/application-context-stage.md#obtaining-application-file-paths). ```ts // xxx.ts import UIAbility from '@ohos.app.ability.UIAbility'; @@ -123,6 +123,7 @@ Web(options: { src: ResourceStr, controller: WebviewController | WebController}) } ``` + HTML file to be loaded: ```html @@ -587,15 +588,16 @@ Sets whether to display the horizontal scrollbar, including the default system s controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { - Web({ src: 'www.example.com', controller: this.controller }) + Web({ src: $rawfile('index.html'), controller: this.controller }) .horizontalScrollBarAccess(true) } } } ``` + HTML file to be loaded: ```html - + @@ -640,15 +642,16 @@ Sets whether to display the vertical scrollbar, including the default system scr controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { - Web({ src: 'www.example.com', controller: this.controller }) + Web({ src: $rawfile('index.html'), controller: this.controller }) .verticalScrollBarAccess(true) } } } ``` + HTML file to be loaded: ```html - + @@ -669,6 +672,11 @@ Sets whether to display the vertical scrollbar, including the default system scr ``` +### password + +password(password: boolean) + +Sets whether the password should be saved. This API is a void API. ### cacheMode @@ -1236,6 +1244,18 @@ Sets whether to enable forcible dark mode for the web page. By default, this fea } ``` +### tableData + +tableData(tableData: boolean) + +Sets whether form data should be saved. This API is a void API. + +### wideViewModeAccess + +wideViewModeAccess(wideViewModeAccess: boolean) + +Sets whether to support the viewport attribute of the HTML **\** tag. This API is a void API. + ### pinchSmooth9+ pinchSmooth(isEnabled: boolean) @@ -1420,7 +1440,7 @@ Called when **alert()** is invoked to display an alert dialog box on the web pag controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { - Web({ src: $rawfile("xxx.html"), controller: this.controller }) + Web({ src: $rawfile("index.html"), controller: this.controller }) .onAlert((event) => { console.log("event.url:" + event.url) console.log("event.message:" + event.message) @@ -1450,8 +1470,9 @@ Called when **alert()** is invoked to display an alert dialog box on the web pag } ``` - ``` - + HTML file to be loaded: + ```html + @@ -1502,7 +1523,7 @@ Called when this page is about to exit after the user refreshes or closes the pa build() { Column() { - Web({ src: $rawfile("xxx.html"), controller: this.controller }) + Web({ src: $rawfile("index.html"), controller: this.controller }) .onBeforeUnload((event) => { console.log("event.url:" + event.url) console.log("event.message:" + event.message) @@ -1532,8 +1553,9 @@ Called when this page is about to exit after the user refreshes or closes the pa } ``` - ``` - + HTML file to be loaded: + ```html + @@ -1584,7 +1606,7 @@ Called when **confirm()** is invoked by the web page. build() { Column() { - Web({ src: $rawfile("xxx.html"), controller: this.controller }) + Web({ src: $rawfile("index.html"), controller: this.controller }) .onConfirm((event) => { console.log("event.url:" + event.url) console.log("event.message:" + event.message) @@ -1614,8 +1636,9 @@ Called when **confirm()** is invoked by the web page. } ``` - ``` - + HTML file to be loaded: + ```html + @@ -1673,7 +1696,7 @@ onPrompt(callback: (event?: { url: string; message: string; value: string; resul build() { Column() { - Web({ src: $rawfile("xxx.html"), controller: this.controller }) + Web({ src: $rawfile("index.html"), controller: this.controller }) .onPrompt((event) => { console.log("url:" + event.url) console.log("message:" + event.message) @@ -1704,8 +1727,9 @@ onPrompt(callback: (event?: { url: string; message: string; value: string; resul } ``` - ``` - + HTML file to be loaded: + ```html + @@ -1776,6 +1800,8 @@ Called to notify the host application of a JavaScript console message. onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisposition: string, mimetype: string, contentLength: number }) => void) +Instructs the main application to start downloading a file. + **Parameters** | Name | Type | Description | @@ -2084,6 +2110,26 @@ Called when loading of the web page is complete. This API is used by an applicat } ``` +### onSslErrorReceive(deprecated) + +onSslErrorReceive(callback: (event?: { handler: Function, error: object }) => void) + +Called when an SSL error occurs during resource loading. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [onSslErrorEventReceive9+](#onsslerroreventreceive9) instead. + +### onFileSelectorShow(deprecated) + +onFileSelectorShow(callback: (event?: { callback: Function, fileSelector: object }) => void) + +Called to process an HTML form whose input type is **file**, in response to the tapping of the **Select File** button. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [onShowFileSelector9+](#onshowfileselector9) instead. + ### onRenderExited9+ onRenderExited(callback: (event?: { renderExitReason: RenderExitReason }) => void) @@ -3308,7 +3354,7 @@ Called when the **\** component is about to access a URL. This API is used | Name | Type | Description | | ------- | ---------------------------------------- | --------- | -| request | [Webresourcerequest](#webresourcerequest) | Information about the URL request.| +| request | [WebResourceRequest](#webresourcerequest) | Information about the URL request.| **Return value** @@ -4280,6 +4326,7 @@ Enumerates the error codes returned by **onSslErrorEventReceive** API. | Name | Description | Remarks | | --------- | ------------- | -------------------------- | | MidiSysex | MIDI SYSEX resource.| Currently, only permission events can be reported. MIDI devices are not yet supported.| +| VIDEO_CAPTURE10+ | Video capture resource, such as a camera.| | ## WebDarkMode9+ | Name | Description | @@ -4933,6 +4980,7 @@ This API is deprecated since API version 9. You are advised to use [registerJava } ``` + HTML file to be loaded: ```html @@ -4993,7 +5041,7 @@ This API is deprecated since API version 9. You are advised to use [runJavaScrip } } ``` - + HTML file to be loaded: ```html @@ -5009,7 +5057,6 @@ This API is deprecated since API version 9. You are advised to use [runJavaScrip } - ``` ### stop(deprecated) @@ -5075,17 +5122,12 @@ This API is deprecated since API version 9. You are advised to use [clearHistory Manages behavior of cookies in **\** components. All **\** components in an application share a **WebCookie**. You can use the **getCookieManager** API in **controller** to obtain the **WebCookie** for subsequent cookie management. ### setCookie(deprecated) -setCookie(url: string, value: string): boolean -Sets the cookie. This API returns the result synchronously. Returns **true** if the operation is successful; returns **false** otherwise. -This API is deprecated since API version 9. You are advised to use [setCookie9+](../apis/js-apis-webview.md#setcookie) instead. +setCookie(): boolean -**Parameters** +Sets the cookie. This API returns the result synchronously. Returns **true** if the operation is successful; returns **false** otherwise. -| Name | Type | Mandatory | Default Value | Description | -| ----- | ------ | ---- | ---- | ----------------- | -| url | string | Yes | - | URL of the cookie to set. A complete URL is recommended.| -| value | string | Yes | - | Value of the cookie to set. | +This API is deprecated since API version 9. You are advised to use [setCookie9+](../apis/js-apis-webview.md#setcookie) instead. **Return value** @@ -5093,31 +5135,12 @@ This API is deprecated since API version 9. You are advised to use [setCookie { - let result = this.controller.getCookieManager().setCookie("https://www.example.com", "a=b") - console.log("result: " + result) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` ### saveCookie(deprecated) + saveCookie(): boolean Saves the cookies in the memory to the drive. This API returns the result synchronously. + This API is deprecated since API version 9. You are advised to use [saveCookieAsync9+](../apis/js-apis-webview.md#savecookieasync) instead. **Return value** @@ -5125,25 +5148,3 @@ This API is deprecated since API version 9. You are advised to use [saveCookieAs | Type | Description | | ------- | -------------------- | | boolean | Operation result.| - -**Example** - - ```ts - // xxx.ets - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - - build() { - Column() { - Button('saveCookie') - .onClick(() => { - let result = this.controller.getCookieManager().saveCookie() - console.log("result: " + result) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md b/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md index f775992c63793b3f41e30d819fab405be931be90..13ec25f92964ea6f702626768a41df16498eadb2 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md @@ -14,20 +14,39 @@ Since API version 9, child components are supported when **type** is set to **"c ## APIs -XComponent(value: {id: string, type: string, libraryname?: string, controller?: XComponentController}) +**API 1**: XComponent(value: {id: string, type: string, libraryname?: string, controller?: XComponentController}) **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | ---------------------------------------- | -| id | string | Yes | Unique ID of the component. The value can contain a maximum of 128 characters. | -| type | string | Yes | Type of the component. The options are as follows:
- **"surface"**: The content of the component is displayed individually, without being combined with that of other components. This option is used for displaying EGL/OpenGL ES and media data.
- **"component"**9+: The component becomes a container where non-UI logic can be executed to dynamically load the display content.| -| libraryname | string | No | Name of the dynamic library generated after compilation at the application native layer. This parameter is valid only when the component type is **"surface"**.| -| controller | [XComponentcontroller](#xcomponentcontroller) | No | Controller bound to the component, which can be used to invoke methods of the component. This parameter is valid only when the component type is **"surface"**.| +| Name | Type | Mandatory| Description | +| ----------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| id | string | Yes | Unique ID of the component. The value can contain a maximum of 128 characters. | +| type | string | Yes | Type of the component. The options are as follows:
- **"surface"**: The custom content is displayed individually on the screen. This option is used for displaying EGL/OpenGL ES and media data.
- **"component"**9+: The component becomes a container where non-UI logic can be executed to dynamically load the display content.
Any other value evaluates to **"surface"**.| +| libraryname | string | No | Name of the dynamic library generated after compilation at the application native layer. This parameter is valid only when **type** is **"surface"**.| +| controller | [XComponentcontroller](#xcomponentcontroller) | No | Controller bound to the component, which can be used to invoke methods of the component. This parameter is valid only when the component type is **"surface"**.| + +**API 2**: XComponent(value: {id: string, type: XComponentType, libraryname?: string, controller?: XComponentController})10+ + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| id | string | Yes | Unique ID of the component. The value can contain a maximum of 128 characters. | +| type | [XComponentType](#xcomponenttype10) | Yes | Type of the component. | +| libraryname | string | No | Name of the dynamic library generated after compilation at the application native layer. This parameter is valid only when **type** is **SURFACE** or **TEXTURE**.| +| controller | [XComponentcontroller](#xcomponentcontroller) | No | Controller bound to the component, which can be used to invoke methods of the component. This parameter is valid only when **type** is **SURFACE** or **TEXTURE**.| + +## XComponentType10+ + +| Name | Description | +| --------- | ------------------------------------------------------------ | +| SURFACE | The custom content is displayed individually on the screen. This option is used for displaying EGL/OpenGL ES and media data.| +| COMPONENT | The component becomes a container where non-UI logic can be executed to dynamically load the display content.| +| TEXTURE | The custom content of the component is grouped and displayed together with content of the component.| > **NOTE** > -> When **type** is set to **"component"**, the **\** functions as a container, where child components are laid out vertically. +> When **type** is set to **COMPONENT("component")**, the **\** functions as a container, where child components are laid out vertically. > > - Vertical alignment: [FlexAlign](ts-appendix-enums.md#flexalign).Start > - Horizontal alignment: [FlexAlign](ts-appendix-enums.md#flexalign).Center @@ -39,13 +58,14 @@ XComponent(value: {id: string, type: string, libraryname?: string, controller?: > The non-UI logic written internally needs to be encapsulated in one or more functions. ## Attributes -- You can customize the content displayed in the **\**. Among the universal attributes, the [background](./ts-universal-attributes-background.md), [opacity](./ts-universal-attributes-opacity.md), and [image effects](./ts-universal-attributes-image-effect.md) attributes are not supported. -- When **type** is set to **"surface"**, you are advised to use the APIs provided by the EGL/OpenGL ES to set the display content. -- When **type** is set to **"component"**, you are advised to mount child components to set the display content. +- You can customize the content displayed in the **\**. Depending on the **type** settings, the support for the universal attributes [background](./ts-universal-attributes-background.md), [opacity](./ts-universal-attributes-opacity.md), and [image effects](./ts-universal-attributes-image-effect.md) varies: +- When **type** is set to **SURFACE("surface")**, none of these attributes is supported. For configuration, you are advised to use the APIs provided by EGL/OpenGL ES instead. +- When **type** is set to **COMPONENT("component")**, none of these attributes is supported. For configuration, you are advised to mount child components. +- When **type** is set to **TEXTURE**, only [opacity](./ts-universal-attributes-opacity.md) and **backgroundColor** in [background](./ts-universal-attributes-background.md) are supported. For configuration of other attributes, you are advised to use the APIs provided by EGL/OpenGL ES instead. ## Events -The following events are supported only when **type** is set to **"surface"**. The [universal events](ts-universal-events-click.md) and [universal gestures](ts-gesture-settings.md) are not supported. +When **type** is set to **SURFACE("surface")** or **TEXTURE**, the following events are supported. The [universal events](ts-universal-events-click.md) and gestures (ts-gesture-settings.md) are not supported. ### onLoad @@ -79,7 +99,7 @@ xcomponentController: XComponentController = new XComponentController() getXComponentSurfaceId(): string -Obtains the ID of the surface held by the **\**. The ID can be used for @ohos interfaces. For details, see [Camera Management](../apis/js-apis-camera.md). This API works only when **type** of the **\** is set to **"surface"**. +Obtains the ID of the surface held by the **\**, which can then be used for @ohos APIs. For details, see [Camera Management](../apis/js-apis-camera.md). This API works only when **type** of the **\** is set to **SURFACE("surface")** or **TEXTURE**. **Return value** @@ -93,7 +113,7 @@ Obtains the ID of the surface held by the **\**. The ID can be used setXComponentSurfaceSize(value: {surfaceWidth: number, surfaceHeight: number}): void -Sets the width and height of the surface held by the **\**. This API works only when **type** of the **\** is set to **"surface"**. +Sets the width and height of the surface held by the **\**. This API works only when **type** of the **\** is set to **SURFACE("surface")** or **TEXTURE**. **Parameters** @@ -108,7 +128,7 @@ Sets the width and height of the surface held by the **\**. This API getXComponentContext(): Object -Obtains the context of an **\** object. This API works only when **type** of the **\** is set to **"surface"**. +Obtains the context of an **\** object. This API works only when **type** of the **\** is set to **SURFACE("surface")** or **TEXTURE**. **Return value** diff --git a/en/application-dev/reference/arkui-ts/ts-components-offscreencanvas.md b/en/application-dev/reference/arkui-ts/ts-components-offscreencanvas.md index 71009d767f23d99fc89b24061b46579e4c9b050a..d9d6a891eb62380dce9ad2c93e15eb9017d8c5a1 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-offscreencanvas.md +++ b/en/application-dev/reference/arkui-ts/ts-components-offscreencanvas.md @@ -170,14 +170,14 @@ Obtains the drawing context of the offscreen canvas. | Name | Type | Mandatory| Default Value| Description | | ----------- | ------------------------------------------------------------ | ---- | ------ | ------------------------------------------------------------ | -| contextType | string | Yes | "2d" | Type of the drawing context of the offscreen canvas. | +| contextType | string | Yes | "2d" | Type of the drawing context of the offscreen canvas. The value can only be **"2d"**. | | option | [RenderingContextSettings](ts-canvasrenderingcontext2d.md#renderingcontextsettings) | No | - | For details, see [RenderingContextSettings](ts-canvasrenderingcontext2d.md#renderingcontextsettings).| **Return value** | Type | Description | | ------------------------------------------------------------ | --------------------------------- | -| [OffscreenCanvasRenderingContext2D](ts-offscreencanvasrenderingcontext2d.md) | Drawing context of the offscreen canvas.| +| [OffscreenCanvasRenderingContext2D](ts-offscreencanvasrenderingcontext2d.md) | Drawing context of the offscreen canvas. If **contextType** in **getContext** is set to a value other than **"2d"** (including **null** and **undefined**), **null** is returned.| **Example** diff --git a/en/application-dev/reference/arkui-ts/ts-components-summary.md b/en/application-dev/reference/arkui-ts/ts-components-summary.md index 19bc1f97eec987ec2e7b97f4507b3e8fc107f29d..d6195e588c8874f362faf3c1c88d4943bced4ad4 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-summary.md +++ b/en/application-dev/reference/arkui-ts/ts-components-summary.md @@ -22,7 +22,7 @@ ## Stack, Flex, and Grid -- [Stack](ts-container-stack.md) +- [Stack](ts-container-stack.md) A container where child components are successively stacked and the latter one overwrites the previous one. - [Flex](ts-container-flex.md) @@ -63,7 +63,7 @@ ## Scroll and Swipe -- [Scroll](ts-container-scroll.md) +- [Scroll](ts-container-scroll.md) A container that scrolls the content when the layout size of a component exceeds the size of its parent component. - [Swiper](ts-container-swiper.md) @@ -79,9 +79,9 @@ ## Navigation -- [Navigator](ts-container-navigator.md) +- [Navigator](ts-container-navigator.md) - A container that provides redirection. + A container that provides redirection. - [Navigation](ts-basic-components-navigation.md) A container that typically functions as the root container of a page and displays the title bar, toolbar, and navigation bar based on the attribute settings. @@ -293,7 +293,7 @@ A component that is used to display widgets. - [Menu](ts-basic-components-menu.md) - A component that is used to present a vertical list of items to the user. + A component that is used to present a vertical list of items to the user. - [MenuItem](ts-basic-components-menuitem.md) A component that is used to represent an item in a menu. diff --git a/en/application-dev/reference/arkui-ts/ts-container-ability-component.md b/en/application-dev/reference/arkui-ts/ts-container-ability-component.md index b4bb994bf095875fc9fe39a0bdd0ff1b86117e67..97b7f95f9818531355166d46b0ca5f7f5988fd6e 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-ability-component.md +++ b/en/application-dev/reference/arkui-ts/ts-container-ability-component.md @@ -29,9 +29,9 @@ AbilityComponent(want: Want) **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](../apis/js-apis-app-ability-want.md) | Yes| Description of the default ability to load.| +| Name | Type | Mandatory | Description | +| ---- | ---------------------------------------- | ---- | --------------- | +| want | [Want](../apis/js-apis-app-ability-want.md) | Yes | Description of the default ability to load.| ## Events @@ -74,5 +74,3 @@ struct MyComponent { } } ``` - - \ No newline at end of file diff --git a/en/application-dev/reference/arkui-ts/ts-container-badge.md b/en/application-dev/reference/arkui-ts/ts-container-badge.md index 1984ff242a64a9e8360e6ef2064e84211bd6d0d5..78c8f0060a334c71b476f36fedac5d194213fb8a 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-badge.md +++ b/en/application-dev/reference/arkui-ts/ts-container-badge.md @@ -2,7 +2,7 @@ The **\** component is a container that can be attached to another component for tagging. -> **NOTE** +> **NOTE** > > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. @@ -11,6 +11,10 @@ The **\** component is a container that can be attached to another compon This component supports only one child component. +> **NOTE** +> +> Built-in components and custom components are allowed, with support for ([if/else](../../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../../quick-start/arkts-rendering-control-foreach.md), and [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md)) rendering control. + ## APIs @@ -22,12 +26,12 @@ Since API version 9, this API is supported in ArkTS widgets. **Parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| count | number | Yes| - | Number of notifications.| -| position | [BadgePosition](#badgeposition) | No| BadgePosition.RightTop | Position to display the badge relative to the parent component.| -| maxCount | number | No| 99 | Maximum number of notifications. When the maximum number is reached, only **maxCount+** is displayed.| -| style | [BadgeStyle](#badgestyle) | Yes| - | Style of the badge, including the font color, font size, badge color, and badge size.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| count | number | Yes| Number of notifications.
**NOTE**
If the value is less than or equal to 0, no badge is displayed.
Value range: [-2147483648, 2147483647]
If the value is not an integer, it is rounded off to the nearest integer. For example, 5.5 is rounded off to 5.| +| position | [BadgePosition](#badgeposition) | No| Position to display the badge relative to the parent component.
Default value: **BadgePosition.RightTop**| +| maxCount | number | No| Maximum number of notifications. When the maximum number is reached, only **maxCount+** is displayed.
Default value: **99**
Value range: [-2147483648, 2147483647]
If the value is not an integer, it is rounded off to the nearest integer. For example, 5.5 is rounded off to 5.| +| style | [BadgeStyle](#badgestyle) | Yes| Style of the badge, including the font color, font size, badge color, and badge size.| **API 2**: Badge(value: {value: string, position?: BadgePosition, style: BadgeStyle}) @@ -57,15 +61,23 @@ Since API version 9, this API is supported in ArkTS widgets. Since API version 9, this API is supported in ArkTS widgets. -| Name | Type | Mandatory| Default Value | Description | -| ------------------------- | ------------------------------------------------------------ | ---- | ----------------- | ------------------------------------------------------------ | -| color | [ResourceColor](ts-types.md#resourcecolor) | No | Color.White | Font color. | -| fontSize | number \| string | No | 10 | Font size, in vp. | -| badgeSize | number \| string | No | 16 | Badge size, in vp. This parameter cannot be set in percentage. If it is set to an invalid value, the default value is used.| -| badgeColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color.Red | Badge color. | -| fontWeight10+ | number \|[FontWeight](ts-appendix-enums.md#fontweight) \| string | No | FontWeight.Normal | Font weight of the text. | -| borderColor10+ | [ResourceColor](ts-types.md#resourcecolor) | No | Color.Red | Border color of the background. | -| borderWidth10+ | [Length](ts-types.md#length) | No | 1.0vp | Border width of the background. | +| Name | Type | Mandatory| Description | +| ------------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| color | [ResourceColor](ts-types.md#resourcecolor) | No | Font color.
Default value: **Color.White** | +| fontSize | number \| string | No | Font size.
Default value: **10**
Unit: vp
**NOTE**
This parameter cannot be set in percentage.| +| badgeSize | number \| string | No | Badge size.
Default value: **16**
Unit: vp
**NOTE**
This parameter cannot be set in percentage. If it is set to an invalid value, the default value is used.| +| badgeColor | [ResourceColor](ts-types.md#resourcecolor) | No | Badge color.
Default value: **Color.Red** | +| fontWeight10+ | number \|[FontWeight](ts-appendix-enums.md#fontweight) \| string | No | Font weight of the text.
Default value: **FontWeight.Normal**
**NOTE**
This parameter cannot be set in percentage.| +| borderColor10+ | [ResourceColor](ts-types.md#resourcecolor) | No | Border color of the background. | +| borderWidth10+ | [Length](ts-types.md#length) | No | Border width of the background.
Default value: **1**
Unit: vp
**NOTE**
This parameter cannot be set in percentage.| + +## Attributes + +The [universal attributes](ts-universal-attributes-size.md) are supported. + +## Events + +The [universal events](ts-universal-events-click.md) are supported. ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-container-counter.md b/en/application-dev/reference/arkui-ts/ts-container-counter.md index d23e6938ae1328dd127f5dbf2aee5ad559ea1f8c..fe6f3cbc13fc8a613102a933b2dac061b37ba3d9 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-counter.md +++ b/en/application-dev/reference/arkui-ts/ts-container-counter.md @@ -2,7 +2,7 @@ The **\** component provides an operation to increase or decrease the number. -> **NOTE** +> **NOTE** > > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. @@ -29,7 +29,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ## Events -The universal events and gestures are not supported. Only the following events are supported. +In addition to the [universal events](ts-universal-events-click.md), the following events are supported. | Name| Description| | -------- | -------- | diff --git a/en/application-dev/reference/arkui-ts/ts-container-grid.md b/en/application-dev/reference/arkui-ts/ts-container-grid.md index f301c9b24eb7e972431287906c16d3eecbd87ccb..db50a0ea98c0a306e2684a5882c1b5d5b18327a7 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-grid.md +++ b/en/application-dev/reference/arkui-ts/ts-container-grid.md @@ -44,8 +44,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | -| columnsTemplate | string | Number of columns in the current grid layout. If this attribute is not set, one column is used by default.
For example, **'1fr 1fr 2fr'** indicates three columns, with the first column taking up 1/4 of the parent component's full width, the second column 1/4, and the third column 2/4.
**NOTE**
If this attribute is set to **'0fr'**, the column width is 0, and grid item in the column is not displayed. If this attribute is set to any other invalid value, the grid item is displayed as one column.| -| rowsTemplate | string | Number of rows in the current grid layout. If this attribute is not set, one row is used by default.
For example, **'1fr 1fr 2fr'** indicates three rows, with the first row taking up 1/4 of the parent component's full height, the second row 1/4, and the third row 2/4.
**NOTE**
If this attribute is set to **'0fr'**, the row width is 0, and grid item in the row is not displayed. If this attribute is set to any other invalid value, the grid item is displayed as one row.| +| columnsTemplate | string | Number of columns in the current grid layout. If this attribute is not set, one column will be used.
For example, **'1fr 1fr 2fr'** indicates three columns, with the first column taking up 1/4 of the parent component's full width, the second column 1/4, and the third column 2/4.
**NOTE**
If this attribute is set to **'0fr'**, the column width is 0, and grid item in the column is not displayed. If this attribute is set to any other invalid value, the grid item is displayed as one column.| +| rowsTemplate | string | Number of rows in the current grid layout. If this attribute is not set, one row will be used.
For example, **'1fr 1fr 2fr'** indicates three rows, with the first row taking up 1/4 of the parent component's full height, the second row 1/4, and the third row 2/4.
**NOTE**
If this attribute is set to **'0fr'**, the row width is 0, and grid item in the row is not displayed. If this attribute is set to any other invalid value, the grid item is displayed as one row.| | columnsGap | [Length](ts-types.md#length) | Gap between columns.
Default value: **0**
**NOTE**
A value less than 0 evaluates to the default value.| | rowsGap | [Length](ts-types.md#length) | Gap between rows.
Default value: **0**
**NOTE**
A value less than 0 evaluates to the default value.| | scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.
Default value: **BarState.Off**
**NOTE**
In API version 9 and earlier versions, the default value is **BarState.Off**. In API version 10, the default value is **BarState.Auto**.| @@ -60,6 +60,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | multiSelectable8+ | boolean | Whether to enable mouse frame selection.
Default value: **false**
- **false**: The mouse frame selection is disabled.
- **true**: The mouse frame selection is enabled.| | supportAnimation8+ | boolean | Whether to enable animation. Currently, the grid item drag animation is supported.
Default value: **false**| | edgeEffect10+ | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. The spring effect and shadow effect are supported.
Default value: **EdgeEffect.None**
| +| enableScrollInteraction10+ | boolean | Whether to support scroll gestures. When this attribute is set to **false**, scrolling by finger or mouse is not supported, but the scrolling controller API is not affected.
Default value: **true** | Depending on the settings of the **rowsTemplate** and **columnsTemplate** attributes, the **\** component supports the following layout modes: @@ -116,12 +117,13 @@ In addition to the [universal events](ts-universal-events-click.md), the followi | Name| Description| | -------- | -------- | -| onScrollIndex(event: (first: number) => void) | Triggered when the start item of the grid changes. It is triggered once when the grid is initialized.
- **first**: index of the start item of the grid.
If it changes, this event will be triggered.| -| onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => (() => any) \| void) | Triggered when a grid item starts to be dragged.
- **event**: See [ItemDragInfo](#itemdraginfo).
- **itemIndex**: index of the dragged element.
**NOTE**
If **void** is returned, the drag operation cannot be performed.
This event is triggered when the user long presses a grid item.| +| onScrollIndex(event: (first: number) => void) | Triggered when the first item displayed in the grid changes. It is triggered once when the grid is initialized.
- **first**: index of the first item of the grid.
If it changes, this event will be triggered.| +| onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => (() => any) \| void) | Triggered when a grid item starts to be dragged.
- **event**: See [ItemDragInfo](#itemdraginfo).
- **itemIndex**: index of the dragged item.
**NOTE**
If **void** is returned, the drag operation cannot be performed.
This event is triggered when the user long presses a grid item.| | onItemDragEnter(event: (event: ItemDragInfo) => void) | Triggered when the dragged item enters the drop target of the grid.
- **event**: See [ItemDragInfo](#itemdraginfo).| | onItemDragMove(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number) => void) | Triggered when the dragged item moves over the drop target of the grid.
- **event**: See [ItemDragInfo](#itemdraginfo).
- **itemIndex**: initial position of the dragged item.
- **insertIndex**: index of the position to which the dragged item will be dropped.| -| onItemDragLeave(event: (event: ItemDragInfo, itemIndex: number) => void) | Triggered when the dragged item exits the drop target of the grid.
- **event**: See [ItemDragInfo](#itemdraginfo).
- **itemIndex**: index of the dragged item.| +| onItemDragLeave(event: (event: ItemDragInfo, itemIndex: number) => void) | Triggered when the dragged item leaves the drop target of the grid.
- **event**: See [ItemDragInfo](#itemdraginfo).
- **itemIndex**: index of the dragged item.| | onItemDrop(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => void) | Triggered when the dragged item is dropped on the drop target of the grid.
- **event**: See [ItemDragInfo](#itemdraginfo).
- **itemIndex**: initial position of the dragged item.
- **insertIndex**: index of the position to which the dragged item will be dropped.
- **isSuccess**: whether the dragged item is successfully dropped.| +| onScrollBarUpdate(event: (index: number, offset: number) => ComputedBarAttribute) | Triggered when the first item displayed in the grid changes. You can use this callback to set the position and length of the scrollbar.
- **index**: index of the first item displayed in the grid.
- **offset**: offset of the displayed first item relative to the start position of the grid.
- **ComputedBarAttribute**: See [ComputedBarAttribute](#computedbarattribute). | ## ItemDragInfo @@ -130,6 +132,13 @@ In addition to the [universal events](ts-universal-events-click.md), the followi | x | number | X coordinate of the dragged item. | | y | number | Y coordinate of the dragged item. | +## ComputedBarAttribute + +| Name | Type | Description | +| ---------- | ---------- | ---------- | +| totalOffset | number | Total offset of the grid content relative to the display area. | +| totalLength | number | Total length of the grid content. | + ## Example ```ts @@ -186,9 +195,13 @@ struct GridExample { .onScrollIndex((first: number) => { console.info(first.toString()) }) + .onScrollBarUpdate((index: number, offset: number) => { + return {totalOffset: (index / 5) * (80 + 10) - 10 + offset, totalLength: 80 * 5 + 10 * 4} + }) .width('90%') .backgroundColor(0xFAEEE0) .height(300) + .scrollBar(BarState.Off) Button('next page') .onClick(() => {// Click to go to the next page. this.scroller.scrollPage({ next: true }) diff --git a/en/application-dev/reference/arkui-ts/ts-container-list.md b/en/application-dev/reference/arkui-ts/ts-container-list.md index e20063ba938358602853548c86cfba6275e0620a..0456b0eabd821d1df0d4996900b88b98d8aed26d 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-list.md +++ b/en/application-dev/reference/arkui-ts/ts-container-list.md @@ -39,37 +39,38 @@ Since API version 9, this API is supported in ArkTS widgets. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| space | number \| string | No| Spacing between list items along the main axis.
Default value: **0**
**NOTE**
If this parameter is set to a percentage or a negative number other than -1, the default value is used.
If the value of **space** is less than the width of the list divider, the latter is used as the spacing.| -| initialIndex | number | No| Item displayed at the beginning of the viewport when the current list is loaded for the first time, that is, the first item to be displayed.
Default value: **0**
**NOTE**
If this parameter is set to a negative value other than -1 or is greater than the index value of the last item in the current list, the value is invalid. In this case, the default value is used.| -| scroller | [Scroller](ts-container-scroll.md#scroller) | No| Scroller, which can be bound to scrollable components.
**NOTE**
The scroller cannot be bound to other scrollable components.| +| Name | Type | Mandatory | Description | +| ------------ | ---------------------------------------- | ---- | ---------------------------------------- | +| space | number \| string | No | Spacing between list items along the main axis.
Default value: **0**
**NOTE**
If the set value is a negative number, the default value will be used.
If the value of **space** is less than the width of the list divider, the latter is used as the spacing.| +| initialIndex | number | No | Item displayed at the beginning of the viewport when the current list is loaded for the first time, that is, the first item to be displayed.
Default value: **0**
**NOTE**
If the set value is a negative number or is greater than the index of the last item in the list, the value is invalid. In this case, the default value will be used.| +| scroller | [Scroller](ts-container-scroll.md#scroller) | No | Scroller, which can be bound to scrollable components.
**NOTE**
The scroller cannot be bound to other scrollable components.| ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name| Type| Description| -| -------- | -------- | -------- | -| listDirection | [Axis](ts-appendix-enums.md#axis) | Direction in which the list items are arranged.
Default value: **Axis.Vertical**
Since API version 9, this API is supported in ArkTS widgets.| -| divider | {
strokeWidth: [Length](ts-types.md#length),
color?:[ResourceColor](ts-types.md#resourcecolor),
startMargin?: Length,
endMargin?: Length
} \| null | Style of the divider for the list items. By default, there is no divider.
- **strokeWidth**: stroke width of the divider.
- **color**: color of the divider.
- **startMargin**: distance between the divider and the start edge of the list.
- **endMargin**: distance between the divider and the end edge of the list.
Since API version 9, this API is supported in ArkTS widgets.
The sum of **endMargin** and **startMargin** cannot exceed the column width.
**startMargin** and **endMargin** cannot be set in percentage.
The divider is drawn between list items along the main axis, and not above the first list item and below the last list item.
In multi-column mode, the value of **startMargin** is calculated from the start edge of the cross axis of each column. In other cases, it is calculated from the start edge of the cross axis of the list.| -| scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.
Default value: **BarState.Off**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
In API version 9 and earlier versions, the default value is **BarState.Off**. In API version 10, the default value is **BarState.Auto**.| -| cachedCount | number | Number of list items or list item groups to be preloaded (cached). It works only in [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md). A list item group is calculated as a whole, and all list items of the group are preloaded at the same time. For details, see [Minimizing White Blocks During Swiping](../../ui/arkts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).
Default value: **1**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
In single-column mode, the number of the list items to be cached before and after the currently displayed one equals the value of **cachedCount**.
In multi-column mode, the number of the list items to be cached is the value of **cachedCount** multiplied by the number of columns.| -| editMode(deprecated) | boolean | Whether to enter editing mode.
This API is deprecated since API version 9. For details about how to implement deletion of a selected list item, see [Example 3](#example-3).
Default value: **false**| -| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. The spring effect and shadow effect are supported.
Default value: **EdgeEffect.Spring**
Since API version 9, this API is supported in ArkTS widgets.| -| chainAnimation | boolean | Whether to display chained animations on this list when it slides or its top or bottom is dragged. The list items are separated with even space, and one item animation starts after the previous animation during basic sliding interactions. The chained animation effect is similar with spring physics.
Default value: **false**
- **false**: No chained animations are displayed.
- **true**: Chained animations are displayed.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When chained animations are in motion, the list divider is not displayed.
The following prerequisites must be met for the chained animations to take effect:
- The edge effect of the list is of the Spring type.
- The multi-column mode is not enabled for the list.| -|chainAnimationOptions10+| [ChainAnimationOptions](#chainanimationoptions10) | Chained animation settings.
**System API**: This is a system API.| -| multiSelectable8+ | boolean | Whether to enable mouse frame selection.
Default value: **false**
- **false**: The mouse frame selection is disabled.
- **true**: The mouse frame selection is enabled.
Since API version 9, this API is supported in ArkTS widgets.| -| lanes9+ | number \| [LengthConstrain](ts-types.md#lengthconstrain) | In the following description, **listDirection** is set to **Axis.Vertical**:
Number of columns in which the list items are arranged along the cross axis.
Default value: **1**
The rules are as follows:
- If the value is set to a number, the column width is calculated by dividing the cross-axis width of the **\** component by the specified number.
- If the value is set to {minLength, maxLength}, the number of columns is adjusted adaptively based on the width of the **\** component, ensuring that the width respects the {minLength, maxLength} constraints during adaptation. The **minLength** constraint is prioritized.
- If the value is set to {minLength, maxLength}, and the cross-axis width constraint of the parent component is infinite, the parent component is arranged by column, and the column width is calculated based on the largest list item in the display area.
- Each list item group occupies one row in multi-column mode. Its child list items are arranged based on the **lanes** attribute of the list.
- If the value is set to {minLength, maxLength}, the number of columns is calculated based on the cross-axis width of the list item group. If the cross-axis width of the list item group is different from that of the list, the number of columns in the list item group may be different from that in the list.
This API is supported in ArkTS widgets.| -| alignListItem9+ | [ListItemAlign](#listitemalign9) | Alignment mode of list items along the cross axis when: Cross-axis width of the **\** component > Cross-axis width of list items x Value of **lanes**.
Default value: **ListItemAlign.Start**
This API is supported in ArkTS widgets.| -| sticky9+ | [StickyStyle](#stickystyle9) | Whether to pin the header to the top or the footer to the bottom in the **\** component. This attribute is used together with the **[\](ts-container-listitemgroup.md)** component.
Default value: **StickyStyle.None**
This API is supported in ArkTS widgets.
**NOTE**
The **sticky** attribute can be set to **StickyStyle.Header** or \| **StickyStyle.Footer** to support both the pin-to-top and pin-to-bottom features.| +| Name | Type | Description | +| ----------------------------------- | ---------------------------------------- | ---------------------------------------- | +| listDirection | [Axis](ts-appendix-enums.md#axis) | Direction in which the list items are arranged.
Default value: **Axis.Vertical**
Since API version 9, this API is supported in ArkTS widgets.| +| divider | {
strokeWidth: [Length](ts-types.md#length),
color?:[ResourceColor](ts-types.md#resourcecolor),
startMargin?: Length,
endMargin?: Length
} \| null | Style of the divider for the list items. By default, there is no divider.
- **strokeWidth**: stroke width of the divider.
- **color**: color of the divider.
- **startMargin**: distance between the divider and the start edge of the list.
- **endMargin**: distance between the divider and the end edge of the list.
Since API version 9, this API is supported in ArkTS widgets.
The sum of **endMargin** and **startMargin** cannot exceed the column width.
**startMargin** and **endMargin** cannot be set in percentage.
The divider is drawn between list items along the main axis, and not above the first list item and below the last list item.
In multi-column mode, the value of **startMargin** is calculated from the start edge of the cross axis of each column. In other cases, it is calculated from the start edge of the cross axis of the list.| +| scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.
Default value: **BarState.Off**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
In API version 9 and earlier versions, the default value is **BarState.Off**. In API version 10, the default value is **BarState.Auto**.| +| cachedCount | number | Number of list items or list item groups to be preloaded (cached). It works only in [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md). A list item group is calculated as a whole, and all list items of the group are preloaded at the same time. For details, see [Minimizing White Blocks During Swiping](../../ui/arkts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).
Default value: **1**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
In single-column mode, the number of the list items to be cached before and after the currently displayed one equals the value of **cachedCount**.
In multi-column mode, the number of the list items to be cached is the value of **cachedCount** multiplied by the number of columns.| +| editMode(deprecated) | boolean | Whether to enter editing mode.
This API is deprecated since API version 9. For details about how to implement deletion of a selected list item, see [Example 3](#example-3).
Default value: **false**| +| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. The spring effect and shadow effect are supported.
Default value: **EdgeEffect.Spring**
Since API version 9, this API is supported in ArkTS widgets.| +| chainAnimation | boolean | Whether to display chained animations on this list when it slides or its top or bottom is dragged. The list items are separated with even space, and one item animation starts after the previous animation during basic sliding interactions. The chained animation effect is similar with spring physics.
Default value: **false**
- **false**: No chained animations are displayed.
- **true**: Chained animations are displayed.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When chained animations are in motion, the list divider is not displayed.
The following prerequisites must be met for the chained animations to take effect:
- The edge effect of the list is of the Spring type.
- The multi-column mode is not enabled for the list.| +| chainAnimationOptions10+ | [ChainAnimationOptions](#chainanimationoptions10) | Chained animation settings.
**System API**: This is a system API. | +| multiSelectable8+ | boolean | Whether to enable mouse frame selection.
Default value: **false**
- **false**: The mouse frame selection is disabled.
- **true**: The mouse frame selection is enabled.
Since API version 9, this API is supported in ArkTS widgets.| +| lanes9+ | number \| [LengthConstrain](ts-types.md#lengthconstrain) | In the following description, **listDirection** is set to **Axis.Vertical**:
Number of columns in which the list items are arranged along the cross axis.
Default value: **1**
The rules are as follows:
- If the value is set to a number, the column width is calculated by dividing the cross-axis width of the **\** component by the specified number.
- If the value is set to {minLength, maxLength}, the number of columns is adjusted adaptively based on the width of the **\** component, ensuring that the width respects the {minLength, maxLength} constraints during adaptation. The **minLength** constraint is prioritized.
- If the value is set to {minLength, maxLength}, and the cross-axis width constraint of the parent component is infinite, the parent component is arranged by column, and the column width is calculated based on the largest list item in the display area.
- Each list item group occupies one row in multi-column mode. Its child list items are arranged based on the **lanes** attribute of the list.
- If the value is set to {minLength, maxLength}, the number of columns is calculated based on the cross-axis width of the list item group. If the cross-axis width of the list item group is different from that of the list, the number of columns in the list item group may be different from that in the list.
This API is supported in ArkTS widgets.| +| alignListItem9+ | [ListItemAlign](#listitemalign9) | Alignment mode of list items along the cross axis when: Cross-axis width of the **\** component > Cross-axis width of list items x Value of **lanes**.
Default value: **ListItemAlign.Start**
This API is supported in ArkTS widgets.| +| sticky9+ | [StickyStyle](#stickystyle9) | Whether to pin the header to the top or the footer to the bottom in the **\** component. This attribute is used together with the **[\](ts-container-listitemgroup.md)** component.
Default value: **StickyStyle.None**
This API is supported in ArkTS widgets.
**NOTE**
The **sticky** attribute can be set to **StickyStyle.Header** or \| **StickyStyle.Footer** to support both the pin-to-top and pin-to-bottom features.| +| enableScrollInteraction10+ | boolean | Whether to support scroll gestures. When this attribute is set to **false**, scrolling by finger or mouse is not supported, but the scrolling controller API is not affected.
Default value: **true** | ## ListItemAlign9+ This API is supported in ArkTS widgets. -| Name | Description | -| ------ | -------------------------------------- | +| Name | Description | +| ------ | ------------------------- | | Start | The list items are packed toward the start edge of the **\** component along the cross axis.| | Center | The list items are centered in the **\** component along the cross axis.| | End | The list items are packed toward the end edge of the **\** component along the cross axis.| @@ -78,11 +79,11 @@ This API is supported in ArkTS widgets. This API is supported in ArkTS widgets. -| Name | Description | -| ------ | -------------------------------------- | -| None | In the **\** component, the header is not pinned to the top, and the footer is not pinned to the bottom.| -| Header | In the **\** component, the header is pinned to the top, and the footer is not pinned to the bottom.| -| Footer | In the **\** component, the footer is pinned to the bottom, and the header is not pinned to the top.| +| Name | Description | +| ------ | ---------------------------------- | +| None | In the **\** component, the header is not pinned to the top, and the footer is not pinned to the bottom.| +| Header | In the **\** component, the header is pinned to the top, and the footer is not pinned to the bottom. | +| Footer | In the **\** component, the footer is pinned to the bottom, and the header is not pinned to the top. | ## ChainEdgeEffect10+ @@ -90,10 +91,10 @@ Describes the chained animation edge effect. **System API**: This is a system API. -| Name | Description | -| ------ | -------------------------------------- | -| DEFAULT | Default effect. After the list is scrolled to the edge, a continued drag of the list will result in reduced spacing between the list items in the drag direction and increased spacing between the list items in the direction opposite to the drag direction.| -| STRETCH | After the list is scrolled to the edge, a continued drag of the list result in increased spacing between all the list items.| +| Name | Description | +| ------- | ---------------------------------------- | +| DEFAULT | Default effect. After the list is scrolled to the edge, a continued drag of the list will result in reduced spacing between the list items in the drag direction and increased spacing between the list items in the direction opposite to the drag direction.| +| STRETCH | After the list is scrolled to the edge, a continued drag of the list result in increased spacing between all the list items. | ## chainAnimationOptions10+ @@ -101,13 +102,13 @@ Provides the chained animation settings, which cover the maximum spacing, minimu **System API**: This is a system API. -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------- | -| minSpace | [Length](ts-types.md#length) | Yes | Minimum spacing between the chained animations.| -| maxSpace | [Length](ts-types.md#length) | Yes | Maximum spacing between the chained animations.| -| conductivity | number | No | Conductivity of the chained animations. The value range is [0,1]. A larger value indicates higher conductivity.
Default value: **0.7** | -| intensity | number | No | Intensity of the chained animations. The value range is [0,1]. A larger value indicates more obvious animations.
Default value: **0.3**| -| edgeEffect | [ChainEdgeEffect](#chainedgeeffect10)| No| Chained animation edge effect.
Default value: **ChainEdgeEffect.DEFAULT**| +| Name | Type | Mandatory | Description | +| ------------ | ---------------------------------------- | ---- | ---------------------------------------- | +| minSpace | [Length](ts-types.md#length) | Yes | Minimum spacing between the chained animations. | +| maxSpace | [Length](ts-types.md#length) | Yes | Maximum spacing between the chained animations. | +| conductivity | number | No | Conductivity of the chained animations. The value range is [0,1]. A larger value indicates higher conductivity.
Default value: **0.7**| +| intensity | number | No | Intensity of the chained animations. The value range is [0,1]. A larger value indicates more obvious animations.
Default value: **0.3**| +| edgeEffect | [ChainEdgeEffect](#chainedgeeffect10)| No | Chained animation edge effect.
Default value: **ChainEdgeEffect.DEFAULT**| > **NOTE** > @@ -115,16 +116,16 @@ Provides the chained animation settings, which cover the maximum spacing, minimu ## Events -| Name| Description| -| -------- | -------- | +| Name | Description | +| ---------------------------------------- | ---------------------------------------- | | onItemDelete(deprecated)(event: (index: number) => boolean) | Triggered when a list item is deleted.
This API is deprecated since API version 9.
- **index**: index of the deleted list item.| | onScroll(event: (scrollOffset: number, scrollState: ScrollState) => void) | Triggered when the list scrolls.
- **scrollOffset**: scroll offset of each frame. The offset is positive when the list is scrolled up and negative when the list is scrolled down.
- **[scrollState](#scrollstate)**: current scroll state.
This event is not triggered when **ScrollEdge** and **ScrollToIndex** are called by using the controller. In other cases, this event is triggered when scrolling occurs.
Since API version 9, this API is supported in ArkTS widgets.| | onScrollIndex(event: (start: number, end: number) => void) | Triggered when a child component enters or leaves the list display area.
During index calculation, each **\** component is taken as a whole and assigned an index, and the indexes of the list items within are not included in the calculation.
- **start**: index of the scroll start position.
- **end**: index of the scroll end position.
This event is triggered once when the list is initialized and when the index of the first list item or the next list item in the list display area changes.
When the list edge effect is the spring effect, the **onScrollIndex** event is not triggered when the user scrolls the list to the edge or releases the list to rebound.
Since API version 9, this API is supported in ArkTS widgets.| -| onReachStart(event: () => void) | Triggered when the list reaches the start position.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This event is triggered once when **initialIndex** is **0** during list initialization and once when the list scrolls to the start position. When the list edge effect is the spring effect, this event is triggered once when the list passes the start position and is triggered again when the list returns to the start position.| -| onReachEnd(event: () => void) | Triggered when the list reaches the end position.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When the list edge effect is the spring effect, this event is triggered once when the list passes the end position and is triggered again when the list returns to the end position.| +| onReachStart(event: () => void) | Triggered when the list reaches the start position.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This event is triggered once when **initialIndex** is **0** during list initialization and once when the list scrolls to the start position. When the list edge effect is the spring effect, this event is triggered once when the list passes the start position and is triggered again when the list returns to the start position.| +| onReachEnd(event: () => void) | Triggered when the list reaches the end position.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When the list edge effect is the spring effect, this event is triggered once when the list passes the end position and is triggered again when the list returns to the end position.| | onScrollFrameBegin9+(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when the list starts to scroll. The input parameters indicate the amount by which the list will scroll. The event handler then works out the amount by which the list needs to scroll based on the real-world situation and returns the result.
\- **offset**: amount to scroll by, in vp.
\- **state**: current sliding status.
- **offsetRemain**: actual amount by which the list scrolls, in vp.
This event is triggered when the user starts dragging the list or the list starts inertial scrolling. This event is not triggered when the list rebounds or the scrolling controller is used.
This API is supported in ArkTS widgets.
**NOTE**
If **listDirection** is set to **Axis.Vertical**, the return value is the amount by which the list needs to scroll in the vertical direction. If **listDirection** is set to **Axis.Horizontal**, the return value is the amount by which the list needs to scroll in the horizontal direction.| | onScrollStart9+(event: () => void) | Triggered when the list starts scrolling initiated by the user's finger dragging the **\** component or its scrollbar. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](ts-container-scroll.md#scroller) starts.
This API is supported in ArkTS widgets.| -| onScrollStop(event: () => void) | Triggered when the list stops scrolling after the user's finger leaves the screen. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](ts-container-scroll.md#scroller) stops.
Since API version 9, this API is supported in ArkTS widgets.| +| onScrollStop(event: () => void) | Triggered when the list stops scrolling after the user's finger leaves the screen. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](ts-container-scroll.md#scroller) stops.
Since API version 9, this API is supported in ArkTS widgets.| | onItemMove(event: (from: number, to: number) => boolean) | Triggered when a list item moves.
- **from**: index of the item before moving.
- **to**: index of the item after moving.| | onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => ((() => any) \| void) | Triggered when a list element starts to be dragged.
- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).
- **itemIndex**: index of the dragged list element.| | onItemDragEnter(event: (event: ItemDragInfo) => void) | Triggered when the dragged item enters the drop target of the list.
- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).| @@ -136,11 +137,11 @@ Provides the chained animation settings, which cover the maximum spacing, minimu Since API version 9, this API is supported in ArkTS widgets. -| Name | Description | -| ------ | ------------------------- | -| Idle | Not scrolling. Triggered when the API provided by the controller is used to scroll the list or when the scrollbar is dragged.| -| Scroll | Finger dragging. Triggered when the user drags the list to scroll.| -| Fling | Inertial scrolling. Triggered when inertial scrolling occurs or when the list bounces back after being released from a quick swipe.| +| Name | Description | +| ------ | ------------------------------ | +| Idle | Not scrolling. Triggered when the API provided by the controller is used to scroll the list or when the scrollbar is dragged. | +| Scroll | Finger dragging. Triggered when the user drags the list to scroll. | +| Fling | Inertial scrolling. Triggered when inertial scrolling occurs or when the list bounces back after being released from a quick swipe.| > **NOTE** > @@ -158,8 +159,9 @@ Since API version 9, this API is supported in ArkTS widgets. > > - The list item is bound to the **onDragStart** event and the event returns a floating UI during event callback. +## Example -## Example 1 +### Example 1 ```ts // xxx.ets @@ -180,6 +182,7 @@ struct ListExample { }, item => item) } .listDirection(Axis.Vertical) // Arrangement direction + .scrollBar(BarState.Off) .divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) // Divider .edgeEffect(EdgeEffect.Spring) // No effect when the list scrolls to the edge. .onScrollIndex((firstIndex: number, lastIndex: number) => { @@ -199,7 +202,7 @@ struct ListExample { ![en-us_image_0000001174264378](figures/en-us_image_0000001174264378.gif) -## Example 2 +### Example 2 ```ts // xxx.ets @@ -230,6 +233,7 @@ struct ListLanesExample { .border({ width: 3, color: Color.Red }) .lanes({ minLength: 40, maxLength: 40 }) .alignListItem(this.alignListItem) + .scrollBar(BarState.Off) Button("Change alignListItem: "+ this.alignListItem).onClick(() => { if (this.alignListItem == ListItemAlign.Start) { @@ -248,7 +252,7 @@ struct ListLanesExample { ![list](figures/list1.gif) -## Example 3 +### Example 3 ```ts // xxx.ets @@ -288,6 +292,7 @@ struct ListExample{ } }, item => item) }.width('90%') + .scrollBar(BarState.Off) }.width('100%') Button('edit list') diff --git a/en/application-dev/reference/arkui-ts/ts-container-listitem.md b/en/application-dev/reference/arkui-ts/ts-container-listitem.md index 97f1d9faf82279e83ed14f7388c6b495fa6e948a..c54b6e0ee78b9ee062639e1ba966e75566bda5e8 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-listitem.md +++ b/en/application-dev/reference/arkui-ts/ts-container-listitem.md @@ -11,13 +11,28 @@ The **\** component displays specific items in the list. It must be us This component can contain a single child component. - ## APIs -ListItem(value?: string) - Since API version 9, this API is supported in ArkTS widgets. +**API 1**: ListItem(value?: ListItemOptions)10+ + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| value | [ListItemOptions](#listitemoptions10) | No | Value of the list item, containing the **style** parameter of the **ListItemStyle**enum type.| + +**API 2**: ListItem(value?: string)(deprecated) + +This API is deprecated since API version 10. You are advised to use API 1 instead. + +**Parameters** + +| Name| Type | Mandatory| Description| +| ------ | ----------------------------- | ---- | -------- | +| value | string(deprecated) | No | N/A | + ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. @@ -27,7 +42,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | sticky(deprecated) | [Sticky](#stickydeprecated) | Sticky effect of the list item.
Default value: **Sticky.None**
This API is deprecated since API version 9. You are advised to use **sticky** of the [\](ts-container-list.md#attributes) component.| | editable(deprecated) | boolean \| [EditMode](#editmodedeprecated) | Whether to enter editing mode, where the list item can be deleted or moved.
This API is deprecated since API version 9.
Default value: **false**| | selectable8+ | boolean | Whether the current list item is selectable by mouse drag.
**NOTE**
This attribute takes effect only when mouse frame selection is enabled for the parent **\** container.
Default value: **true**| -| swipeAction9+ | {
start?: CustomBuilder,
end?:CustomBuilder,
edgeEffect?: [SwipeEdgeEffect](#swipeedgeeffect9),
} | Component displayed when the list item is swiped out from the screen edge.
- **start**: component on the left of the list item when the item is swiped to the right (in vertical list layout) or component above the list item when the item is swiped down (in horizontal list layout).
- **end**: component on the right of the list item when the item is swiped to the left (in vertical list layout) or component below the list item when the item is swiped up (in horizontal list layout).
- **edgeEffect**: scroll effect.
**NOTE**
The top level of the **@builder** function corresponding to **start** and **end** must be a single component and cannot be an **if/else**, **ForEach**, or **LazyForEach** statement.| +| swipeAction9+ | {
start?: CustomBuilder \| [SwipeActionItem](#swipeactionitem10),
end?:CustomBuilder \| [SwipeActionItem](#swipeactionitem10),
edgeEffect?: [SwipeEdgeEffect](#swipeedgeeffect9),
} | Swipe action displayed when the list item is swiped out from the screen edge.
- **start**: swipe action displayed on the left of the list item when the item is swiped right (in vertical list layout) or above the list item when the item is swiped down (in horizontal list layout).
- **end**: swipe action displayed on the right of the list item when the item is swiped left (in vertical list layout) or below the list item when the item is swiped up (in horizontal list layout).
- **edgeEffect**: scroll effect.
**NOTE**
- The top level of the **@builder** function corresponding to **start** and **end** must be a single component and cannot be an **if/else**, **ForEach**, or **LazyForEach** statement.
- The swipe gesture works only in the list item area. If a swipe causes a child component to extend beyond the list item area, the portion outside the area does not respond to the swipe. In light of this, avoid setting **swipeAction** to a component too wide in a multi-column list. | ## Sticky(deprecated) This API is deprecated since API version 9. You are advised to use [stickyStyle](ts-container-list.md#stickystyle9) of the **\** component. @@ -48,8 +63,36 @@ This API is deprecated since API version 9. ## SwipeEdgeEffect9+ | Name| Description| | -------- | -------- | -| Spring | When the list item scrolls to the edge of the list, it can continue to scroll for a distance and rebound after being released.| -| None | The list item cannot scroll beyond the edge of the list| +| Spring | When the list item scrolls to the edge of the list, it can continue to scroll for a distance. If the delete area is set, the list item can continue to scroll after the scroll distance reaches the delete threshold and, after being released, rebound following the spring curve.| +| None | The list item cannot scroll beyond the edge of the list. If the delete area is set, the list item cannot continue to scroll after the scroll distance reaches the delete threshold. If the delete callback is set, it is triggered when the delete threshold is reached and the list item is released.| + +## SwipeActionItem10+ +Describes the swipe action item. + +For a list in vertical layout, it refers to the delete item displayed on the left (or right) of the list item when the list item is swiped right (or left). + +For a list in horizontal layout, it refers to the delete item displayed below (or above) the list item when the list item is swiped up (or down). + +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| deleteAreaDistance | [Length](ts-types.md#length) | No| Swipe distance threshold for deleting the list item.
Default value: **56vp**
**NOTE**
This parameter cannot be set in percentage.
If the value is greater than the list item width minus the width of **swipeAction**, or is less than or equal to 0, the delete area will not be set.| +| onDelete | () => void | No| Callback invoked when the list item is released while in the delete area.
**NOTE**
This callback is invoked only when the list item is released in a position that meets or goes beyond the specified swipe distance threshold (which must be valid) for deleting the list item.| +| onEntryDeleteArea | () => void | No| Callback invoked each time the list item enters the delete area.| +| onExitDeleteArea | () => void | No|Callback invoked each time the list item exits the delete area.| +| builder | CustomBuilder | No|Swipe action item displayed when the list item is swiped left or right (in vertical list layout) or up or down (in horizontal list layout).| +| useDefaultDeleteAnimation | boolean | No|Whether to use the default delete animation.
Default value: **true**| +## ListItemOptions10+ + +| Name | Type | Mandatory| Description | +| ----- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| style | [ListItemStyle](#listitemstyle10) | No | Style of the list item.
Default value: **ListItemStyle.NONE**
If this parameter is set to **ListItemStyle.NONE**, no style is applied.
If this parameter is set to **ListItemStyle.CARD**, the default card style is applied, but only when **ListItemGroupStyle.CARD** is set for [\](ts-container-listitemgroup.md).
In the default card style, the list item has a 48 vp height and 100% width. It can be in focus, hover, press, selected, or disable style depending on the state.
**NOTE**
In the default card style, the list has its **listDirection** attribute fixed at **Axis.Vertical** and **alignListItem** attribute at **ListItemAlign.Center**. | + +## ListItemStyle10+ + +| Name| Description | +| ---- | ------------------ | +| NONE | No style. | +| CARD | Default card style.| ## Events @@ -78,6 +121,7 @@ struct ListItemExample { } }, item => item) }.width('90%') + .scrollBar(BarState.Off) }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 }) } } @@ -85,45 +129,63 @@ struct ListItemExample { ![en-us_image_0000001219864159](figures/en-us_image_0000001219864159.gif) + ```ts // xxx.ets @Entry @Component struct ListItemExample2 { @State message: string = 'Hello World' + @State arr: number[] = [0, 1, 2, 3, 4] + @State enterEndDeleteAreaString: string = "not enterEndDeleteArea" + @State exitEndDeleteAreaString: string = "not exitEndDeleteArea" @Builder itemEnd() { - Row () { - Button("Del").margin("4vp") + Row() { + Button("Delete").margin("4vp") Button("Set").margin("4vp") }.padding("4vp").justifyContent(FlexAlign.SpaceEvenly) } build() { Column() { - List({space:10}) { - ListItem() { - Text(this.message) - .width('100%') - .height(100) - .fontSize(16) - .textAlign(TextAlign.Center) - .borderRadius(10) - .backgroundColor(0xFFFFFF) - } - .swipeAction({ end:this.itemEnd}) - - ListItem() { - Text(this.message) - .width('100%') - .height(100) - .fontSize(16) - .textAlign(TextAlign.Center) - .borderRadius(10) - .backgroundColor(0xFFFFFF) - } - .swipeAction({ start:this.itemEnd}) + List({ space: 10 }) { + ForEach(this.arr, (item) => { + ListItem() { + Text("item" + item) + .width('100%') + .height(100) + .fontSize(16) + .textAlign(TextAlign.Center) + .borderRadius(10) + .backgroundColor(0xFFFFFF) + } + .transition({ type: TransitionType.Delete, opacity: 0 }) + .swipeAction({ + end: { + builder: this.itemEnd.bind(this, item), + useDefaultDeleteAnimation: true, + onDelete: () => { + animateTo({ duration: 1000 }, () => { + let index = this.arr.indexOf(item) + this.arr.splice(index, 1) + }) + }, + deleteAreaDistance: 80, + onEnterDeleteArea: () => { + this.enterEndDeleteAreaString = "enterEndDeleteArea" + this.exitEndDeleteAreaString = "not exitEndDeleteArea" + }, + onExitDeleteArea: () => { + this.enterEndDeleteAreaString = "not enterEndDeleteArea" + this.exitEndDeleteAreaString = "exitEndDeleteArea" + } + } + }) + }, item => item) } + Text(this.enterEndDeleteAreaString).fontSize(20) + Text(this.exitEndDeleteAreaString).fontSize(20) } .padding(10) .backgroundColor(0xDCDCDC) @@ -132,4 +194,4 @@ struct ListItemExample2 { } } ``` -![en-us_image_1501929990650](figures/en-us_image_1501929990650.jpg) +![deleteListItem](figures/deleteListItem.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-container-listitemgroup.md b/en/application-dev/reference/arkui-ts/ts-container-listitemgroup.md index f0aab291ecf652bba774dcdaa7c567081dea69a6..48ed2249eb25c786c2bcd5f8cb900bd4e4b1589a 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-listitemgroup.md +++ b/en/application-dev/reference/arkui-ts/ts-container-listitemgroup.md @@ -19,15 +19,16 @@ This component supports the **[\](ts-container-listitem.md)** child co ## APIs -ListItemGroup(options?: {header?: CustomBuilder, footer?: CustomBuilder, space?: number | string}) +ListItemGroup(options?: {header?: CustomBuilder, footer?: CustomBuilder, space?: number | string, style?: ListItemGroupStyle}) **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| header | [CustomBuilder](ts-types.md#custombuilder8) | No| Header of the **\** component.| -| footer | [CustomBuilder](ts-types.md#custombuilder8) | No| Footer of the **\** component.| -| space | number \| string | No| Spacing between list items. This parameter is valid only between list items, but not between a header and list item or between a footer and list item.| +| Name | Type | Mandatory| Description | +| ------------------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | +| header | [CustomBuilder](ts-types.md#custombuilder8) | No | Header of the list item group. | +| footer | [CustomBuilder](ts-types.md#custombuilder8) | No | Footer of the list item group. | +| space | number \| string | No | Spacing between list items. This parameter is valid only between list items, but not between a header and list item or between a footer and list item.| +| style10+ | [ListItemGroupStyle](#listitemgroupstyle10) | No | Style of the list item group.
Default value: **ListItemGroupStyle.NONE**
If this parameter is set to **ListItemGroupStyle.NONE**, no style is applied.
If this parameter is set to **ListItemGroupStyle.CARD**, the default card style is applied, but only when **ListItemStyle.CARD** is set for [\](ts-container-listitem.md).
It can be in focus, hover, press, selected, or disable style depending on the state.
**NOTE**
In the default card style, the list has its **listDirection** attribute fixed at **Axis.Vertical** and **alignListItem** attribute at **ListItemAlign.Center**; the **header** and **footer** parameters cannot be set for the list item group. | ## Attributes @@ -35,6 +36,13 @@ ListItemGroup(options?: {header?: CustomBuilder, footer?: CustomBuilder, space?: | -------- | -------- | -------- | | divider | {
strokeWidth: [Length](ts-types.md#length),
color?: [ResourceColor](ts-types.md#resourcecolor),
startMargin?: [Length](ts-types.md#length),
endMargin?: [Length](ts-types.md#length)
} \| null | Style of the divider for the list items. By default, there is no divider.
- **strokeWidth**: stroke width of the divider.
- **color**: color of the divider.
- **startMargin**: distance between the divider and the start of the list.
- **endMargin**: distance between the divider and the end of the list.| +## ListItemGroupStyle10+ + +| Name| Description | +| ---- | ------------------ | +| NONE | No style. | +| CARD | Default card style.| + > **NOTE** > > The **\** component does not support the universal attribute **[aspectRatio](ts-universal-attributes-layout-constraints.md)**. @@ -99,12 +107,12 @@ struct ListItemGroupExample { } }, item => item) } - .borderRadius(20) .divider ({ strokeWidth: 1,color:Color.Blue }) // Divider between lines }) } .width('90%') .sticky(StickyStyle.Header|StickyStyle.Footer) + .scrollBar(BarState.Off) }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 }) } } diff --git a/en/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md b/en/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md index 52fbd9e3d32589538b10f699b209a7f00c9dc5fb..9b195d49a0ed0a36bdf1675820d7fb2b8cadcbd9 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md +++ b/en/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md @@ -34,6 +34,7 @@ SideBarContainer( type?: SideBarContainerType ) | -------- | -------- | | Embed | The sidebar is embedded in the component and displayed side by side with the content area.| | Overlay | The sidebar is displayed overlaid on the content area.| +| AUTO | The sidebar is displayed in Embed mode when the component size is greater than or equal to the sum of **minSideBarWidth** and **minContentWidth**
and in Overlay mode otherwise.| ## Attributes @@ -50,6 +51,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | autoHide9+ | boolean | Whether to automatically hide the sidebar when it is dragged to be smaller than the minimum width.
Default value: **true**
**NOTE**
The value is subject to the **minSideBarWidth** attribute method. If it is not set in **minSideBarWidth**, the default value is used.
Whether the sidebar should be hidden is determined when it is being dragged. When its width is less than the minimum width, the damping effect is required to trigger hiding (a distance out of range).| | sideBarPosition9+ | [SideBarPosition](#sidebarposition9) | Position of the sidebar.
Default value: **SideBarPosition.Start**| | divider10+ | [DividerStyle](#dividerstyle10) \| null | Divider style.
- **DividerStyle** (default): The divider is displayed.
- **null**: The divider is not displayed.| +| minContentWidth10+ | Dimension | Minimum width of the content area of the sidebar container.
Default value: **360**
Unit: vp| ## ButtonStyle diff --git a/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md b/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md index e72c5eb5c4eb4c0a9621d92feb10a5bd69082935..67d314759805d013bb678b47643e4646b62629b5 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md +++ b/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md @@ -27,8 +27,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | -| tabBar | string \| Resource \| {
icon?: string \| Resource,
text?: string \| Resource
}
\| [CustomBuilder](ts-types.md)8+ | Content displayed on the tab bar.
**CustomBuilder**: builder, to which components can be passed (applicable to API version 8 and later versions).
**NOTE**
If an icon uses an SVG image, the width and height attributes of the SVG image must be deleted. Otherwise, the icon size will be determined by the width and height attributes of the SVG image.
If the content set exceeds the space provided by the tab bar, it will be clipped.| -| tabBar9+ | [SubTabBarStyle](#subtabbarstyle) \| [BottomTabBarStyle](#bottomtabbarstyle) | Content displayed on the tab bar.
**SubTabBarStyle**: subtab style. It takes text as its input parameter.
**BottomTabBarStyle**: bottom and side tab style. It takes text and images as its input parameters.
**NOTE**
The bottom tab style does not include an underline.
When an icon display error occurs, a gray blank block is displayed.| +| tabBar | string \| [Resource](ts-types.md#resource) \| {
icon?: string \| [Resource](ts-types.md#resource),
text?: string \| [Resource](ts-types.md#resource)
}
\| [CustomBuilder](ts-types.md)8+ | Content displayed on the tab bar.
**CustomBuilder**: builder, to which components can be passed (applicable to API version 8 and later versions).
**NOTE**
If an icon uses an SVG image, the width and height attributes of the SVG image must be deleted. Otherwise, the icon size will be determined by the width and height attributes of the SVG image.
If the content set exceeds the space provided by the tab bar, it will be clipped.| +| tabBar9+ | [SubTabBarStyle](#subtabbarstyle9) \| [BottomTabBarStyle](#bottomtabbarstyle9) | Content displayed on the tab bar.
**SubTabBarStyle**: subtab style. It takes text as its input parameter.
**BottomTabBarStyle**: bottom and side tab style. It takes text and images as its input parameters.
**NOTE**
The bottom tab style does not include an underline.
When an icon display error occurs, a gray blank block is displayed.| > **NOTE** > @@ -81,10 +81,10 @@ The following attributes are supported. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------------------------------- | | color | [ResourceColor](ts-types.md#resourcecolor) | No| Underline indicator color and board color.
Default value: **#FF007DFF**| -| height | [Length](ts-types.md#length) | No| Height of the underline indicator.
Default value: **2.0**
Unit: vp| -| width | [Length](ts-types.md#length) | No| Width of the underline indicator.
Default value: **0.0**
Unit: vp| -| borderRadius | [Length](ts-types.md#length) | No| Radius of the rounded corner of the underline indicator.
Default value: **0.0**
Unit: vp| -| marginTop | [Length](ts-types.md#length) | No| Spacing between the underline indicator and text.
Default value: **8.0**
Unit: vp| +| height | [Length](ts-types.md#length) | No| Height of the underline indicator. It cannot be set in percentage.
Default value: **2.0**
Unit: vp| +| width | [Length](ts-types.md#length) | No| Width of the underline indicator. It cannot be set in percentage.
Default value: **0.0**
Unit: vp| +| borderRadius | [Length](ts-types.md#length) | No| Radius of the rounded corner of the underline indicator. It cannot be set in percentage.
Default value: **0.0**
Unit: vp| +| marginTop | [Length](ts-types.md#length) | No| Spacing between the underline indicator and text. It cannot be set in percentage.
Default value: **8.0**
Unit: vp| ## SelectedMode10+ | Name | Description | @@ -96,7 +96,7 @@ The following attributes are supported. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | ------------------------------------ | -| borderRadius | [Length](ts-types.md#length) | No| Radius of the rounded corner of the underline indicator.
Default value: **8.0**
Unit: vp| +| borderRadius | [Length](ts-types.md#length) | No| Radius of the rounded corner of the board. It cannot be set in percentage.
Default value: **8.0**
Unit: vp| ## LabelStyle10+ diff --git a/en/application-dev/reference/arkui-ts/ts-container-tabs.md b/en/application-dev/reference/arkui-ts/ts-container-tabs.md index 99f26a37c690f220d5d1a0bdbc0be42e7c789372..5f5423416d93440e5ed52c75b6b49b6bec25e1f9 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-tabs.md +++ b/en/application-dev/reference/arkui-ts/ts-container-tabs.md @@ -41,7 +41,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | vertical | boolean | Whether to use vertical tabs. The value **true** means to use vertical tabs, and **false** means to use horizontal tabs.
Default value: **false**| | scrollable | boolean | Whether the tabs are scrollable. The value **true** means that the tabs are scrollable, and **false** means the opposite.
Default value: **true**| | barMode | BarMode | Tab bar layout mode. For details, see **BarMode**.
Default value: **BarMode.Fixed**| -| barWidth | number \| Length8+ | Width of the tab bar.
The default value varies.
If the tab bar has the **vertical** attribute set to **false** and does not have a style specified, the default value is the width of the **\** component.
If the tab bar has the **vertical** attribute set to **true** and does not have a style specified, the default value is **56vp**.
If the tab bar has the **vertical** attribute set to **false** and **SubTabbarStyle** specified, the default value is the width of the **\** component.
If the tab bar has the **vertical** attribute set to **true** and **SubTabbarStyle** specified, the default value is **56vp**.
If the tab bar has the **vertical** attribute set to **true** and **BottomTabbarStyle** specified, the default value is **96vp**.
If the tab bar has the **vertical** attribute set to **false** and **BottomTabbarStyle** specified, the default value is the width of the **\** component.
**NOTE**

A value less than 0 or greater than the width of the **\** component evaluates to the default value.| +| barWidth | number \| Length8+ | Width of the tab bar.
The default value varies.
If the tab bar has the **vertical** attribute set to **false** and does not have a style specified, the default value is the width of the **\** component.
If the tab bar has the **vertical** attribute set to **true** and does not have a style specified, the default value is **56vp**.
If the tab bar has the **vertical** attribute set to **false** and **SubTabbarStyle** specified, the default value is the width of the **\** component.
If the tab bar has the **vertical** attribute set to **true** and **SubTabbarStyle** specified, the default value is **56vp**.
If the tab bar has the **vertical** attribute set to **true** and **BottomTabbarStyle** specified, the default value is **96vp**.
If the tab bar has the **vertical** attribute set to **false** and **BottomTabbarStyle** specified, the default value is the width of the **\** component.
**NOTE**
A value less than 0 or greater than the width of the **\** component evaluates to the default value.| | barHeight | number \| Length8+ | Height of the tab bar.
The default value varies.
If the tab bar has the **vertical** attribute set to **false** and does not have a style specified, the default value is **56vp**.
If the tab bar has the **vertical** attribute set to **true** and does not have a style specified, the default value is the height of the **\** component.
If the tab bar has the **vertical** attribute set to **false** and **SubTabbarStyle** specified, the default value is **56vp**.
If the tab bar has the **vertical** attribute set to **true** and **SubTabbarStyle** specified, the default value is the height of the **\** component.
If the tab bar has the **vertical** attribute set to **true** and **BottomTabbarStyle** specified, the default value is the height of the **\** component.
If the tab bar has the **vertical** attribute set to **false** and **BottomTabbarStyle** specified, the default value is **56vp**.
**NOTE**
A value less than 0 or greater than the height of the **\** component evaluates to the default value. | | animationDuration | number | Duration of the slide animation for tab switching. If this parameter is set, the tab switching animation is played when the user switches between tabs by sliding or clicking. If this parameter is not set, the tab switching animation is played only when the user switches between tabs by sliding.
Default value: **300**
**NOTE**
A value less than 0 or in percentage evaluates to the default value. | | divider10+ | [DividerStyle](#dividerstyle10) \| null | Whether the divider is displayed for the **\** and **\** components and the divider style. By default, the divider is not displayed.
**DividerStyle**: divider style.
**null**: The divider is not displayed.| @@ -53,10 +53,10 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name | Type | Mandatory | Description | | ----------- | ---------------------------------------- | ---- | ----------------------------------- | -| strokeWidth | [Length](ts-types.md#length) | Yes | Width of the divider. | +| strokeWidth | [Length](ts-types.md#length) | Yes | Width of the divider. It cannot be set in percentage. | | color | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the divider.
Default value: **#33182431** | -| startMargin | [Length](ts-types.md#length) | No | Distance between the divider and the top of the sidebar.
Default value: **0.0**
Unit: vp| -| endMargin | [Length](ts-types.md#length) | No | Distance between the divider and the bottom of the sidebar.
Default value: **0.0**
Unit: vp| +| startMargin | [Length](ts-types.md#length) | No | Distance between the divider and the top of the sidebar. It cannot be set in percentage.
Default value: **0.0**
Unit: vp| +| endMargin | [Length](ts-types.md#length) | No | Distance between the divider and the bottom of the sidebar. It cannot be set in percentage.
Default value: **0.0**
Unit: vp| ## BarMode diff --git a/en/application-dev/reference/arkui-ts/ts-custom-component-lifecycle.md b/en/application-dev/reference/arkui-ts/ts-custom-component-lifecycle.md index 148129e651983ba9ba54a017cd6d30d79272571d..4726d5481822059bfc36acfc0481fe27e7656a5e 100644 --- a/en/application-dev/reference/arkui-ts/ts-custom-component-lifecycle.md +++ b/en/application-dev/reference/arkui-ts/ts-custom-component-lifecycle.md @@ -1,12 +1,11 @@ # Custom Component Lifecycle - The lifecycle callbacks of a custom component are used to notify users of the lifecycle of the component. These callbacks are private and are invoked by the development framework at a specified time at runtime. They cannot be manually invoked from applications. - >**NOTE** > ->Promise and asynchronous callback functions can be used in lifecycle functions, for example, network resource getters and timer setters. +>- 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. +>- Promise and asynchronous callback functions can be used in lifecycle functions, for example, network resource getters and timer setters. ## aboutToAppear @@ -123,8 +122,8 @@ Since API version 10, this API is supported in ArkTS widgets. **Parameters** -| Name| Type | Description | -| ------ | -------------------------- | -------------------- | +| Name | Type | Description | +| ------ | -------------------------- | ---------- | | params | { [key: string]: unknown } | Parameters used for constructing the custom component.| diff --git a/en/application-dev/reference/arkui-ts/ts-methods-action-sheet.md b/en/application-dev/reference/arkui-ts/ts-methods-action-sheet.md index 7615fe3729496bd536aebc57a9efc622fa3957a5..05c6a8e612ead7cd031b37c1fe52c3ba302bd52d 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-action-sheet.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-action-sheet.md @@ -5,8 +5,10 @@ An action sheet is a dialog box that displays actions a user can take. > **NOTE** > > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. - - +> +> The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see [UIContext](../apis/js-apis-arkui-UIContext.md#uicontext). +> +> Since API version 10, you can use the [showActionSheet](../apis/js-apis-arkui-UIContext.md#showactionsheet) API in [UIContext](../apis/js-apis-arkui-UIContext.md#uicontext) to obtain the UI context. ## ActionSheet.show diff --git a/en/application-dev/reference/arkui-ts/ts-methods-alert-dialog-box.md b/en/application-dev/reference/arkui-ts/ts-methods-alert-dialog-box.md index db8ca389e215c3a8ffd750b672212f0db0453ff9..20b98309f386de5f891f49955adb97a9c879be79 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-alert-dialog-box.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-alert-dialog-box.md @@ -5,7 +5,10 @@ You can set the text content and response callback for an alert dialog box. > **NOTE** > > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. - +> +> The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see [UIContext](../apis/js-apis-arkui-UIContext.md#uicontext). +> +> Since API version 10, you can use the[showAlertDialog](../apis/js-apis-arkui-UIContext.md#showalertdialog) API in [UIContext](../apis/js-apis-arkui-UIContext.md#uicontext) to obtain the UI context. ## Attributes diff --git a/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md b/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md index c1ad40842425ca4cdf7c66635cee70623b1c4509..95a43d0529cce215537848c33198d99c8361594d 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md @@ -4,8 +4,11 @@ A date picker dialog box is a dialog box that allows users to select a date from > **NOTE** > -> The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. - +> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. +> +> The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see [UIContext](../apis/js-apis-arkui-UIContext.md#uicontext). +> +> Since API version 10, you can use the [showDatePickerDialog](../apis/js-apis-arkui-UIContext.md#showdatepickerdialog) API in [UIContext](../apis/js-apis-arkui-UIContext.md#uicontext) to obtain the UI context. ## DatePickerDialog.show @@ -15,20 +18,20 @@ Shows a date picker dialog box. **DatePickerDialogOptions** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| start | Date | No| Date('1970-1-1') | Start date of the picker.| -| end | Date | No| Date('2100-12-31') | End date of the picker.| -| selected | Date | No| Current system date| Selected date.| -| lunar | boolean | No| false | Whether to display the lunar calendar.| -| showTime10+ | boolean | No| false | Whether to display the time item.| -| useMilitaryTime10+ | boolean | No| false | Whether to display time in 24-hour format.| -| disappearTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| - | Font color, font size, and font width for the top and bottom items.| -| textStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| - | Font color, font size, and font width of all items except the top, bottom, and selected items.| -| selectedTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| - | Font color, font size, and font width of the selected item.| -| onAccept | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult)) => void | No| - | Callback invoked when the OK button in the dialog box is clicked.| -| onCancel | () => void | No| - | Callback invoked when the Cancel button in the dialog box is clicked.| -| onChange | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult)) => void | No| - | Callback invoked when the selected item in the picker changes.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| start | Date | No| Start date of the picker.
Default value: **Date('1970-1-1')**| +| end | Date | No| End date of the picker.
Default value: **Date('2100-12-31')**| +| selected | Date | No| Selected date.
Default value: current system date| +| lunar | boolean | No| Whether to display the lunar calendar.
Default value: **false**| +| showTime10+ | boolean | No| Whether to display the time item.
Default value: **false**| +| useMilitaryTime10+ | boolean | No| Whether to display time in 24-hour format.
Default value: **false**| +| disappearTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width for the top and bottom items.
Default value:
{
color: '#ff182431',
font: {
size: '14fp',
weight: FontWeight.Regular
}
} | +| textStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of all items except the top, bottom, and selected items.
Default value:
{
color: '#ff182431',
font: {
size: '16fp',
weight: FontWeight.Regular
}
} | +| selectedTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of the selected item.
Default value:
{
color: '#ff007dff',
font: {
size: '20vp',
weight: FontWeight.Medium
}
} | +| onAccept | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult)) => void | No| Callback invoked when the OK button in the dialog box is clicked.| +| onCancel | () => void | No| Callback invoked when the Cancel button in the dialog box is clicked.| +| onChange | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult)) => void | No| Callback invoked when the selected item in the picker changes.| ## Example @@ -86,3 +89,5 @@ struct DatePickerDialogExample { } } ``` + +![DataPickerDialog](figures/DataPickerDialog.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md b/en/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md index 4da30a11300a3c5e2ab2cf3f622384f207bbf415..c4eb8a23c9fa6473b7c20eb31277ccca64feb4d6 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md @@ -5,7 +5,10 @@ A text picker dialog box is a dialog box that allows users to select text from t > **NOTE** > > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. - +> +> The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see [UIContext](../apis/js-apis-arkui-UIContext.md#uicontext). +> +> Since API version 10, you can use the [showTextPickerDialog](../apis/js-apis-arkui-UIContext.md#showtextpickerdialog) API in [UIContext](../apis/js-apis-arkui-UIContext.md#uicontext) to obtain the UI context. ## TextPickerDialog.show @@ -17,13 +20,13 @@ Shows a text picker in the given settings. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| range | string[] \| [Resource](ts-types.md#resource)\|[TextPickerRangeContent](ts-basic-components-textpicker.md#textpickerrangecontent10)[]10+ | Yes| Data selection range of the picker. This parameter cannot be set to an empty array. If set to an empty array, it will not be displayed.| +| range | string[] \| [Resource](ts-types.md#resource)\|[TextPickerRangeContent](ts-basic-components-textpicker.md#textpickerrangecontent10)[]10+ | Yes| Data selection range of the picker. This parameter cannot be set to an empty array. If set to an empty array, it will not be displayed.
**NOTE**
The Resource type supports only [strarray.json](../../quick-start/resource-categories-and-access.md#resource-group-subdirectories).| | selected | number | No| Index of the selected item.
Default value: **0**| | value | string | No | Text of the selected item. This parameter does not take effect when the **selected** parameter is set. If the value is not within the range, the first item in the range is used instead.| | defaultPickerItemHeight | number \| string | No| Height of the picker item.| -| disappearTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width for the top and bottom items.| -| textStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of all items except the top, bottom, and selected items.| -| selectedTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of the selected item.| +| disappearTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width for the top and bottom items.
Default value:
{
color: '#ff182431',
font: {
size: '14fp',
weight: FontWeight.Regular
}
} | +| textStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of all items except the top, bottom, and selected items.
Default value:
{
color: '#ff182431',
font: {
size: '16fp',
weight: FontWeight.Regular
}
} | +| selectedTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of the selected item.
Default value:
{
color: '#ff007dff',
font: {
size: '20vp',
weight: FontWeight.Medium
}
} | | onAccept | (value: [TextPickerResult](#textpickerresult)) => void | No| Callback invoked when the OK button in the dialog box is clicked.| | onCancel | () => void | No| Callback invoked when the Cancel button in the dialog box is clicked.| | onChange | (value: [TextPickerResult](#textpickerresult)) => void | No| Callback invoked when the selected item changes.| @@ -32,8 +35,8 @@ Shows a text picker in the given settings. | Name| Type| Description| | -------- | -------- | -------- | -| value | string | Text of the selected item.
**NOTE**
For a text list or a list consisting of text and images, **value** indicates the text value of the selected item.
For an image list, **value** is empty.| -| index | number | Index of the selected item in the range.| +| value | string \| string []10+ | Text of the selected item.
**NOTE**
When the picker contains text only or both text and imagery, **value** indicates the text value of the selected item. (For a multi-column picker, **value** is of the array type.)
For an image list, **value** is empty.| +| index | number \| number []10+ | Index of the selected item in the range. (For a multi-column picker, **index** is of the array type.)| ## Example @@ -42,31 +45,35 @@ Shows a text picker in the given settings. @Entry @Component struct TextPickerDialogExample { - @State select: number = 2 + private select: number | number[] = 2 private fruits: string[] = ['apple1', 'orange2', 'peach3', 'grape4', 'banana5'] build() { - Column() { - Button("TextPickerDialog") - .margin(20) - .onClick(() => { - TextPickerDialog.show({ - range: this.fruits, - selected: this.select, - onAccept: (value: TextPickerResult) => { - // Set select to the index of the item selected when the OK button is touched. In this way, when the text picker dialog box is displayed again, the selected item is the one last confirmed. - this.select = value.index - console.info("TextPickerDialog:onAccept()" + JSON.stringify(value)) - }, - onCancel: () => { - console.info("TextPickerDialog:onCancel()") - }, - onChange: (value: TextPickerResult) => { - console.info("TextPickerDialog:onChange()" + JSON.stringify(value)) - } + Row() { + Column() { + Button("TextPickerDialog") + .margin(20) + .onClick(() => { + TextPickerDialog.show({ + range: this.fruits, + selected: this.select, + onAccept: (value: TextPickerResult) => { + // Set select to the index of the item selected when the OK button is touched. In this way, when the text picker dialog box is displayed again, the selected item is the one last confirmed. + this.select = value.index + console.info("TextPickerDialog:onAccept()" + JSON.stringify(value)) + }, + onCancel: () => { + console.info("TextPickerDialog:onCancel()") + }, + onChange: (value: TextPickerResult) => { + console.info("TextPickerDialog:onChange()" + JSON.stringify(value)) + } + }) }) - }) - }.width('100%') + }.width('100%') + }.height('100%') } } ``` + +![TextPickerDialog](figures/TextPickerDialog.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md b/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md index 246beaf9da869b68aa059efe66b7570f042ff205..bbb16d3d03209f0b955b5c47092e280ef45950db 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md @@ -5,6 +5,10 @@ A time picker dialog box is a dialog box that allows users to select a time from > **NOTE** > > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. +> +> The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see [UIContext](../apis/js-apis-arkui-UIContext.md#uicontext). +> +> Since API version 10, you can use the [showTimePickerDialog](../apis/js-apis-arkui-UIContext.md#showtimepickerdialog) API in [UIContext](../apis/js-apis-arkui-UIContext.md#uicontext) to obtain the UI context. ## TimePickerDialog.show @@ -19,9 +23,9 @@ Shows a time picker dialog box. | -------- | -------- | -------- | -------- | | selected | Date | No| Selected time.
Default value: current system time| | useMilitaryTime | boolean | No| Whether to display time in 24-hour format. The 12-hour format is used by default.
Default value: **false**| -| disappearTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width for the top and bottom items.| -| textStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of all items except the top, bottom, and selected items.| -| selectedTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of the selected item.| +| disappearTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width for the top and bottom items.
Default value:
{
color: '#ff182431',
font: {
size: '14fp',
weight: FontWeight.Regular
}
} | +| textStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of all items except the top, bottom, and selected items.
Default value:
{
color: '#ff182431',
font: {
size: '16fp',
weight: FontWeight.Regular
}
} | +| selectedTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of the selected item.
Default value:
{
color: '#ff007dff',
font: {
size: '20vp',
weight: FontWeight.Medium
}
} | | onAccept | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| Callback invoked when the OK button in the dialog box is clicked.| | onCancel | () => void | No| Callback invoked when the Cancel button in the dialog box is clicked.| | onChange | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| Callback invoked when the selected time changes.| @@ -43,7 +47,7 @@ struct TimePickerDialogExample { TimePickerDialog.show({ selected: this.selectTime, onAccept: (value: TimePickerResult) => { - //Set selectTime to the time when the OK button is clicked. In this way, when the dialog box is displayed again, the selected time is the time when the operation was confirmed last time. + // Set selectTime to the time when the OK button is clicked. In this way, when the dialog box is displayed again, the selected time is the time when the operation was confirmed last time. this.selectTime.setHours(value.hour, value.minute) console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)) }, @@ -77,3 +81,5 @@ struct TimePickerDialogExample { } } ``` + +![TimetPickerDialog](figures/TimePickerDialog.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-pixel-units.md b/en/application-dev/reference/arkui-ts/ts-pixel-units.md index 8a820840da5c7a8d5ad232f16f548acd585ed262..26ae5a8713858fed4427021145353a500a35b8a7 100644 --- a/en/application-dev/reference/arkui-ts/ts-pixel-units.md +++ b/en/application-dev/reference/arkui-ts/ts-pixel-units.md @@ -1,13 +1,17 @@ # Pixel Units -The framework provides four pixel units, with vp as the reference data unit. +ArkUI provides four pixel units, with vp as the reference data unit. +>**Notes:** +> +>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. -| Name| Description | -| ---- | ------------------------------------------------------------ | -| px | Physical pixel unit of the screen. | + +| Name | Description | +| ---- | ---------------------------------------- | +| px | Physical pixel unit of the screen. | | vp | Pixel unit specific to the screen density. Pixels in this unit are converted into physical pixels of the screen based on the screen pixel density. This unit is used for values whose unit is not specified. On a screen with an actual width of 1440 physical pixels, 1 vp is approximately equal to 3 px.| -| fp | Font pixel, which is similar to vp and varies according to the system font size.| +| fp | Font pixel, which is similar to vp and varies according to the system font size. | | lpx | Logical pixel unit of the window. It is the ratio of the actual screen width to the logical width (configured by **designWidth**). For example, if **designWidth** is set to **720** (default value), then 1 lpx is equal to 2 px for a screen with an actual width of 1440 physical pixels.| @@ -15,12 +19,12 @@ The framework provides four pixel units, with vp as the reference data unit. Conversion between px and other pixel units is supported. -| API | Description | -| --------------------------------------------------- | ------------------------------------------------------------ | -| vp2px(value : number) : number | Converts a value in units of vp to a value in units of px.
Since API version 9, this API is supported in ArkTS widgets.| -| px2vp(value : number) : number | Converts a value in units of px to a value in units of vp.
Since API version 9, this API is supported in ArkTS widgets.| -| fp2px(value : number) : number | Converts a value in units of fp to a value in units of px.
Since API version 9, this API is supported in ArkTS widgets.| -| px2fp(value : number) : number | Converts a value in units of px to a value in units of fp.
Since API version 9, this API is supported in ArkTS widgets.| +| API | Description | +| ---------------------------------------- | ---------------------------------------- | +| vp2px(value : number) : number | Converts a value in units of vp to a value in units of px.
Since API version 9, this API is supported in ArkTS widgets.| +| px2vp(value : number) : number | Converts a value in units of px to a value in units of vp.
Since API version 9, this API is supported in ArkTS widgets.| +| fp2px(value : number) : number | Converts a value in units of fp to a value in units of px.
Since API version 9, this API is supported in ArkTS widgets.| +| px2fp(value : number) : number | Converts a value in units of px to a value in units of fp.
Since API version 9, this API is supported in ArkTS widgets.| | lpx2px(value : number) : number | Converts a value in units of lpx to a value in units of px.
Since API version 9, this API is supported in ArkTS widgets.| | px2lpx(value : number) : number | Converts a value in units of px to a value in units of lpx.
Since API version 9, this API is supported in ArkTS widgets.| diff --git a/en/application-dev/reference/arkui-ts/ts-types.md b/en/application-dev/reference/arkui-ts/ts-types.md index dd3ce725c77effe392403ed8b2102e9f8608e19b..df71967ffb8f97b52183d429b82ae3d7c38b8c0e 100644 --- a/en/application-dev/reference/arkui-ts/ts-types.md +++ b/en/application-dev/reference/arkui-ts/ts-types.md @@ -156,10 +156,10 @@ The **Font** type is used to set the text style. | Name | Type | Mandatory | Description | | ------ | ---------------------------------------- | ---- | ---------------------------------------- | -| size | [Length](#length) | No | Font size. If the value is of the number type, the unit fp is used. The value cannot be a percentage.| -| weight | [FontWeight](ts-appendix-enums.md#fontweight) \| number \| string | No | Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight.| +| size | [Length](#length) | No | Font size. If the value is of the number type, the unit fp is used. The value cannot be a percentage.
Default value: **16.0** | +| weight | [FontWeight](ts-appendix-enums.md#fontweight) \| number \| string | No | Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. A larger value indicates a thicker font.
Default value: **400** \| **FontWeight.Normal** | | family | string \| [Resource](#resource) | No | Font family of the text. Use commas (,) to separate multiple fonts. The priority of the fonts is the sequence in which they are placed. An example value is **'Arial, HarmonyOS Sans'**. Currently, only the **'HarmonyOS Sans'** font is supported.| -| style | [FontStyle](ts-appendix-enums.md#fontstyle) | No | Font style. | +| style | [FontStyle](ts-appendix-enums.md#fontstyle) | No | Font style.
Default value: **FontStyle.Normal** | ## Area8+ diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-background.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-background.md index 8d3208442cc40edfd53d623a125c03d979b0af80..dc70be06327ffc45da2153ff8e7b0a3445bae16f 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-background.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-background.md @@ -14,7 +14,7 @@ You can set the background for a component. | backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),
repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | **src**: image address, which can be the address of an Internet or a local image or a Base64 encoded image. SVG images are not supported.
**repeat**: whether the background image is repeated. By default, the background image is not repeated. If the set image has a transparent background and **backgroundColor** is set, the image is overlaid on the background color.
Since API version 9, this API is supported in ArkTS widgets.| | backgroundImageSize | {
width?: [Length](ts-types.md#length),
height?: [Length](ts-types.md#length)
} \| [ImageSize](ts-appendix-enums.md#imagesize) | Width and height of the background image. If the input is a **{width: Length, height: Length}** object and only one attribute is set, the other attribute is the set value multiplied by the original aspect ratio of the image. By default, the original image aspect ratio remains unchanged.
The value range of **width** and **height** is [0, +∞).
Default value: **ImageSize.Auto**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
A value less than 0 evaluates to the value **0**. If **height** is set but **width** is not, the image width is adjusted based on the original aspect ratio of the image.| | backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | Position of the background image in the component, that is, the coordinates relative to the upper left corner of the component.
Default value:
{
x: 0,
y: 0
}
When **x** and **y** are set in percentage, the offset is calculated based on the width and height of the component.
Since API version 9, this API is supported in ArkTS widgets.| -| backgroundBlurStyle9+ | value:[BlurStyle](ts-appendix-enums.md#blurstyle9),
options10+?:[BackgroundBlurStyleOptions](#backgroundblurstyleoptions10) | Background blur style applied between the content and the background.
**value**: settings of the background blur style, including the blur radius, mask color, mask opacity, and saturation.
**options**: background blur options. Optional.
This API is supported in ArkTS widgets.| +| backgroundBlurStyle9+ | value:[BlurStyle](ts-appendix-enums.md#blurstyle9),
options10+?:[BackgroundBlurStyleOptions](#backgroundblurstyleoptions10) | Background blur style applied between the content and the background.
**value**: settings of the background blur style, including the blur radius, mask color, mask opacity, saturation, and brightness.
**options**: background blur options. Optional.
This API is supported in ArkTS widgets.| ## BackgroundBlurStyleOptions10+ @@ -22,6 +22,7 @@ You can set the background for a component. | --------------------------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | | colorMode10+ | [ThemeColorMode](ts-appendix-enums.md#themecolormode10) | No | Color mode used for the background blur.
Default value: **ThemeColorMode.System**| | adaptiveColor10+ | [AdaptiveColor](ts-appendix-enums.md#adaptivecolor10) | No | Adaptive color mode.
Default value: **AdaptiveColor.Default**| +| scale10+ | number | No | Blurredness of the background material. This API is a system API.
Default value: **1.0**
Value range: [0.0, 1.0]
| ## Example @@ -109,7 +110,7 @@ struct BackgroundBlurStyleDemo { } .width('50%') .height('50%') - .backgroundBlurStyle(BlurStyle.Thin, { colorMode: ThemeColorMode.LIGHT, adaptiveColor: AdaptiveColor.DEFAULT }) + .backgroundBlurStyle(BlurStyle.Thin, { colorMode: ThemeColorMode.LIGHT, adaptiveColor: AdaptiveColor.DEFAULT, scale: 1.0 }) .position({ x: '15%', y: '30%' }) } .height('100%') diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-click-effect.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-click-effect.md index ffcc737568abcbe244bef30a33e78248161bc8a4..cf4f1c12a7848c5a1b96211404bb8a4978a25f51 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-click-effect.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-click-effect.md @@ -9,16 +9,16 @@ You can set the click effect for a component to define how it behaves when click ### Attributes -| Name | Type | Description | -| ----------- | ------------------- | ------------------------------------------------------------ | -| clickEffect | [ClickEffect](#clickeffect) \| null | Click effect of the component.
**NOTE**
The click effect is revoked when this attribute is set to **null**.| +| Name | Type | Description | +| ----------- | ------------------------------------------- | ------------------------------------------------------------ | +| clickEffect | [ClickEffect](#clickeffect) \| null | Click effect of the component.
**NOTE**
You can remove the click effect by setting this attribute to **undefined** or **null**.
Avoid using this attribute in scenarios where the component size dynamically changes.
This attribute is not supported when the component cannot trigger a universal event.| ### ClickEffect | Name | Type | Mandatory| Description | | ----- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| level | [ClickEffectLevel](ts-appendix-enums.md#clickeffectlevel10) | Yes | Click effect of the component.
Default value: **ClickEffectLevel.LIGHT**| -| scale | number | No | Zoom ratio. This parameter works based on the setting of **ClickEffectLevel**.
**NOTE**
The default value of this parameter varies by the value of **level**.
- If **level** is set to **ClickEffectLevel.LIGHT**, the default value is **0.90**.
- If **level** is set to **ClickEffectLevel.MIDDLE** or **ClickEffectLevel.HEAVY**, the default value is **0.95**. | +| level | [ClickEffectLevel](ts-appendix-enums.md#clickeffectlevel10) | Yes | Click effect of the component.
**NOTE**
If **level** is set to **undefined** or **null**, the click effect corresponding to **ClickEffectLevel.LIGHT** will be used. For details about the zoom ratio, see the description of **scale**.| +| scale | number | No | Zoom ratio. This parameter works based on the setting of **ClickEffectLevel**.
**NOTE**
The default value of this parameter varies by the value of **level**.
- If **level** is set to **ClickEffectLevel.LIGHT**, the default value is **0.90**.
- If **level** is set to **ClickEffectLevel.MIDDLE** or **ClickEffectLevel.HEAVY**, the default value is **0.95**.
- If **level** is set to **undefined** or **null** (both of which evaluate to **ClickEffectLevel.LIGHT**), the default value is **0.90**.
If **scale** is set to **undefined** or **null**, the default zoom ratio for the set level will be used. | ### Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md index 5c282923bc24c0d62718d986f16a7ed09b0d7642..62ff2bf39459d2e6ff58418fc7d0ab1cea3c46ff 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md @@ -22,10 +22,10 @@ Image effects include blur, shadow, spherical effect, and much more. | invert | number | 0 | Inversion ratio of the component. If the value is **1**, the component is completely inverted. If the value is **0**, the component remains unchanged. The unit is percentage.
Value range: [0, 1]
**NOTE**
A value less than 0 evaluates to the value **0**.
Since API version 9, this API is supported in ArkTS widgets.| | sepia | number | 0 | Sepia conversion ratio of the component. If the value is **1**, the image is completely sepia. If the value is **0**, the component remains unchanged. The unit is percentage.
Since API version 9, this API is supported in ArkTS widgets.| | hueRotate | number \| string | '0deg' | Hue rotation angle of the component.
Value range: (-∞, +∞)
**NOTE**
A rotation of 360 degrees leaves the color unchanged. A rotation of 180 degrees and then -180 degrees also leaves the color unchanged. When the data type is number, the value 90 is equivalent to **'90deg'**.
Since API version 9, this API is supported in ArkTS widgets.| -| colorBlend 8+ | [Color](ts-appendix-enums.md#color) \| string \| [Resource](ts-types.md#resource) | - | Color to blend with the component.
Since API version 9, this API is supported in ArkTS widgets.| -| sphericalEffect10+ | [number] | - | Spherical degree of the component.
The value ranges from 0 to 1.
**NOTE**
1. If the value is **0**, the component remains unchanged. If the value is **1**, the component is completely spherical. Between 0 and 1, a greater value indicates a higher spherical degree.
A value less than 0 evaluates to the value **0**. A value greater than 1 evaluates to the value **1**.
2. If a component image is loaded asynchronously, the spherical effect is not supported. For example, the **\** component uses asynchronous loading by default, which means that **syncLoad** must be set to **true** to apply the spherical effect. However, this setting is not recommended. Asynchronous loading is also used for **backgroundImage**. Therefore, if **backgroundImage** is set, the spherical effect is not supported.
3. If the shadow effect is set for a component, the spherical effect is not supported.| -| lightUpEffect10+ | [number] | - | Light up degree of the component.
The value ranges from 0 to 1.
If the value is **0**, the component is dark. If the value is **1**, the component is fully illuminated. Between 0 and 1, a greater value indicates higher luminance. A value less than 0 evaluates to the value **0**. A value greater than 1 evaluates to the value **1**.| -| pixelStretchEffect10+ | [PixelStretchEffectOptions](ts-types.md#pixelstretcheffectoptions10) | - | Pixel stretch effect options.
The **options** parameter includes the length by which a pixel is stretched toward the four edges.
**NOTE**
1. If the length is a positive value, the original image is stretched, and the image size increases. The edge pixels grow by the set length toward the top, bottom, left, and right edges.
2. 2. If the length is a negative value, the original image shrinks as follows, but the image size remains unchanged:
(1) The image shrinks from the four edges by the absolute value of length set through **options**.
(2) The image is stretched back to the original size with edge pixels.
3. Constraints on **options**:
(1) The length values for the four edges must be all positive or all negative. That is, the four edges are stretched or shrink at the same time in the same direction.
(2) The length values must all be a percentage or a specific value. Combined use of the percentage and specific value is not allowed.
(3) If the input value is invalid, the image is displayed as {0, 0, 0, 0}, that is, the image is the same as the original image. | +| colorBlend8+ | [Color](ts-appendix-enums.md#color) \| string \| [Resource](ts-types.md#resource) | - | Color to blend with the component.
Since API version 9, this API is supported in ArkTS widgets.| +| sphericalEffect10+ | [number] | - | Spherical degree of the component.
The value ranges from 0 to 1.
**NOTE**
1. If the value is **0**, the component remains unchanged. If the value is **1**, the component is completely spherical. Between 0 and 1, a greater value indicates a higher spherical degree.
A value less than 0 evaluates to the value **0**. A value greater than 1 evaluates to the value **1**.
2. If a component image is loaded asynchronously, the spherical effect is not supported. For example, the **\** component uses asynchronous loading by default, which means that **syncLoad** must be set to **true** to apply the spherical effect. However, this setting is not recommended. Asynchronous loading is also used for **backgroundImage**. Therefore, if **backgroundImage** is set, the spherical effect is not supported.
3. If the shadow effect is set for a component, the spherical effect is not supported.
This is a system API.| +| lightUpEffect10+ | [number] | - | Light up degree of the component.
The value ranges from 0 to 1.
If the value is **0**, the component is dark. If the value is **1**, the component is fully illuminated. Between 0 and 1, a greater value indicates higher luminance. A value less than 0 evaluates to the value **0**. A value greater than 1 evaluates to the value **1**.
This is a system API.| +| pixelStretchEffect10+ | [PixelStretchEffectOptions](ts-types.md#pixelstretcheffectoptions10) | - | Pixel stretch effect options.
The **options** parameter includes the length by which a pixel is stretched toward the four edges.
**NOTE**
1. If the length is a positive value, the original image is stretched, and the image size increases. The edge pixels grow by the set length toward the top, bottom, left, and right edges.
2. 2. If the length is a negative value, the original image shrinks as follows, but the image size remains unchanged:
(1) The image shrinks from the four edges by the absolute value of length set through **options**.
(2) The image is stretched back to the original size with edge pixels.
3. Constraints on **options**:
(1) The length values for the four edges must be all positive or all negative. That is, the four edges are stretched or shrink at the same time in the same direction.
(2) The length values must all be a percentage or a specific value. Combined use of the percentage and specific value is not allowed.
(3) If the input value is invalid, the image is displayed as {0, 0, 0, 0}, that is, the image is the same as the original image.
This is a system API.| ## ShadowOptions @@ -320,7 +320,6 @@ Below is how the component looks: Compared with the original image, the effect drawing is implemented in two steps: -1. The image size is reduced. The resultant size is the original image size minus -the lengths by which the pixels shrink. For example, if the original image size is 100 x 100 and **pixelStretchEffect({top:-10,left:-10,** +1. The image size is reduced. The resultant size is the original image size minus the lengths by which the pixels shrink. For example, if the original image size is 100 x 100 and **pixelStretchEffect({top:-10,left:-10,** **right:-10,bottom:-10})** is set, the resultant size is (100-10-10) x (100-10-10), that is, 8080. 2. Edge pixels are stretched to restore the image to its original size. \ No newline at end of file diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md index 37581d1f6c53d2b01266ee7930ea34bfeebbc5a4..a7b7b9f2d66ad0e6ede1a742cb262de2c27d6307 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md @@ -12,7 +12,7 @@ You can bind a popup to a component, specifying its content, interaction logic, | Name | Type | Description | | --------- | ---------------------------------------- | ---------------------------------------- | -| bindPopup | show: boolean,
popup: [PopupOptions](#popupoptions) \| [CustomPopupOptions](#custompopupoptions8)8+ | Binds a popup to the component.
**show**: whether to show the popup. The default value is **false**, indicating that the popup is hidden.
**popup**: parameters of the popup.| +| bindPopup | show: boolean,
popup: [PopupOptions](#popupoptions) \| [CustomPopupOptions](#custompopupoptions8)8+ | Binds a popup to the component.
**show**: whether to show the popup. The default value is **false**, indicating that the popup is hidden. As the popup can be displayed only after building of all pages is completed, **show** cannot be set to **true** during page building. Otherwise, the display position and shape of the popup will be incorrect.
**popup**: parameters of the popup.| ## PopupOptions diff --git a/en/application-dev/reference/arkui-ts/ts-universal-component-area-change-event.md b/en/application-dev/reference/arkui-ts/ts-universal-component-area-change-event.md index 2e0e8610515d57f66aa28d424140c657da95f368..61312be7ecde554a1a50681c007f70421e257cf9 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-component-area-change-event.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-component-area-change-event.md @@ -11,7 +11,7 @@ The area change event is triggered when the component's size, position, or any o | Name | Bubbling Supported| Description | | ---------------------------------------- | ---- | ---------------------------------------- | -| onAreaChange(event: (oldValue: [Area](ts-types.md#area8), newValue: [Area](ts-types.md#area8)) => void) | No | Triggered when the component area changes.| +| onAreaChange(event: (oldValue: [Area](ts-types.md#area8), newValue: [Area](ts-types.md#area8)) => void) | No | Triggered when the component area changes in size or position due to layout updates. This event is not triggered for render attribute changes caused by re-rendering, such as changes of **translate** and **offset**.| ## Example diff --git a/en/application-dev/reference/errorcodes/Readme-EN.md b/en/application-dev/reference/errorcodes/Readme-EN.md index 3c7ea85b1474912717e3dde2df486159aad388b2..baffeb2d779edbb96e55d77add3164bbbd2be604 100644 --- a/en/application-dev/reference/errorcodes/Readme-EN.md +++ b/en/application-dev/reference/errorcodes/Readme-EN.md @@ -61,7 +61,7 @@ - [Wi-Fi Error Codes](errorcode-wifi.md) - [NFC Error Codes](errorcode-nfc.md) - [RPC Error Codes](errorcode-rpc.md) - - Basic Features +- Basic Features - [Accessibility Error Codes](errorcode-accessibility.md) - [FaultLogger Error Codes](errorcode-faultlogger.md) - [Application Event Logging Error Codes](errorcode-hiappevent.md) @@ -92,7 +92,7 @@ - [Update Error Codes](errorcode-update.md) - Customization - [Enterprise Device Management Error Codes](errorcode-enterpriseDeviceManager.md) -- Language Base Class Library - - [Utils Error Codes](errorcode-utils.md) +- Common Library Library + - [Common Library Error Codes](errorcode-utils.md) - Test - [UiTest Error Codes](errorcode-uitest.md) diff --git a/en/application-dev/reference/errorcodes/errorcode-bundle.md b/en/application-dev/reference/errorcodes/errorcode-bundle.md index 8f7f78de3cd348f9cd0df3c393c4303bb18666bb..e247f85658e0fa7bd297c2eed514ae386b71157d 100644 --- a/en/application-dev/reference/errorcodes/errorcode-bundle.md +++ b/en/application-dev/reference/errorcodes/errorcode-bundle.md @@ -719,9 +719,8 @@ Failed to install the HAP because the isolationMode configured is not supported. During application installation, the value of **isolationMode** in the HAP conflicts with the isolation mode of the device. **Possible Causes** - -1. The device supports the isolation mode (the value of **supportIsolationMode** is **true**), whereas the value of **isolationMode** in the HAP is **nonisolationOnly**. -2. The device does not support the isolation mode (the value of **supportIsolationMode** is **false**), whereas the value of **isolationMode** in the HAP is **isolationOnly**. +1. The device supports the isolation mode (the value of **persist.bms.supportIsolationMode** is **true**), whereas the value of **isolationMode** in the HAP is **nonisolationOnly**. +2. The device does not support the isolation mode (the value of **persist.bms.supportIsolationMode** is **false**), whereas the value of **isolationMode** in the HAP is **isolationOnly**. **Solution** @@ -764,3 +763,24 @@ The version of the application to be updated is not later than the current versi 1. Set the version number of the application to be later than the current version number. 2. If you want to update the application without changing the version number, set **installFlag** to **REPLACE_EXISTING**. + +## 17700048 Code Signature Verification Failure +**Error Message** + +Failed to install the HAP because the code signature verification is failed. + +**Description** + +During application installation, the code signature file of the installation package fails to be verified. + +**Possible Causes** + +1. The module corresponding to the code signature file does not exist in the installation package. +2. The path of the code signature file is invalid. +3. The code signature file does not match the installation package. + +**Solution** + +1. Ensure that the module corresponding to the code signature file is contained in the installation package. +2. Provide a valid path of the code signature file. +3. Use the code signature file that matches the installation package. diff --git a/en/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-css.md b/en/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-css.md index 79aa6fa9c7dbb7ea0373a545633307df3df62f41..3d3332c012725d3b6c275ad20d905ae1483e48e4 100644 --- a/en/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-css.md +++ b/en/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-css.md @@ -23,7 +23,7 @@ CSS files can be imported using the **\@import** statement. This facilitates mod The **.css** file with the same name as the **.hml** file in each page directory describes the styles of components on the HML page, determining how the components will be displayed. 1. Internal style: The **style** and **class** attributes can be used to specify the component style. Example: - + ```html
@@ -31,7 +31,7 @@ The **.css** file with the same name as the **.hml** file in each page directory
``` - + ```css /* index.css */ .container { @@ -40,7 +40,7 @@ The **.css** file with the same name as the **.hml** file in each page directory ``` 2. External style files: You need to import the files. For example, create a **style.css** file in the **common** directory and import the file at the beginning of **index.css**. - + ```css /* style.css */ .title { @@ -48,7 +48,7 @@ The **.css** file with the same name as the **.hml** file in each page directory } ``` - + ```css /* index.css */ @import '../../common/style.css'; @@ -62,10 +62,10 @@ The **.css** file with the same name as the **.hml** file in each page directory A CSS selector is used to select elements for which styles need to be added to. The following table lists the supported selectors. -| Selector| Example| Description| -| -------- | -------- | -------- | +| Selector | Example | Description | +| ------ | ---------- | ------------------------- | | .class | .container | Selects all components whose **class** is **container**.| -| \#id | \#titleId | Selects all components whose **id** is **titleId**.| +| \#id | \#titleId | Selects all components whose **id** is **titleId**. | Example: diff --git a/en/application-dev/reference/native-apis/Readme-EN.md b/en/application-dev/reference/native-apis/Readme-EN.md index ee896c67409995bce0420d9b762ba232d270de01..7b6840f6392866ec1183a618034f80d7670ea89e 100644 --- a/en/application-dev/reference/native-apis/Readme-EN.md +++ b/en/application-dev/reference/native-apis/Readme-EN.md @@ -7,6 +7,7 @@ - [Drawing](_drawing.md) - [Image](image.md) - [Rawfile](rawfile.md) + - [RDB](_r_d_b.md) - [MindSpore](_mind_spore.md) - [NeuralNeworkRuntime](_neural_nework_runtime.md) - [AudioDecoder](_audio_decoder.md) @@ -58,6 +59,12 @@ - [native_huks_api.h](native__huks__api_8h.md) - [native_huks_param.h](native__huks__param_8h.md) - [native_huks_type.h](native__huks__type_8h.md) + - [oh_cursor.h](oh__cursor_8h.md) + - [oh_predicates.h](oh__predicates_8h.md) + - [oh_value_object.h](oh__value__object_8h.md) + - [oh_values_bucket.h](oh__values__bucket_8h.md) + - [relational_store_error_code.h](relational__store__error__code_8h.md) + - [relational_store.h](relational__store_8h.md) - [syscap_ndk.h](syscap__ndk_8h.md) - [purgeable_memory.h](purgeable__memory_8h.md) - Structs @@ -95,3 +102,9 @@ - [OH_Huks_ParamSet](_o_h___huks___param_set.md) - [OH_Huks_PubKeyInfo](_o_h___huks___pub_key_info.md) - [OH_Huks_Result](_o_h___huks___result.md) + - [OH_Cursor](_o_h___cursor.md) + - [OH_Predicates](_o_h___predicates.md) + - [OH_Rdb_Config](_o_h___rdb___config.md) + - [OH_Rdb_Store](_o_h___rdb___store.md) + - [OH_VBucket](_o_h___v_bucket.md) + - [OH_VObject](_o_h___v_object.md) diff --git a/en/application-dev/reference/native-apis/_mind_spore.md b/en/application-dev/reference/native-apis/_mind_spore.md index ded41297291a904a08793bd2cd94e2ab667a10a0..e52fc4f327ea142c3f8a0c5777c5b8ce8de67ec0 100644 --- a/en/application-dev/reference/native-apis/_mind_spore.md +++ b/en/application-dev/reference/native-apis/_mind_spore.md @@ -7,125 +7,146 @@ Provides APIs related to MindSpore Lite model inference. \@Syscap SystemCapability.Ai.MindSpore -**Since:** +**Since** + 9 + ## Summary -### Files +### File -| Name | Description | -| -------- | -------- | -| [context.h](context_8h.md) | Provides **Context** APIs for configuring runtime information.
File to Include: | -| [data_type.h](data__type_8h.md) | Declares tensor data types.
File to Include: | -| [format.h](format_8h.md) | Declares tensor data formats.
File to Include: | -| [model.h](model_8h.md) | Provides model-related APIs for model creation and inference.
File to Include: | -| [status.h](status_8h.md) | Provides the status codes of MindSpore Lite.
File to Include: | -| [tensor.h](tensor_8h.md) | Provides APIs for creating and modifying tensor information.
File to Include: | -| [types.h](types_8h.md) | Provides the model file types and device types supported by MindSpore Lite.
File to Include: | +| Name | Description | +| ------------------------------- | ------------------------------------------------------------ | +| [context.h](context_8h.md) | Provides **Context** APIs for configuring runtime information.
File to include: \| +| [data_type.h](data__type_8h.md) | Declares tensor data types.
File to include: \| +| [format.h](format_8h.md) | Declares tensor data formats.
File to include: \ | +| [model.h](model_8h.md) | Provides model-related APIs for model creation and inference.
File to include: \| +| [status.h](status_8h.md) | Provides the status codes of MindSpore Lite.
File to include: \| +| [tensor.h](tensor_8h.md) | Provides APIs for creating and modifying tensor information.
File to include: \| +| [types.h](types_8h.md) | Provides the model file types and device types supported by MindSpore Lite.
File to include: \| ### Structs -| Name | Description | -| -------- | -------- | -| [OH_AI_TensorHandleArray](_o_h___a_i___tensor_handle_array.md) | Defines the tensor array structure, which is used to store the tensor array pointer and tensor array length. | -| [OH_AI_ShapeInfo](_o_h___a_i___shape_info.md) | Defines dimension information. The maximum dimension is set by **MS_MAX_SHAPE_NUM**. | -| [OH_AI_CallBackParam](_o_h___a_i___call_back_param.md) | Defines the operator information passed in a callback. | +| Name | Description | +| ------------------------------------------------------------ | ---------------------------------------------------- | +| [OH_AI_TensorHandleArray](_o_h___a_i___tensor_handle_array.md) | Defines the tensor array structure, which is used to store the tensor array pointer and tensor array length.| +| [OH_AI_ShapeInfo](_o_h___a_i___shape_info.md) | Dimension information. The maximum dimension is set by **MS_MAX_SHAPE_NUM**. | +| [OH_AI_CallBackParam](_o_h___a_i___call_back_param.md) | Defines the operator information passed in a callback. | -### Macros - -| Name | Description | -| -------- | -------- | -| [OH_AI_MAX_SHAPE_NUM](#oh_ai_max_shape_num) 32 | Defines dimension information. The maximum dimension is set by **MS_MAX_SHAPE_NUM**. | +### Macro Definition +| Name | Description | +| ------------------------------------------------ | -------------------------------------------- | +| [OH_AI_MAX_SHAPE_NUM](#oh_ai_max_shape_num) 32 | Defines dimension information. The maximum dimension is set by **MS_MAX_SHAPE_NUM**.| ### Types -| Name | Description | -| -------- | -------- | -| [OH_AI_ContextHandle](#oh_ai_contexthandle) | Defines the pointer to the MindSpore context. | -| [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) | Defines the pointer to the MindSpore device information. | -| [OH_AI_DataType](#oh_ai_datatype) | Declares data types supported by MSTensor. | -| [OH_AI_Format](#oh_ai_format) | Declares data formats supported by MSTensor. | -| [OH_AI_ModelHandle](#oh_ai_modelhandle) | Defines the pointer to a model object. | -| [OH_AI_TensorHandleArray](#oh_ai_tensorhandlearray) | Defines the tensor array structure, which is used to store the tensor array pointer and tensor array length. | -| **OH_AI_ShapeInfo** | Defines dimension information. The maximum dimension is set by **MS_MAX_SHAPE_NUM**. | -| [OH_AI_CallBackParam](#oh_ai_callbackparam) | Defines the operator information passed in a callback. | -| [OH_AI_KernelCallBack](#oh_ai_kernelcallback)) (const [OH_AI_TensorHandleArray](_o_h___a_i___tensor_handle_array.md) inputs, const [OH_AI_TensorHandleArray](_o_h___a_i___tensor_handle_array.md) outputs, const [OH_AI_CallBackParam](_o_h___a_i___call_back_param.md) kernel_Info) | Defines the pointer to a callback. | -| [OH_AI_Status](#oh_ai_status) | Defines MindSpore status codes. | -| [OH_AI_TensorHandle](#oh_ai_tensorhandle) | Defines the handle of a tensor object. | -| [OH_AI_ModelType](#oh_ai_modeltype) | Defines model file types. | -| [OH_AI_DeviceType](#oh_ai_devicetype) | Defines the supported device types. | +| Name | Description | +| ------------------------------------------------------------ | -------------------------------------------------- | +| [OH_AI_ContextHandle](#oh_ai_contexthandle) | Defines the pointer to the MindSpore context. | +| [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) | Defines the pointer to the MindSpore device information. | +| [OH_AI_DataType](#oh_ai_datatype) | Declares data types supported by MSTensor. | +| [OH_AI_Format](#oh_ai_format) | Declares data formats supported by MSTensor. | +| [OH_AI_ModelHandle](#oh_ai_modelhandle) | Defines the pointer to a model object. | +| [OH_AI_TensorHandleArray](#oh_ai_tensorhandlearray) | Defines the tensor array structure, which is used to store the tensor array pointer and tensor array length.| +| [OH_AI_ShapeInfo](_o_h___a_i___shape_info.md) | Defines dimension information. The maximum dimension is set by **MS_MAX_SHAPE_NUM**. | +| [OH_AI_CallBackParam](#oh_ai_callbackparam) | Defines the operator information passed in a callback. | +| [OH_AI_KernelCallBack](#oh_ai_kernelcallback) | Defines the pointer to a callback. | +| [OH_AI_Status](#oh_ai_status) | Defines MindSpore status codes. | +| [OH_AI_TensorHandle](#oh_ai_tensorhandle) | Defines the handle of a tensor object. | +| [OH_AI_ModelType](#oh_ai_modeltype) | Defines model file types. | +| [OH_AI_DeviceType](#oh_ai_devicetype) | Defines the supported device types. | +| [OH_AI_NNRTDeviceType](#oh_ai_nnrtdevicetype) | Defines NNRt device types. | +| [OH_AI_PerformanceMode](#oh_ai_performancemode) | Defines performance modes of the NNRt device. | +| [OH_AI_Priority](#oh_ai_priority) | Defines NNRt inference task priorities. | +| [NNRTDeviceDesc](#nnrtdevicedesc) | Defines the NNRt device information, including the device ID and device name. | ### Enums -| Name | Description | -| -------- | -------- | -| [OH_AI_DataType](#oh_ai_datatype) {
OH_AI_DATATYPE_UNKNOWN = 0, OH_AI_DATATYPE_OBJECTTYPE_STRING = 12, OH_AI_DATATYPE_OBJECTTYPE_LIST = 13, OH_AI_DATATYPE_OBJECTTYPE_TUPLE = 14,
OH_AI_DATATYPE_OBJECTTYPE_TENSOR = 17, OH_AI_DATATYPE_NUMBERTYPE_BEGIN = 29, OH_AI_DATATYPE_NUMBERTYPE_BOOL = 30, OH_AI_DATATYPE_NUMBERTYPE_INT8 = 32,
OH_AI_DATATYPE_NUMBERTYPE_INT16 = 33, OH_AI_DATATYPE_NUMBERTYPE_INT32 = 34, OH_AI_DATATYPE_NUMBERTYPE_INT64 = 35, OH_AI_DATATYPE_NUMBERTYPE_UINT8 = 37,
OH_AI_DATATYPE_NUMBERTYPE_UINT16 = 38, OH_AI_DATATYPE_NUMBERTYPE_UINT32 = 39, OH_AI_DATATYPE_NUMBERTYPE_UINT64 = 40, OH_AI_DATATYPE_NUMBERTYPE_FLOAT16 = 42,
OH_AI_DATATYPE_NUMBERTYPE_FLOAT32 = 43, OH_AI_DATATYPE_NUMBERTYPE_FLOAT64 = 44, OH_AI_DATATYPE_NUMBERTYPE_END = 46, OH_AI_DataTypeInvalid = INT32_MAX
} | Declares data types supported by MSTensor. | -| [OH_AI_Format](#oh_ai_format) {
OH_AI_FORMAT_NCHW = 0, OH_AI_FORMAT_NHWC = 1, OH_AI_FORMAT_NHWC4 = 2, OH_AI_FORMAT_HWKC = 3,
OH_AI_FORMAT_HWCK = 4, OH_AI_FORMAT_KCHW = 5, OH_AI_FORMAT_CKHW = 6, OH_AI_FORMAT_KHWC = 7,
OH_AI_FORMAT_CHWK = 8, OH_AI_FORMAT_HW = 9, OH_AI_FORMAT_HW4 = 10, OH_AI_FORMAT_NC = 11,
OH_AI_FORMAT_NC4 = 12, OH_AI_FORMAT_NC4HW4 = 13, OH_AI_FORMAT_NCDHW = 15, OH_AI_FORMAT_NWC = 16,
OH_AI_FORMAT_NCW = 17
} | Declares data formats supported by MSTensor. | -| [OH_AI_CompCode](#oh_ai_compcode) { OH_AI_COMPCODE_CORE = 0x00000000u, OH_AI_COMPCODE_LITE = 0xF0000000u } | Defines MinSpore component codes. | -| [OH_AI_Status](#oh_ai_status) {
OH_AI_STATUS_SUCCESS = 0, OH_AI_STATUS_CORE_FAILED = OH_AI_COMPCODE_CORE \| 0x1, OH_AI_STATUS_LITE_ERROR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -1), OH_AI_STATUS_LITE_NULLPTR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -2),
OH_AI_STATUS_LITE_PARAM_INVALID = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -3), OH_AI_STATUS_LITE_NO_CHANGE = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -4), OH_AI_STATUS_LITE_SUCCESS_EXIT = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -5), OH_AI_STATUS_LITE_MEMORY_FAILED = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -6),
OH_AI_STATUS_LITE_NOT_SUPPORT = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -7), OH_AI_STATUS_LITE_THREADPOOL_ERROR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -8), OH_AI_STATUS_LITE_UNINITIALIZED_OBJ = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -9), OH_AI_STATUS_LITE_OUT_OF_TENSOR_RANGE = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -100),
OH_AI_STATUS_LITE_INPUT_TENSOR_ERROR, OH_AI_STATUS_LITE_REENTRANT_ERROR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -102), OH_AI_STATUS_LITE_GRAPH_FILE_ERROR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -200), OH_AI_STATUS_LITE_NOT_FIND_OP = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -300),
OH_AI_STATUS_LITE_INVALID_OP_NAME = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -301), OH_AI_STATUS_LITE_INVALID_OP_ATTR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -302), OH_AI_STATUS_LITE_OP_EXECUTE_FAILURE, OH_AI_STATUS_LITE_FORMAT_ERROR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -400),
OH_AI_STATUS_LITE_INFER_ERROR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -500), OH_AI_STATUS_LITE_INFER_INVALID, OH_AI_STATUS_LITE_INPUT_PARAM_INVALID
} | Defines MindSpore status codes. | -| [OH_AI_ModelType](#oh_ai_modeltype) { OH_AI_MODELTYPE_MINDIR = 0, OH_AI_MODELTYPE_INVALID = 0xFFFFFFFF } | Defines model file types. | -| [OH_AI_DeviceType](#oh_ai_devicetype) {
OH_AI_DEVICETYPE_CPU = 0, OH_AI_DEVICETYPE_GPU, OH_AI_DEVICETYPE_KIRIN_NPU, OH_AI_DEVICETYPE_NNRT = 60,
OH_AI_DEVICETYPE_INVALID = 100
} | Defines the supported device types. | +| Name | Description | +| ------------------------------------------------------------ | ---------------------------------------- | +| [OH_AI_DataType](#oh_ai_datatype-1) {
OH_AI_DATATYPE_UNKNOWN = 0,
OH_AI_DATATYPE_OBJECTTYPE_STRING = 12,
OH_AI_DATATYPE_OBJECTTYPE_LIST = 13,
OH_AI_DATATYPE_OBJECTTYPE_TUPLE = 14,
OH_AI_DATATYPE_OBJECTTYPE_TENSOR = 17,
OH_AI_DATATYPE_NUMBERTYPE_BEGIN = 29,
OH_AI_DATATYPE_NUMBERTYPE_BOOL = 30,
OH_AI_DATATYPE_NUMBERTYPE_INT8 = 32,
OH_AI_DATATYPE_NUMBERTYPE_INT16 = 33,
OH_AI_DATATYPE_NUMBERTYPE_INT32 = 34,
OH_AI_DATATYPE_NUMBERTYPE_INT64 = 35,
OH_AI_DATATYPE_NUMBERTYPE_UINT8 = 37,
OH_AI_DATATYPE_NUMBERTYPE_UINT16 = 38,
OH_AI_DATATYPE_NUMBERTYPE_UINT32 = 39,
OH_AI_DATATYPE_NUMBERTYPE_UINT64 = 40,
OH_AI_DATATYPE_NUMBERTYPE_FLOAT16 = 42,
OH_AI_DATATYPE_NUMBERTYPE_FLOAT32 = 43,
OH_AI_DATATYPE_NUMBERTYPE_FLOAT64 = 44,
OH_AI_DATATYPE_NUMBERTYPE_END = 46,
OH_AI_DataTypeInvalid = INT32_MAX
} | Declares data types supported by MSTensor. | +| [OH_AI_Format](#oh_ai_format-1) {
OH_AI_FORMAT_NCHW = 0,
OH_AI_FORMAT_NHWC = 1,
OH_AI_FORMAT_NHWC4 = 2,
OH_AI_FORMAT_HWKC = 3,
OH_AI_FORMAT_HWCK = 4,
OH_AI_FORMAT_KCHW = 5,
OH_AI_FORMAT_CKHW = 6,
OH_AI_FORMAT_KHWC = 7,
OH_AI_FORMAT_CHWK = 8,
OH_AI_FORMAT_HW = 9,
OH_AI_FORMAT_HW4 = 10,
OH_AI_FORMAT_NC = 11,
OH_AI_FORMAT_NC4 = 12,
OH_AI_FORMAT_NC4HW4 = 13,
OH_AI_FORMAT_NCDHW = 15,
OH_AI_FORMAT_NWC = 16,
OH_AI_FORMAT_NCW = 17
} | Declares data formats supported by MSTensor. | +| [OH_AI_CompCode](#oh_ai_compcode) {
OH_AI_COMPCODE_CORE = 0x00000000u,
OH_AI_COMPCODE_LITE = 0xF0000000u
} | Defines MindSpore component codes. | +| [OH_AI_Status](#oh_ai_status-1) {
OH_AI_STATUS_SUCCESS = 0, OH_AI_STATUS_CORE_FAILED = OH_AI_COMPCODE_CORE \| 0x1, OH_AI_STATUS_LITE_ERROR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -1), OH_AI_STATUS_LITE_NULLPTR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -2),
OH_AI_STATUS_LITE_PARAM_INVALID = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -3), OH_AI_STATUS_LITE_NO_CHANGE = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -4), OH_AI_STATUS_LITE_SUCCESS_EXIT = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -5), OH_AI_STATUS_LITE_MEMORY_FAILED = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -6),
OH_AI_STATUS_LITE_NOT_SUPPORT = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -7), OH_AI_STATUS_LITE_THREADPOOL_ERROR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -8), OH_AI_STATUS_LITE_UNINITIALIZED_OBJ = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -9), OH_AI_STATUS_LITE_OUT_OF_TENSOR_RANGE = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -100),
OH_AI_STATUS_LITE_INPUT_TENSOR_ERROR, OH_AI_STATUS_LITE_REENTRANT_ERROR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -102), OH_AI_STATUS_LITE_GRAPH_FILE_ERROR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -200), OH_AI_STATUS_LITE_NOT_FIND_OP = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -300),
OH_AI_STATUS_LITE_INVALID_OP_NAME = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -301), OH_AI_STATUS_LITE_INVALID_OP_ATTR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -302), OH_AI_STATUS_LITE_OP_EXECUTE_FAILURE, OH_AI_STATUS_LITE_FORMAT_ERROR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -400),
OH_AI_STATUS_LITE_INFER_ERROR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF & -500), OH_AI_STATUS_LITE_INFER_INVALID, OH_AI_STATUS_LITE_INPUT_PARAM_INVALID
} | Defines MindSpore status codes. | +| [OH_AI_ModelType](#oh_ai_modeltype-1) {
OH_AI_MODELTYPE_MINDIR = 0,
OH_AI_MODELTYPE_INVALID = 0xFFFFFFFF
} | Defines model file types. | +| [OH_AI_DeviceType](#oh_ai_devicetype-1) {
OH_AI_DEVICETYPE_CPU = 0,
OH_AI_DEVICETYPE_GPU,
OH_AI_DEVICETYPE_KIRIN_NPU,
OH_AI_DEVICETYPE_NNRT = 60,
OH_AI_DEVICETYPE_INVALID = 100
} | Defines the supported device types.| +| [OH_AI_NNRTDeviceType](#oh_ai_nnrtdevicetype-1) {
OH_AI_NNRTDEVICE_OTHERS = 0,
OH_AI_NNRTDEVICE_CPU = 1,
OH_AI_NNRTDEVICE_GPU = 2,
OH_AI_NNRTDEVICE_ACCELERATOR = 3
} | Defines NNRt device types. | +| [OH_AI_PerformanceMode](#oh_ai_performancemode-1) {
OH_AI_PERFORMANCE_NONE = 0,
OH_AI_PERFORMANCE_LOW = 1,
OH_AI_PERFORMANCE_MEDIUM = 2,
OH_AI_PERFORMANCE_HIGH = 3,
OH_AI_PERFORMANCE_EXTREME = 4
} | Defines performance modes of the NNRt device. | +| [OH_AI_Priority](#oh_ai_priority-1) {
OH_AI_PRIORITY_NONE = 0,
OH_AI_PRIORITY_LOW = 1,
OH_AI_PRIORITY_MEDIUM = 2,
OH_AI_PRIORITY_HIGH = 3
} | Defines NNRt inference task priorities. | ### Functions -| Name | Description | -| -------- | -------- | -| [OH_AI_ContextCreate](#oh_ai_contextcreate) () | Creates a context object. | -| [OH_AI_ContextDestroy](#oh_ai_contextdestroy) ([OH_AI_ContextHandle](#oh_ai_contexthandle) \*context) | Destroys a context object. | -| [OH_AI_ContextSetThreadNum](#oh_ai_contextsetthreadnum) ([OH_AI_ContextHandle](#oh_ai_contexthandle) context, int32_t thread_num) | Sets the number of runtime threads. | -| [OH_AI_ContextGetThreadNum](#oh_ai_contextgetthreadnum) (const [OH_AI_ContextHandle](#oh_ai_contexthandle) context) | Obtains the number of threads. | -| [OH_AI_ContextSetThreadAffinityMode](#oh_ai_contextsetthreadaffinitymode) ([OH_AI_ContextHandle](#oh_ai_contexthandle) context, int mode) | Sets the affinity mode for binding runtime threads to CPU cores, which are categorized into little cores and big cores depending on the CPU frequency. | -| [OH_AI_ContextGetThreadAffinityMode](#oh_ai_contextgetthreadaffinitymode) (const [OH_AI_ContextHandle](#oh_ai_contexthandle) context) | Obtains the affinity mode for binding runtime threads to CPU cores. | -| [OH_AI_ContextSetThreadAffinityCoreList](#oh_ai_contextsetthreadaffinitycorelist) ([OH_AI_ContextHandle](#oh_ai_contexthandle) context, const int32_t \*core_list, size_t core_num) | Sets the list of CPU cores bound to a runtime thread. | -| [OH_AI_ContextGetThreadAffinityCoreList](#oh_ai_contextgetthreadaffinitycorelist) (const [OH_AI_ContextHandle](#oh_ai_contexthandle) context, size_t \*core_num) | Obtains the list of bound CPU cores. | -| [OH_AI_ContextSetEnableParallel](#oh_ai_contextsetenableparallel) ([OH_AI_ContextHandle](#oh_ai_contexthandle) context, bool is_parallel) | Sets whether to enable parallelism between operators. | -| [OH_AI_ContextGetEnableParallel](#oh_ai_contextgetenableparallel) (const [OH_AI_ContextHandle](#oh_ai_contexthandle) context) | Checks whether parallelism between operators is supported. | -| [OH_AI_ContextAddDeviceInfo](#oh_ai_contextadddeviceinfo) ([OH_AI_ContextHandle](#oh_ai_contexthandle) context, [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info) | Adds information about a running device. | -| [OH_AI_DeviceInfoCreate](#oh_ai_deviceinfocreate) ([OH_AI_DeviceType](#oh_ai_devicetype) device_type) | Creates a device information object. | -| [OH_AI_DeviceInfoDestroy](#oh_ai_deviceinfodestroy) ([OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) \*device_info) | Destroys a device information instance. | -| [OH_AI_DeviceInfoSetProvider](#oh_ai_deviceinfosetprovider) ([OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info, const char \*provider) | Sets the name of a provider. | -| [OH_AI_DeviceInfoGetProvider](#oh_ai_deviceinfogetprovider) (const [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info) | Obtains the provider name. | -| [OH_AI_DeviceInfoSetProviderDevice](#oh_ai_deviceinfosetproviderdevice) ([OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info, const char \*device) | Sets the name of a provider device. | -| [OH_AI_DeviceInfoGetProviderDevice](#oh_ai_deviceinfogetproviderdevice) (const [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info) | Obtains the name of a provider device. | -| [OH_AI_DeviceInfoGetDeviceType](#oh_ai_deviceinfogetdevicetype) (const [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info) | Obtains the type of a provider device. | -| [OH_AI_DeviceInfoSetEnableFP16](#oh_ai_deviceinfosetenablefp16) ([OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info, bool is_fp16) | Sets whether to enable float16 inference. This function is available only for CPU/GPU devices. | -| [OH_AI_DeviceInfoGetEnableFP16](#oh_ai_deviceinfogetenablefp16) (const [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info) | Checks whether float16 inference is enabled. This function is available only for CPU/GPU devices. | -| [OH_AI_DeviceInfoSetFrequency](#oh_ai_deviceinfosetfrequency) ([OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info, int frequency) | Sets the NPU frequency type. This function is available only for NPU devices. | -| [OH_AI_DeviceInfoGetFrequency](#oh_ai_deviceinfogetfrequency) (const [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info) | Obtains the NPU frequency type. This function is available only for NPU devices. | -| [OH_AI_ModelCreate](#oh_ai_modelcreate) () | Creates a model object. | -| [OH_AI_ModelDestroy](#oh_ai_modeldestroy) ([OH_AI_ModelHandle](#oh_ai_modelhandle) \*model) | Destroys a model object. | -| [OH_AI_ModelBuild](#oh_ai_modelbuild) ([OH_AI_ModelHandle](#oh_ai_modelhandle) model, const void \*model_data, size_t data_size, [OH_AI_ModelType](#oh_ai_modeltype) model_type, const [OH_AI_ContextHandle](#oh_ai_contexthandle) model_context) | Loads and builds a MindSpore model from the memory buffer. | -| [OH_AI_ModelBuildFromFile](#oh_ai_modelbuildfromfile) ([OH_AI_ModelHandle](#oh_ai_modelhandle) model, const char \*model_path, [OH_AI_ModelType](#oh_ai_modeltype) model_type, const [OH_AI_ContextHandle](#oh_ai_contexthandle) model_context) | Loads and builds a MindSpore model from a model file. | -| [OH_AI_ModelResize](#oh_ai_modelresize) ([OH_AI_ModelHandle](#oh_ai_modelhandle) model, const [OH_AI_TensorHandleArray](_o_h___a_i___tensor_handle_array.md) inputs, [OH_AI_ShapeInfo](_o_h___a_i___shape_info.md) \*shape_infos, size_t shape_info_num) | Adjusts the input tensor shapes of a built model. | -| [OH_AI_ModelPredict](#oh_ai_modelpredict) ([OH_AI_ModelHandle](#oh_ai_modelhandle) model, const [OH_AI_TensorHandleArray](_o_h___a_i___tensor_handle_array.md) inputs, [OH_AI_TensorHandleArray](_o_h___a_i___tensor_handle_array.md) \*outputs, const [OH_AI_KernelCallBack](#oh_ai_kernelcallback) before, const [OH_AI_KernelCallBack](#oh_ai_kernelcallback) after) | Performs model inference. | -| [OH_AI_ModelGetInputs](#oh_ai_modelgetinputs) (const [OH_AI_ModelHandle](#oh_ai_modelhandle) model) | Obtains the input tensor array structure of a model. | -| [OH_AI_ModelGetOutputs](#oh_ai_modelgetoutputs) (const [OH_AI_ModelHandle](#oh_ai_modelhandle) model) | Obtains the output tensor array structure of a model. | -| [OH_AI_ModelGetInputByTensorName](#oh_ai_modelgetinputbytensorname) (const [OH_AI_ModelHandle](#oh_ai_modelhandle) model, const char \*tensor_name) | Obtains the input tensor of a model by tensor name. | -| [OH_AI_ModelGetOutputByTensorName](#oh_ai_modelgetoutputbytensorname) (const [OH_AI_ModelHandle](#oh_ai_modelhandle) model, const char \*tensor_name) | Obtains the output tensor of a model by tensor name. | -| [OH_AI_TensorCreate](#oh_ai_tensorcreate) (const char \*name, [OH_AI_DataType](#oh_ai_datatype) type, const int64_t \*shape, size_t shape_num, const void \*data, size_t data_len) | Creates a tensor object. | -| [OH_AI_TensorDestroy](#oh_ai_tensordestroy) ([OH_AI_TensorHandle](#oh_ai_tensorhandle) \*tensor) | Destroys a tensor object. | -| [OH_AI_TensorClone](#oh_ai_tensorclone) ([OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor) | Clones a tensor. | -| [OH_AI_TensorSetName](#oh_ai_tensorsetname) ([OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor, const char \*name) | Sets the name of a tensor. | -| [OH_AI_TensorGetName](#oh_ai_tensorgetname) (const [OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor) | Obtains the name of a tensor. | -| [OH_AI_TensorSetDataType](#oh_ai_tensorsetdatatype) ([OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor, [OH_AI_DataType](#oh_ai_datatype) type) | Sets the data type of a tensor. | -| [OH_AI_TensorGetDataType](#oh_ai_tensorgetdatatype) (const [OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor) | Obtains the data type of a tensor. | -| [OH_AI_TensorSetShape](#oh_ai_tensorsetshape) ([OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor, const int64_t \*shape, size_t shape_num) | Sets the shape of a tensor. | -| [OH_AI_TensorGetShape](#oh_ai_tensorgetshape) (const [OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor, size_t \*shape_num) | Obtains the shape of a tensor. | -| [OH_AI_TensorSetFormat](#oh_ai_tensorsetformat) ([OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor, [OH_AI_Format](#oh_ai_format) format) | Sets the tensor data format. | -| [OH_AI_TensorGetFormat](#oh_ai_tensorgetformat) (const [OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor) | Obtains the tensor data format. | -| [OH_AI_TensorSetData](#oh_ai_tensorsetdata) ([OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor, void \*data) | Sets the tensor data. | -| [OH_AI_TensorGetData](#oh_ai_tensorgetdata) (const [OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor) | Obtains the pointer to tensor data. | -| [OH_AI_TensorGetMutableData](#oh_ai_tensorgetmutabledata) (const [OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor) | Obtains the pointer to variable tensor data. If the data is empty, memory will be allocated. | -| [OH_AI_TensorGetElementNum](#oh_ai_tensorgetelementnum) (const [OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor) | Obtains the number of tensor elements. | -| [OH_AI_TensorGetDataSize](#oh_ai_tensorgetdatasize) (const [OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor) | Obtains the number of bytes of the tensor data. | +| Name | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| [OH_AI_ContextCreate](#oh_ai_contextcreate) () | Creates a context object. | +| [OH_AI_ContextDestroy](#oh_ai_contextdestroy) ([OH_AI_ContextHandle](#oh_ai_contexthandle) \*context) | Destroys a context object. | +| [OH_AI_ContextSetThreadNum](#oh_ai_contextsetthreadnum) ([OH_AI_ContextHandle](#oh_ai_contexthandle) context, int32_t thread_num) | Sets the number of runtime threads. | +| [OH_AI_ContextGetThreadNum](#oh_ai_contextgetthreadnum) (const [OH_AI_ContextHandle](#oh_ai_contexthandle) context) | Obtains the number of threads. | +| [OH_AI_ContextSetThreadAffinityMode](#oh_ai_contextsetthreadaffinitymode) ([OH_AI_ContextHandle](#oh_ai_contexthandle) context, int mode) | Sets the affinity mode for binding runtime threads to CPU cores, which are classified into large, medium, and small cores based on the CPU frequency. You only need to bind the large or medium cores, but not small cores.| +| [OH_AI_ContextGetThreadAffinityMode](#oh_ai_contextgetthreadaffinitymode) (const [OH_AI_ContextHandle](#oh_ai_contexthandle) context) | Obtains the affinity mode for binding runtime threads to CPU cores. | +| [OH_AI_ContextSetThreadAffinityCoreList](#oh_ai_contextsetthreadaffinitycorelist) ([OH_AI_ContextHandle](#oh_ai_contexthandle) context, const int32_t \*core_list, size_t core_num) | Sets the list of CPU cores bound to a runtime thread. | +| [OH_AI_ContextGetThreadAffinityCoreList](#oh_ai_contextgetthreadaffinitycorelist) (const [OH_AI_ContextHandle](#oh_ai_contexthandle) context, size_t \*core_num) | Obtains the list of bound CPU cores. | +| [OH_AI_ContextSetEnableParallel](#oh_ai_contextsetenableparallel) ([OH_AI_ContextHandle](#oh_ai_contexthandle) context, bool is_parallel) | Sets whether to enable parallelism between operators. The setting is ineffective because the feature of this API is not yet available. | +| [OH_AI_ContextGetEnableParallel](#oh_ai_contextgetenableparallel) (const [OH_AI_ContextHandle](#oh_ai_contexthandle) context) | Checks whether parallelism between operators is supported. | +| [OH_AI_ContextAddDeviceInfo](#oh_ai_contextadddeviceinfo) ([OH_AI_ContextHandle](#oh_ai_contexthandle) context, [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info) | Attaches the custom device information to the inference context. | +| [OH_AI_DeviceInfoCreate](#oh_ai_deviceinfocreate) ([OH_AI_DeviceType](#oh_ai_devicetype) device_type) | Creates a device information object. | +| [OH_AI_DeviceInfoDestroy](#oh_ai_deviceinfodestroy) ([OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) \*device_info) | Destroys a device information object. Note: After the device information instance is added to the context, the caller does not need to destroy it manually. | +| [OH_AI_DeviceInfoSetProvider](#oh_ai_deviceinfosetprovider) ([OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info, const char \*provider) | Sets the provider name. | +| [OH_AI_DeviceInfoGetProvider](#oh_ai_deviceinfogetprovider) (const [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info) | Obtains the provider name. | +| [OH_AI_DeviceInfoSetProviderDevice](#oh_ai_deviceinfosetproviderdevice) ([OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info, const char \*device) | Sets the name of a provider device. | +| [OH_AI_DeviceInfoGetProviderDevice](#oh_ai_deviceinfogetproviderdevice) (const [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info) | Obtains the name of a provider device. | +| [OH_AI_DeviceInfoGetDeviceType](#oh_ai_deviceinfogetdevicetype) (const [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info) | Obtains the device type. | +| [OH_AI_DeviceInfoSetEnableFP16](#oh_ai_deviceinfosetenablefp16) ([OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info, bool is_fp16) | Sets whether to enable float16 inference. This function is available only for CPU and GPU devices. | +| [OH_AI_DeviceInfoGetEnableFP16](#oh_ai_deviceinfogetenablefp16) (const [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info) | Checks whether float16 inference is enabled. This function is available only for CPU and GPU devices. | +| [OH_AI_DeviceInfoSetFrequency](#oh_ai_deviceinfosetfrequency) ([OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info, int frequency) | Sets the NPU frequency type. This function is available only for NPU devices. | +| [OH_AI_DeviceInfoGetFrequency](#oh_ai_deviceinfogetfrequency) (const [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info) | Obtains the NPU frequency type. This function is available only for NPU devices. | +| [OH_AI_GetAllNNRTDeviceDescs](#oh_ai_getallnnrtdevicedescs) (size_t \*num) | Obtains the descriptions of all NNRt devices in the system. | +| [OH_AI_DestroyAllNNRTDeviceDescs](#oh_ai_destroyallnnrtdevicedescs) ([NNRTDeviceDesc](#nnrtdevicedesc) \*\*desc) | Destroys the array of NNRT descriptions obtained by [OH_AI_GetAllNNRTDeviceDescs](#oh_ai_getallnnrtdevicedescs).| +| [OH_AI_GetDeviceIdFromNNRTDeviceDesc](#oh_ai_getdeviceidfromnnrtdevicedesc) (const [NNRTDeviceDesc](#nnrtdevicedesc) \*desc) | Obtains the NNRt device ID from the specified NNRt device description. Note that this ID is valid only for NNRt devices.| +| [OH_AI_GetNameFromNNRTDeviceDesc](#oh_ai_getnamefromnnrtdevicedesc) (const [NNRTDeviceDesc](#nnrtdevicedesc) \*desc) | Obtains the NNRt device name from the specified NNRt device description. | +| [OH_AI_GetTypeFromNNRTDeviceDesc](#oh_ai_gettypefromnnrtdevicedesc) (const [NNRTDeviceDesc](#nnrtdevicedesc) \*desc) | Obtains the NNRt device type from the specified NNRt device description. | +| [OH_AI_CreateNNRTDeviceInfoByName](#oh_ai_creatennrtdeviceinfobyname) (const char \*name) | Searches for the NNRt device with the specified name and creates the NNRt device information based on the information about the first found NNRt device.| +| [OH_AI_CreateNNRTDeviceInfoByType](#oh_ai_creatennrtdeviceinfobytype) ([OH_AI_NNRTDeviceType](#oh_ai_nnrtdevicetype) type) | Searches for the NNRt device with the specified type and creates the NNRt device information based on the information about the first found NNRt device.| +| [OH_AI_DeviceInfoSetDeviceId](#oh_ai_deviceinfosetdeviceid) ([OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info, size_t device_id) | Sets the ID of an NNRt device. This API is available only for NNRt devices. | +| [OH_AI_DeviceInfoGetDeviceId](#oh_ai_deviceinfogetdeviceid) (const [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info) | Obtains the ID of an NNRt device. This API is available only for NNRt devices. | +| [OH_AI_DeviceInfoSetPerformanceMode](#oh_ai_deviceinfosetperformancemode) ([OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info, [OH_AI_PerformanceMode](#oh_ai_performancemode) mode) | Sets the performance mode of an NNRt device. This API is available only for NNRt devices. | +| [OH_AI_DeviceInfoGetPerformanceMode](#oh_ai_deviceinfogetperformancemode) (const [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info) | Obtains the performance mode of an NNRt device. This API is available only for NNRt devices. | +| [OH_AI_DeviceInfoSetPriority](#oh_ai_deviceinfosetpriority) ([OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info, [OH_AI_Priority](#oh_ai_priority) priority) | Sets the priority of an NNRT task. This API is available only for NNRt devices. | +| [OH_AI_DeviceInfoGetPriority](#oh_ai_deviceinfogetpriority) (const [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info) | Obtains the priority of an NNRT task. This API is available only for NNRt devices. | +| [OH_AI_ModelCreate](#oh_ai_modelcreate) () | Creates a model object. | +| [OH_AI_ModelDestroy](#oh_ai_modeldestroy) ([OH_AI_ModelHandle](#oh_ai_modelhandle) \*model) | Destroys a model object. | +| [OH_AI_ModelBuild](#oh_ai_modelbuild) ([OH_AI_ModelHandle](#oh_ai_modelhandle) model, const void \*model_data, size_t data_size, [OH_AI_ModelType](#oh_ai_modeltype) model_type, const [OH_AI_ContextHandle](#oh_ai_contexthandle) model_context) | Loads and builds a MindSpore model from the memory buffer. | +| [OH_AI_ModelBuildFromFile](#oh_ai_modelbuildfromfile) ([OH_AI_ModelHandle](#oh_ai_modelhandle) model, const char \*model_path, [OH_AI_ModelType](#oh_ai_modeltype) model_type, const [OH_AI_ContextHandle](#oh_ai_contexthandle) model_context) | Loads and builds a MindSpore model from a model file. | +| [OH_AI_ModelResize](#oh_ai_modelresize) ([OH_AI_ModelHandle](#oh_ai_modelhandle) model, const [OH_AI_TensorHandleArray](_o_h___a_i___tensor_handle_array.md) inputs, [OH_AI_ShapeInfo](_o_h___a_i___shape_info.md) \*shape_infos, size_t shape_info_num) | Adjusts the input tensor shapes of a built model. | +| [OH_AI_ModelPredict](#oh_ai_modelpredict) ([OH_AI_ModelHandle](#oh_ai_modelhandle) model, const [OH_AI_TensorHandleArray](_o_h___a_i___tensor_handle_array.md) inputs, [OH_AI_TensorHandleArray](_o_h___a_i___tensor_handle_array.md) \*outputs, const [OH_AI_KernelCallBack](#oh_ai_kernelcallback) before, const [OH_AI_KernelCallBack](#oh_ai_kernelcallback) after) | Performs model inference. | +| [OH_AI_ModelGetInputs](#oh_ai_modelgetinputs) (const [OH_AI_ModelHandle](#oh_ai_modelhandle) model) | Obtains the input tensor array structure of a model. | +| [OH_AI_ModelGetOutputs](#oh_ai_modelgetoutputs) (const [OH_AI_ModelHandle](#oh_ai_modelhandle) model) | Obtains the output tensor array structure of a model. | +| [OH_AI_ModelGetInputByTensorName](#oh_ai_modelgetinputbytensorname) (const [OH_AI_ModelHandle](#oh_ai_modelhandle) model, const char \*tensor_name) | Obtains the input tensor of a model by tensor name. | +| [OH_AI_ModelGetOutputByTensorName](#oh_ai_modelgetoutputbytensorname) (const [OH_AI_ModelHandle](#oh_ai_modelhandle) model, const char \*tensor_name) | Obtains the output tensor of a model by tensor name. | +| [OH_AI_TensorCreate](#oh_ai_tensorcreate) (const char \*name, [OH_AI_DataType](#oh_ai_datatype) type, const int64_t \*shape, size_t shape_num, const void \*data, size_t data_len) | Creates a tensor object. | +| [OH_AI_TensorDestroy](#oh_ai_tensordestroy) ([OH_AI_TensorHandle](#oh_ai_tensorhandle) \*tensor) | Destroys a tensor object. | +| [OH_AI_TensorClone](#oh_ai_tensorclone) ([OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor) | Deeply copies a tensor. | +| [OH_AI_TensorSetName](#oh_ai_tensorsetname) ([OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor, const char \*name) | Sets the tensor name. | +| [OH_AI_TensorGetName](#oh_ai_tensorgetname) (const [OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor) | Obtains the tensor name. | +| [OH_AI_TensorSetDataType](#oh_ai_tensorsetdatatype) ([OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor, [OH_AI_DataType](#oh_ai_datatype) type) | Sets the data type of a tensor. | +| [OH_AI_TensorGetDataType](#oh_ai_tensorgetdatatype) (const [OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor) | Obtains the tensor type. | +| [OH_AI_TensorSetShape](#oh_ai_tensorsetshape) ([OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor, const int64_t \*shape, size_t shape_num) | Sets the tensor shape. | +| [OH_AI_TensorGetShape](#oh_ai_tensorgetshape) (const [OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor, size_t \*shape_num) | Obtains the tensor shape. | +| [OH_AI_TensorSetFormat](#oh_ai_tensorsetformat) ([OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor, [OH_AI_Format](#oh_ai_format) format) | Sets the tensor data format. | +| [OH_AI_TensorGetFormat](#oh_ai_tensorgetformat) (const [OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor) | Obtains the tensor data format. | +| [OH_AI_TensorSetData](#oh_ai_tensorsetdata) ([OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor, void \*data) | Sets the tensor data. | +| [OH_AI_TensorGetData](#oh_ai_tensorgetdata) (const [OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor) | Obtains the pointer to tensor data. | +| [OH_AI_TensorGetMutableData](#oh_ai_tensorgetmutabledata) (const [OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor) | Obtains the pointer to variable tensor data. If the data is empty, memory will be allocated. | +| [OH_AI_TensorGetElementNum](#oh_ai_tensorgetelementnum) (const [OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor) | Obtains the number of tensor elements. | +| [OH_AI_TensorGetDataSize](#oh_ai_tensorgetdatasize) (const [OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor) | Obtains the number of bytes of the tensor data. | ## Macro Description @@ -133,84 +154,116 @@ Provides APIs related to MindSpore Lite model inference. ### OH_AI_MAX_SHAPE_NUM - + ``` #define OH_AI_MAX_SHAPE_NUM 32 ``` -**Description**
+ +**Description** + Defines dimension information. The maximum dimension is set by **MS_MAX_SHAPE_NUM**. ## Type Description +### NNRTDeviceDesc + + +``` +typedef struct NNRTDeviceDesc NNRTDeviceDesc +``` + +**Description** + +Defines the NNRt device information, including the device ID and device name. + +**Since** + +10 + + ### OH_AI_CallBackParam - + ``` -typedef struct OH_AI_CallBackParamOH_AI_CallBackParam +typedef struct OH_AI_CallBackParam OH_AI_CallBackParam ``` -**Description**
+ +**Description** + Defines the operator information passed in a callback. ### OH_AI_ContextHandle - + ``` typedef void* OH_AI_ContextHandle ``` -**Description**
-Defines the pointer to the MindSpore context. + +**Description** + +Defines the pointer to the MindSpore context. ### OH_AI_DataType - + ``` -typedef enum OH_AI_DataTypeOH_AI_DataType +typedef enum OH_AI_DataType OH_AI_DataType ``` -**Description**
+ +**Description** + Declares data types supported by MSTensor. ### OH_AI_DeviceInfoHandle - + ``` typedef void* OH_AI_DeviceInfoHandle ``` -**Description**
+ +**Description** + Defines the pointer to the MindSpore device information. ### OH_AI_DeviceType - + ``` -typedef enum OH_AI_DeviceTypeOH_AI_DeviceType +typedef enum OH_AI_DeviceType OH_AI_DeviceType ``` -**Description**
+ +**Description** + Defines the supported device types. ### OH_AI_Format - + ``` -typedef enum OH_AI_FormatOH_AI_Format +typedef enum OH_AI_Format OH_AI_Format ``` -**Description**
+ +**Description** + Declares data formats supported by MSTensor. ### OH_AI_KernelCallBack - + ``` typedef bool(* OH_AI_KernelCallBack) (const OH_AI_TensorHandleArray inputs, const OH_AI_TensorHandleArray outputs, const OH_AI_CallBackParam kernel_Info) ``` -**Description**
+ +**Description** + Defines the pointer to a callback. This pointer is used to set the two callback functions in [OH_AI_ModelPredict](#oh_ai_modelpredict). Each callback function must contain three parameters, where **inputs** and **outputs** indicate the input and output tensors of the operator, and **kernel_Info** indicates information about the current operator. You can use the callback functions to monitor the operator execution status, for example, operator execution time and the operator correctness. @@ -218,51 +271,109 @@ This pointer is used to set the two callback functions in [OH_AI_ModelPredict](# ### OH_AI_ModelHandle - + ``` typedef void* OH_AI_ModelHandle ``` -**Description**
+ +**Description** + Defines the pointer to a model object. ### OH_AI_ModelType - + ``` -typedef enum OH_AI_ModelTypeOH_AI_ModelType +typedef enum OH_AI_ModelType OH_AI_ModelType ``` -**Description**
+ +**Description** + Defines model file types. +### OH_AI_NNRTDeviceType + + +``` +typedef enum OH_AI_NNRTDeviceType OH_AI_NNRTDeviceType +``` + +**Description** + +Defines NNRt device types. + +**Since** + +10 + + +### OH_AI_PerformanceMode + + +``` +typedef enum OH_AI_PerformanceMode OH_AI_PerformanceMode +``` + +**Description** + +Defines performance modes of the NNRt device. + +**Since** + +10 + + +### OH_AI_Priority + + +``` +typedef enum OH_AI_Priority OH_AI_Priority +``` + +**Description** + +Defines NNRt inference task priorities. + +**Since** + +10 + + ### OH_AI_Status - + ``` -typedef enum OH_AI_StatusOH_AI_Status +typedef enum OH_AI_Status OH_AI_Status ``` -**Description**
+ +**Description** + Defines MindSpore status codes. ### OH_AI_TensorHandle - + ``` typedef void* OH_AI_TensorHandle ``` -**Description**
+ +**Description** + Defines the handle of a tensor object. ### OH_AI_TensorHandleArray - + ``` -typedef struct OH_AI_TensorHandleArrayOH_AI_TensorHandleArray +typedef struct OH_AI_TensorHandleArray OH_AI_TensorHandleArray ``` -**Description**
+ +**Description** + Defines the tensor array structure, which is used to store the tensor array pointer and tensor array length. @@ -271,215 +382,304 @@ Defines the tensor array structure, which is used to store the tensor array poin ### OH_AI_CompCode - + ``` enum OH_AI_CompCode ``` -**Description**
-Defines MinSpore component codes. -| Name | Description | -| -------- | -------- | -| OH_AI_COMPCODE_CORE | MindSpore Core code | -| OH_AI_COMPCODE_LITE | MindSpore Lite code | +**Description** + +Defines MindSpore component codes. + +| Value | Description | +| ------------------- | --------------------- | +| OH_AI_COMPCODE_CORE | MindSpore Core code| +| OH_AI_COMPCODE_LITE | MindSpore Lite code| ### OH_AI_DataType - + ``` enum OH_AI_DataType ``` -**Description**
+ +**Description** + Declares data types supported by MSTensor. -| Name | Description | -| -------- | -------- | -| OH_AI_DATATYPE_UNKNOWN | Unknown data type | -| OH_AI_DATATYPE_OBJECTTYPE_STRING | String data type | -| OH_AI_DATATYPE_OBJECTTYPE_LIST | List data type | -| OH_AI_DATATYPE_OBJECTTYPE_TUPLE | Tuple data type | -| OH_AI_DATATYPE_OBJECTTYPE_TENSOR | TensorList data type | -| OH_AI_DATATYPE_NUMBERTYPE_BEGIN | Beginning of the number type | -| OH_AI_DATATYPE_NUMBERTYPE_BOOL | Bool data type | -| OH_AI_DATATYPE_NUMBERTYPE_INT8 | Int8 data type | -| OH_AI_DATATYPE_NUMBERTYPE_INT16 | Int16 data type | -| OH_AI_DATATYPE_NUMBERTYPE_INT32 | Int32 data type | -| OH_AI_DATATYPE_NUMBERTYPE_INT64 | Int64 data type | -| OH_AI_DATATYPE_NUMBERTYPE_UINT8 | UInt8 data type | -| OH_AI_DATATYPE_NUMBERTYPE_UINT16 | UInt16 data type | -| OH_AI_DATATYPE_NUMBERTYPE_UINT32 | UInt32 data type | -| OH_AI_DATATYPE_NUMBERTYPE_UINT64 | UInt64 data type | -| OH_AI_DATATYPE_NUMBERTYPE_FLOAT16 | Float16 data type | -| OH_AI_DATATYPE_NUMBERTYPE_FLOAT32 | Float32 data type | -| OH_AI_DATATYPE_NUMBERTYPE_FLOAT64 | Float64 data type | -| OH_AI_DATATYPE_NUMBERTYPE_END | End of the number type | -| OH_AI_DataTypeInvalid | Invalid data type | +| Value | Description | +| --------------------------------- | ---------------------- | +| OH_AI_DATATYPE_UNKNOWN | Unknown data type. | +| OH_AI_DATATYPE_OBJECTTYPE_STRING | String data. | +| OH_AI_DATATYPE_OBJECTTYPE_LIST | List data. | +| OH_AI_DATATYPE_OBJECTTYPE_TUPLE | Tuple data. | +| OH_AI_DATATYPE_OBJECTTYPE_TENSOR | TensorList data. | +| OH_AI_DATATYPE_NUMBERTYPE_BEGIN | Beginning of the number type. | +| OH_AI_DATATYPE_NUMBERTYPE_BOOL | Bool data. | +| OH_AI_DATATYPE_NUMBERTYPE_INT8 | Int8 data. | +| OH_AI_DATATYPE_NUMBERTYPE_INT16 | Int16 data. | +| OH_AI_DATATYPE_NUMBERTYPE_INT32 | Int32 data. | +| OH_AI_DATATYPE_NUMBERTYPE_INT64 | Int64 data. | +| OH_AI_DATATYPE_NUMBERTYPE_UINT8 | UInt8 data. | +| OH_AI_DATATYPE_NUMBERTYPE_UINT16 | UInt16 data . | +| OH_AI_DATATYPE_NUMBERTYPE_UINT32 | UInt32 data. | +| OH_AI_DATATYPE_NUMBERTYPE_UINT64 | UInt64 data. | +| OH_AI_DATATYPE_NUMBERTYPE_FLOAT16 | Float16 data. | +| OH_AI_DATATYPE_NUMBERTYPE_FLOAT32 | Float32 data. | +| OH_AI_DATATYPE_NUMBERTYPE_FLOAT64 | Float64 data. | +| OH_AI_DATATYPE_NUMBERTYPE_END | End of the number type.| +| OH_AI_DataTypeInvalid | Invalid data type. | ### OH_AI_DeviceType - + ``` enum OH_AI_DeviceType ``` -**Description**
+ +**Description** + Defines the supported device types. -| Name | Description | -| -------- | -------- | -| OH_AI_DEVICETYPE_CPU | Device type: CPU
since 9 | -| OH_AI_DEVICETYPE_GPU | Device type: GPU
Reserved, not support yet.
since 9 | -| OH_AI_DEVICETYPE_KIRIN_NPU | Device type: Kirin NPU
Reserved, not support yet.
since 9 | -| OH_AI_DEVICETYPE_NNRT | Device type: NNRt
OHOS-only device range[60,80).
since 9 | -| OH_AI_DEVICETYPE_INVALID | Invalid device type
since 9 | +| Value | Description | +| -------------------------- | --------------------------------------- | +| OH_AI_DEVICETYPE_CPU | Device type: CPU | +| OH_AI_DEVICETYPE_GPU | Device type: GPU Reserved | +| OH_AI_DEVICETYPE_KIRIN_NPU | Device type: Kirin NPU Reserved| +| OH_AI_DEVICETYPE_NNRT | Device type: NNRt OHOS device range: [60, 80)| +| OH_AI_DEVICETYPE_INVALID | Invalid device type | ### OH_AI_Format - + ``` enum OH_AI_Format ``` -**Description**
+ +**Description** + Declares data formats supported by MSTensor. -| Name | Description | -| -------- | -------- | -| OH_AI_FORMAT_NCHW | NCHW format | -| OH_AI_FORMAT_NHWC | NHWC format | -| OH_AI_FORMAT_NHWC4 | NHWC4 format | -| OH_AI_FORMAT_HWKC | HWKC format | -| OH_AI_FORMAT_HWCK | HWCK format | -| OH_AI_FORMAT_KCHW | KCHW format | -| OH_AI_FORMAT_CKHW | CKHW format | -| OH_AI_FORMAT_KHWC | KHWC format | -| OH_AI_FORMAT_CHWK | CHWK format | -| OH_AI_FORMAT_HW | HW format | -| OH_AI_FORMAT_HW4 | HW4 format | -| OH_AI_FORMAT_NC | NC format | -| OH_AI_FORMAT_NC4 | NC4 format | -| OH_AI_FORMAT_NC4HW4 | NC4HW4 format | -| OH_AI_FORMAT_NCDHW | NCDHW format | -| OH_AI_FORMAT_NWC | NWC format | -| OH_AI_FORMAT_NCW | NCW format | +| Value | Description | +| ------------------- | ---------------- | +| OH_AI_FORMAT_NCHW | Tensor data is stored in the sequence of batch number N, channel C, height H, and width W. | +| OH_AI_FORMAT_NHWC | Tensor data is stored in the sequence of batch number N, height H, width W, and channel C. | +| OH_AI_FORMAT_NHWC4 | Tensor data is stored in the sequence of batch number N, height H, width W, and channel C. The C axis is 4-byte aligned. | +| OH_AI_FORMAT_HWKC | Tensor data is stored in the sequence of height H, width W, core count K, and channel C. | +| OH_AI_FORMAT_HWCK | Tensor data is stored in the sequence of height H, width W, channel C, and core count K. | +| OH_AI_FORMAT_KCHW | Tensor data is stored in the sequence of core count K, channel C, height H, and width W. | +| OH_AI_FORMAT_CKHW | Tensor data is stored in the sequence of channel C, core count K, height H, and width W. | +| OH_AI_FORMAT_KHWC | Tensor data is stored in the sequence of core count K, height H, width W, and channel C. | +| OH_AI_FORMAT_CHWK | Tensor data is stored in the sequence of channel C, height H, width W, and core count K. | +| OH_AI_FORMAT_HW | Tensor data is stored in the sequence of height H and width W. | +| OH_AI_FORMAT_HW4 | Tensor data is stored in the sequence of height H and width W. The W axis is 4-byte aligned. | +| OH_AI_FORMAT_NC | Tensor data is stored in the sequence of batch number N and channel C. | +| OH_AI_FORMAT_NC4 | Tensor data is stored in the sequence of batch number N and channel C. The C axis is 4-byte aligned. | +| OH_AI_FORMAT_NC4HW4 | Tensor data is stored in the sequence of batch number N, channel C, height H, and width W. The C axis and W axis are 4-byte aligned.| +| OH_AI_FORMAT_NCDHW | Tensor data is stored in the sequence of batch number N, channel C, depth D, height H, and width W. | +| OH_AI_FORMAT_NWC | Tensor data is stored in the sequence of batch number N, width W, and channel C. | +| OH_AI_FORMAT_NCW | Tensor data is stored in the sequence of batch number N, channel C, and width W. | ### OH_AI_ModelType - + ``` enum OH_AI_ModelType ``` -**Description**
+ +**Description** + Defines model file types. -| Name | Description | -| -------- | -------- | -| OH_AI_MODELTYPE_MINDIR | Model type: MindIR
since 9 | -| OH_AI_MODELTYPE_INVALID | Invalid model type
since 9 | +| Value | Description | +| ----------------------- | ------------------ | +| OH_AI_MODELTYPE_MINDIR | Model type of MindIR. The extension of the model file name is **.ms**.| +| OH_AI_MODELTYPE_INVALID | Invalid model type. | + + +### OH_AI_NNRTDeviceType + + +``` +enum OH_AI_NNRTDeviceType +``` + +**Description** + +Defines NNRt device types. + +**Since** + +10 + +| Value | Description | +| ---------------------------- | ----------------------------------- | +| OH_AI_NNRTDEVICE_OTHERS | Others (any device type except the following three types).| +| OH_AI_NNRTDEVICE_CPU | CPU. | +| OH_AI_NNRTDEVICE_GPU | GPU. | +| OH_AI_NNRTDEVICE_ACCELERATOR | Specific acceleration device. | + + +### OH_AI_PerformanceMode + + +``` +enum OH_AI_PerformanceMode +``` + +**Description** + +Defines performance modes of the NNRt device. + +**Since** + +10 + +| Value | Description | +| ------------------------- | ------------------- | +| OH_AI_PERFORMANCE_NONE | No special settings. | +| OH_AI_PERFORMANCE_LOW | Low power consumption. | +| OH_AI_PERFORMANCE_MEDIUM | Power consumption and performance balancing.| +| OH_AI_PERFORMANCE_HIGH | High performance. | +| OH_AI_PERFORMANCE_EXTREME | Ultimate performance. | + + +### OH_AI_Priority + + +``` +enum OH_AI_Priority +``` + +**Description** + +Defines NNRt inference task priorities. + +**Since** + +10 + +| Value | Description | +| --------------------- | -------------- | +| OH_AI_PRIORITY_NONE | No priority preference.| +| OH_AI_PRIORITY_LOW | Low priority.| +| OH_AI_PRIORITY_MEDIUM | Medium priority| +| OH_AI_PRIORITY_HIGH | High priority. | ### OH_AI_Status - + ``` enum OH_AI_Status ``` -**Description**
-Defines MindSpore status codes. -| Name | Description | -| -------- | -------- | -| OH_AI_STATUS_SUCCESS | Success | -| OH_AI_STATUS_CORE_FAILED | MindSpore Core failure | -| OH_AI_STATUS_LITE_ERROR | MindSpore Lite error | -| OH_AI_STATUS_LITE_NULLPTR | MindSpore Lite null pointer | -| OH_AI_STATUS_LITE_PARAM_INVALID | MindSpore Lite invalid parameters | -| OH_AI_STATUS_LITE_NO_CHANGE | MindSpore Lite no change | -| OH_AI_STATUS_LITE_SUCCESS_EXIT | MindSpore Lite exit without errors | -| OH_AI_STATUS_LITE_MEMORY_FAILED | MindSpore Lite memory allocation failure | -| OH_AI_STATUS_LITE_NOT_SUPPORT | MindSpore Lite not supported | -| OH_AI_STATUS_LITE_THREADPOOL_ERROR | MindSpore Lite thread pool error | -| OH_AI_STATUS_LITE_UNINITIALIZED_OBJ | MindSpore Lite uninitialized | -| OH_AI_STATUS_LITE_OUT_OF_TENSOR_RANGE | MindSpore Lite tensor overflow | -| OH_AI_STATUS_LITE_INPUT_TENSOR_ERROR | MindSpore Lite input tensor error | -| OH_AI_STATUS_LITE_REENTRANT_ERROR | MindSpore Lite reentry error | -| OH_AI_STATUS_LITE_GRAPH_FILE_ERROR | MindSpore Lite file error | -| OH_AI_STATUS_LITE_NOT_FIND_OP | MindSpore Lite operator not found | -| OH_AI_STATUS_LITE_INVALID_OP_NAME | MindSpore Lite invalid operators | -| OH_AI_STATUS_LITE_INVALID_OP_ATTR | MindSpore Lite invalid operator hyperparameters | -| OH_AI_STATUS_LITE_OP_EXECUTE_FAILURE | MindSpore Lite operator execution failure | -| OH_AI_STATUS_LITE_FORMAT_ERROR | MindSpore Lite tensor format error | -| OH_AI_STATUS_LITE_INFER_ERROR | MindSpore Lite shape inference error | -| OH_AI_STATUS_LITE_INFER_INVALID | MindSpore Lite invalid shape inference | -| OH_AI_STATUS_LITE_INPUT_PARAM_INVALID | MindSpore Lite invalid input parameters | +**Description** + +Defines MindSpore status codes. +| Value | Description | +| ------------------------------------- | ----------------------------------------- | +| OH_AI_STATUS_SUCCESS | Success. | +| OH_AI_STATUS_CORE_FAILED | MindSpore Core failure. | +| OH_AI_STATUS_LITE_ERROR | MindSpore Lite error. | +| OH_AI_STATUS_LITE_NULLPTR | MindSpore Lite null pointer. | +| OH_AI_STATUS_LITE_PARAM_INVALID | MindSpore Lite invalid parameters. | +| OH_AI_STATUS_LITE_NO_CHANGE | MindSpore Lite no change. | +| OH_AI_STATUS_LITE_SUCCESS_EXIT | MindSpore Lite exit without errors.| +| OH_AI_STATUS_LITE_MEMORY_FAILED | MindSpore Lite memory allocation failure. | +| OH_AI_STATUS_LITE_NOT_SUPPORT | MindSpore Lite not supported. | +| OH_AI_STATUS_LITE_THREADPOOL_ERROR | MindSpore Lite thread pool error. | +| OH_AI_STATUS_LITE_UNINITIALIZED_OBJ | MindSpore Lite uninitialized. | +| OH_AI_STATUS_LITE_OUT_OF_TENSOR_RANGE | MindSpore Lite tensor overflow. | +| OH_AI_STATUS_LITE_INPUT_TENSOR_ERROR | MindSpore Lite input tensor error. | +| OH_AI_STATUS_LITE_REENTRANT_ERROR | MindSpore Lite reentry error. | +| OH_AI_STATUS_LITE_GRAPH_FILE_ERROR | MindSpore Lite file error. | +| OH_AI_STATUS_LITE_NOT_FIND_OP | MindSpore Lite operator not found. | +| OH_AI_STATUS_LITE_INVALID_OP_NAME | MindSpore Lite invalid operators. | +| OH_AI_STATUS_LITE_INVALID_OP_ATTR | MindSpore Lite invalid operator hyperparameters. | +| OH_AI_STATUS_LITE_OP_EXECUTE_FAILURE | MindSpore Lite operator execution failure. | +| OH_AI_STATUS_LITE_FORMAT_ERROR | MindSpore Lite tensor format error. | +| OH_AI_STATUS_LITE_INFER_ERROR | MindSpore Lite shape inference error. | +| OH_AI_STATUS_LITE_INFER_INVALID | MindSpore Lite invalid shape inference. | +| OH_AI_STATUS_LITE_INPUT_PARAM_INVALID | MindSpore Lite invalid input parameters.| ## Function Description ### OH_AI_ContextAddDeviceInfo() - + ``` OH_AI_API void OH_AI_ContextAddDeviceInfo (OH_AI_ContextHandle context, OH_AI_DeviceInfoHandle device_info ) ``` -**Description**
-Adds information about a running device. - **Parameters** +**Description** -| Name | Description | -| -------- | -------- | -| context | [OH_AI_ContextHandle](#oh_ai_contexthandle) that points to the context instance. | -| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance. | +Attaches the custom device information to the inference context. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| context | [OH_AI_ContextHandle](#oh_ai_contexthandle) that points to the context instance.| +| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance.| ### OH_AI_ContextCreate() - + ``` OH_AI_API OH_AI_ContextHandle OH_AI_ContextCreate () ``` -**Description**
+ +**Description** + Creates a context object. **Returns** -[OH_AI_ContextHandle](#oh_ai_contexthandle) that points to the context. +[OH_AI_ContextHandle](#oh_ai_contexthandle) that points to the context instance. ### OH_AI_ContextDestroy() - + ``` OH_AI_API void OH_AI_ContextDestroy (OH_AI_ContextHandle * context) ``` -**Description**
+ +**Description** + Destroys a context object. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| context | Level-2 pointer to [OH_AI_ContextHandle](#oh_ai_contexthandle). After the context is destroyed, the pointer is set to null. | +| Name | Description | +| ------- | ------------------------------------------------------------ | +| context | Level-2 pointer to [OH_AI_ContextHandle](#oh_ai_contexthandle). After the context is destroyed, the pointer is set to null. | ### OH_AI_ContextGetEnableParallel() - + ``` OH_AI_API bool OH_AI_ContextGetEnableParallel (const OH_AI_ContextHandle context) ``` -**Description**
+ +**Description** + Checks whether parallelism between operators is supported. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| context | [OH_AI_ContextHandle](#oh_ai_contexthandle) that points to the context instance. | +| Name | Description | +| ------- | ------------------------------------------------------------ | +| context | [OH_AI_ContextHandle](#oh_ai_contexthandle) that points to the context instance.| **Returns** @@ -488,59 +688,65 @@ Whether parallelism between operators is supported. The value **true** means tha ### OH_AI_ContextGetThreadAffinityCoreList() - + ``` OH_AI_API const int32_t* OH_AI_ContextGetThreadAffinityCoreList (const OH_AI_ContextHandle context, size_t * core_num ) ``` -**Description**
+ +**Description** + Obtains the list of bound CPU cores. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| context | [OH_AI_ContextHandle](#oh_ai_contexthandle) that points to the context instance. | -| core_num | Number of CPU cores. | +| Name | Description | +| -------- | ------------------------------------------------------------ | +| context | [OH_AI_ContextHandle](#oh_ai_contexthandle) that points to the context instance.| +| core_num | Number of CPU cores. | **Returns** -List of bound CPU cores. +Specifies the CPU core binding list. This list is managed by [OH_AI_ContextHandle](#oh_ai_contexthandle). The caller does not need to destroy it manually. ### OH_AI_ContextGetThreadAffinityMode() - + ``` OH_AI_API int OH_AI_ContextGetThreadAffinityMode (const OH_AI_ContextHandle context) ``` -**Description**
+ +**Description** + Obtains the affinity mode for binding runtime threads to CPU cores. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| context | [OH_AI_ContextHandle](#oh_ai_contexthandle) that points to the context instance. | +| Name | Description | +| ------- | ------------------------------------------------------------ | +| context | [OH_AI_ContextHandle](#oh_ai_contexthandle) that points to the context instance.| **Returns** -Affinity mode. **0**: no affinities; **1**: big cores first; **2**: little cores first +Affinity mode. **0**: no affinities; **1**: big cores first; **2**: medium cores first ### OH_AI_ContextGetThreadNum() - + ``` OH_AI_API int32_t OH_AI_ContextGetThreadNum (const OH_AI_ContextHandle context) ``` -**Description**
+ +**Description** + Obtains the number of threads. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| context | [OH_AI_ContextHandle](#oh_ai_contexthandle) that points to the context instance. | +| Name | Description | +| ------- | ------------------------------------------------------------ | +| context | [OH_AI_ContextHandle](#oh_ai_contexthandle) that points to the context instance.| **Returns** @@ -549,125 +755,239 @@ Number of threads. ### OH_AI_ContextSetEnableParallel() - + ``` OH_AI_API void OH_AI_ContextSetEnableParallel (OH_AI_ContextHandle context, bool is_parallel ) ``` -**Description**
-Sets whether to enable parallelism between operators. - **Parameters** +**Description** + +Sets whether to enable parallelism between operators. The setting is ineffective because the feature of this API is not yet available. -| Name | Description | -| -------- | -------- | -| context | [OH_AI_ContextHandle](#oh_ai_contexthandle) that points to the context instance. | -| is_parallel | Whether to enable parallelism between operators. The value **true** means to enable parallelism between operators, and the value **false** means the opposite. | +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| context | [OH_AI_ContextHandle](#oh_ai_contexthandle) that points to the context instance.| +| is_parallel | Whether parallelism between operators is supported. The value **true** means that parallelism between operators is supported, and the value **false** means the opposite. | ### OH_AI_ContextSetThreadAffinityCoreList() - + ``` OH_AI_API void OH_AI_ContextSetThreadAffinityCoreList (OH_AI_ContextHandle context, const int32_t * core_list, size_t core_num ) ``` -**Description**
+ +**Description** + Sets the list of CPU cores bound to a runtime thread. For example, if **core_list** is set to **[2,6,8]**, threads run on the 2nd, 6th, and 8th CPU cores. If [OH_AI_ContextSetThreadAffinityMode](#oh_ai_contextsetthreadaffinitymode) and [OH_AI_ContextSetThreadAffinityCoreList](#oh_ai_contextsetthreadaffinitycorelist) are called for the same context object, the **core_list** parameter of [OH_AI_ContextSetThreadAffinityCoreList](#oh_ai_contextsetthreadaffinitycorelist) takes effect, but the **mode** parameter of [OH_AI_ContextSetThreadAffinityMode](#oh_ai_contextsetthreadaffinitymode) does not. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| context | [OH_AI_ContextHandle](#oh_ai_contexthandle) that points to the context instance. | -| core_list | List of bound CPU cores. | -| core_num | Number of cores, which indicates the length of **core_list**. | +| Name | Description | +| --------- | ------------------------------------------------------------ | +| context | [OH_AI_ContextHandle](#oh_ai_contexthandle) that points to the context instance.| +| core_list | List of bound CPU cores. | +| core_num | Number of cores, which indicates the length of **core_list**. | ### OH_AI_ContextSetThreadAffinityMode() - + ``` OH_AI_API void OH_AI_ContextSetThreadAffinityMode (OH_AI_ContextHandle context, int mode ) ``` -**Description**
-Sets the affinity mode for binding runtime threads to CPU cores, which are categorized into little cores and big cores depending on the CPU frequency. - **Parameters** +**Description** + +Sets the affinity mode for binding runtime threads to CPU cores, which are classified into large, medium, and small cores based on the CPU frequency. You only need to bind the large or medium cores, but not small cores. + +**Parameters** -| Name | Description | -| -------- | -------- | -| context | [OH_AI_ContextHandle](#oh_ai_contexthandle) that points to the context instance. | -| mode | Affinity mode. **0**: no affinities; **1**: big cores first; **2**: little cores first | +| Name | Description | +| ------- | ------------------------------------------------------------ | +| context | [OH_AI_ContextHandle](#oh_ai_contexthandle) that points to the context instance.| +| mode | Affinity mode. **0**: no affinities; **1**: big cores first; **2**: medium cores first| ### OH_AI_ContextSetThreadNum() - + ``` OH_AI_API void OH_AI_ContextSetThreadNum (OH_AI_ContextHandle context, int32_t thread_num ) ``` -**Description**
+ +**Description** + Sets the number of runtime threads. - **Parameters** +**Parameters** + +| Name | Description | +| ---------- | ------------------------------------------------------------ | +| context | [OH_AI_ContextHandle](#oh_ai_contexthandle) that points to the context instance.| +| thread_num | Number of runtime threads. | + + +### OH_AI_CreateNNRTDeviceInfoByName() + + +``` +OH_AI_API OH_AI_DeviceInfoHandle OH_AI_CreateNNRTDeviceInfoByName (const char * name) +``` + +**Description** + +Searches for the NNRt device with the specified name and creates the NNRt device information based on the information about the first found NNRt device. + +**Parameters** + +| Name| Description | +| ---- | ---------------- | +| name | Name of the NNRt device.| + +**Returns** + +[OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance. + +**Since** + +10 + + +### OH_AI_CreateNNRTDeviceInfoByType() + + +``` +OH_AI_API OH_AI_DeviceInfoHandle OH_AI_CreateNNRTDeviceInfoByType (OH_AI_NNRTDeviceType type) +``` + +**Description** + +Searches for the NNRt device with the specified type and creates the NNRt device information based on the information about the first found NNRt device. + +**Parameters** + +| Name| Description | +| ---- | ------------------------------------------------------------ | +| type | NNRt device type, which is specified by [OH_AI_NNRTDeviceType](#oh_ai_nnrtdevicetype).| + +**Returns** + +[OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance. + +**Since** + +10 + + +### OH_AI_DestroyAllNNRTDeviceDescs() + + +``` +OH_AI_API void OH_AI_DestroyAllNNRTDeviceDescs (NNRTDeviceDesc ** desc) +``` + +**Description** + +Destroys the array of NNRT descriptions obtained by [OH_AI_GetAllNNRTDeviceDescs](#oh_ai_getallnnrtdevicedescs). + +**Parameters** -| Name | Description | -| -------- | -------- | -| context | [OH_AI_ContextHandle](#oh_ai_contexthandle) that points to the context instance. | -| thread_num | Number of runtime threads. | +| Name| Description | +| ---- | ------------------------------------------------------------ | +| desc | Double pointer to the array of the NNRt device descriptions. After the operation is complete, the content pointed to by **desc** is set to **NULL**.| + +**Since** + +10 ### OH_AI_DeviceInfoCreate() - + ``` OH_AI_API OH_AI_DeviceInfoHandle OH_AI_DeviceInfoCreate (OH_AI_DeviceType device_type) ``` -**Description**
+ +**Description** + Creates a device information object. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| device_type | Device type. For details, see [OH_AI_DeviceType](#oh_ai_devicetype). | +| Name | Description | +| ----------- | ------------------------------------------------------- | +| device_type | Device type, which is specified by [OH_AI_DeviceType](#oh_ai_devicetype).| **Returns** -[OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to the device information instance. +[OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance. ### OH_AI_DeviceInfoDestroy() - + ``` OH_AI_API void OH_AI_DeviceInfoDestroy (OH_AI_DeviceInfoHandle * device_info) ``` -**Description**
-Destroys a device information instance. - **Parameters** +**Description** + +Destroys a device information object. Note: After the device information instance is added to the context, the caller does not need to destroy it manually. + +**Parameters** -| Name | Description | -| -------- | -------- | -| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance. | +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance.| + + +### OH_AI_DeviceInfoGetDeviceId() + + +``` +OH_AI_API size_t OH_AI_DeviceInfoGetDeviceId (const OH_AI_DeviceInfoHandle device_info) +``` + +**Description** + +Obtains the ID of an NNRt device. This API is available only for NNRt devices. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance.| + +**Returns** + +NNRt device ID. + +**Since** + +10 ### OH_AI_DeviceInfoGetDeviceType() - + ``` OH_AI_API OH_AI_DeviceType OH_AI_DeviceInfoGetDeviceType (const OH_AI_DeviceInfoHandle device_info) ``` -**Description**
-Obtains the type of a provider device. - **Parameters** +**Description** + +Obtains the device type. -| Name | Description | -| -------- | -------- | -| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance. | +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance.| **Returns** @@ -676,18 +996,20 @@ Type of the provider device. ### OH_AI_DeviceInfoGetEnableFP16() - + ``` OH_AI_API bool OH_AI_DeviceInfoGetEnableFP16 (const OH_AI_DeviceInfoHandle device_info) ``` -**Description**
-Checks whether float16 inference is enabled. This function is available only for CPU/GPU devices. - **Parameters** +**Description** + +Checks whether float16 inference is enabled. This function is available only for CPU and GPU devices. + +**Parameters** -| Name | Description | -| -------- | -------- | -| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance. | +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance.| **Returns** @@ -696,38 +1018,94 @@ Whether float16 inference is enabled. ### OH_AI_DeviceInfoGetFrequency() - + ``` OH_AI_API int OH_AI_DeviceInfoGetFrequency (const OH_AI_DeviceInfoHandle device_info) ``` -**Description**
-Obtains the NPU frequency type. This function is available only for NPU devices. - **Parameters** +**Description** + +Obtains the NPU frequency type. This API is available only for NPU devices. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance.| + +**Returns** + +NPU frequency type. The value ranges from **0** to **4**. **1**: low power consumption; **2**: balanced; **3**: high performance; **4**: ultra-high performance + + +### OH_AI_DeviceInfoGetPerformanceMode() + + +``` +OH_AI_API OH_AI_PerformanceMode OH_AI_DeviceInfoGetPerformanceMode (const OH_AI_DeviceInfoHandle device_info) +``` + +**Description** + +Obtains the performance mode of an NNRt device. This API is available only for NNRt devices. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance.| + +**Returns** + +NNRt performance mode, which is specified by [OH_AI_PerformanceMode](#oh_ai_performancemode). + +**Since** + +10 + + +### OH_AI_DeviceInfoGetPriority() + + +``` +OH_AI_API OH_AI_Priority OH_AI_DeviceInfoGetPriority (const OH_AI_DeviceInfoHandle device_info) +``` + +**Description** -| Name | Description | -| -------- | -------- | -| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance. | +Obtains the priority of an NNRT task. This API is available only for NNRt devices. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance.| **Returns** -Frequency type of the NPU. The value ranges from **0** to **4**. **1**: low power consumption; **2**: balanced; **3**: high performance; **4**: ultra-high performance +NNRt task priority, which is specified by [OH_AI_Priority](#oh_ai_priority). + +**Since** + +10 ### OH_AI_DeviceInfoGetProvider() - + ``` OH_AI_API const char* OH_AI_DeviceInfoGetProvider (const OH_AI_DeviceInfoHandle device_info) ``` -**Description**
+ +**Description** + Obtains the provider name. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance. | +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance.| **Returns** @@ -736,150 +1114,339 @@ Provider name. ### OH_AI_DeviceInfoGetProviderDevice() - + ``` OH_AI_API const char* OH_AI_DeviceInfoGetProviderDevice (const OH_AI_DeviceInfoHandle device_info) ``` -**Description**
+ +**Description** + Obtains the name of a provider device. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance. | +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance.| **Returns** Name of the provider device. +### OH_AI_DeviceInfoSetDeviceId() + + +``` +OH_AI_API void OH_AI_DeviceInfoSetDeviceId (OH_AI_DeviceInfoHandle device_info, size_t device_id ) +``` + +**Description** + +Sets the ID of an NNRt device. This API is available only for NNRt devices. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance.| +| device_id | NNRt device ID. | + +**Since** + +10 + + ### OH_AI_DeviceInfoSetEnableFP16() - + ``` OH_AI_API void OH_AI_DeviceInfoSetEnableFP16 (OH_AI_DeviceInfoHandle device_info, bool is_fp16 ) ``` -**Description**
-Sets whether to enable float16 inference. This function is available only for CPU/GPU devices. - **Parameters** +**Description** + +Sets whether to enable float16 inference. This function is available only for CPU and GPU devices. + +**Parameters** -| Name | Description | -| -------- | -------- | -| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance. | -| is_fp16 | Whether to enable float16 inference. | +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance.| +| is_fp16 | Whether to enable the float16 inference mode. | ### OH_AI_DeviceInfoSetFrequency() - + ``` OH_AI_API void OH_AI_DeviceInfoSetFrequency (OH_AI_DeviceInfoHandle device_info, int frequency ) ``` -**Description**
+ +**Description** + Sets the NPU frequency type. This function is available only for NPU devices. - **Parameters** +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance.| +| frequency | NPU frequency type. The value ranges from **0** to **4**. The default value is **3**. **1**: low power consumption; **2**: balanced; **3**: high performance; **4**: ultra-high performance| + + +### OH_AI_DeviceInfoSetPerformanceMode() + + +``` +OH_AI_API void OH_AI_DeviceInfoSetPerformanceMode (OH_AI_DeviceInfoHandle device_info, OH_AI_PerformanceMode mode ) +``` + +**Description** + +Sets the performance mode of an NNRt device. This API is available only for NNRt devices. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance.| +| mode | NNRt performance mode, which is specified by [OH_AI_PerformanceMode](#oh_ai_performancemode).| + +**Since** -| Name | Description | -| -------- | -------- | -| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance. | -| frequency | NPU frequency type. The value ranges from **0** to **4**. The default value is **3**. **1**: low power consumption; **2**: balanced; **3**: high performance; **4**: ultra-high performance | +10 + + +### OH_AI_DeviceInfoSetPriority() + + +``` +OH_AI_API void OH_AI_DeviceInfoSetPriority (OH_AI_DeviceInfoHandle device_info, OH_AI_Priority priority ) +``` + +**Description** + +Sets the priority of an NNRt task. This API is available only for NNRt devices. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance.| +| priority | NNRt task priority, which is specified by [OH_AI_Priority](#oh_ai_priority). | + +**Since** + +10 ### OH_AI_DeviceInfoSetProvider() - + ``` OH_AI_API void OH_AI_DeviceInfoSetProvider (OH_AI_DeviceInfoHandle device_info, const char * provider ) ``` -**Description**
-Sets the name of a provider. - **Parameters** +**Description** + +Sets the provider name. -| Name | Description | -| -------- | -------- | -| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance. | -| provider | Provider name. | +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance.| +| provider | Provider name. | ### OH_AI_DeviceInfoSetProviderDevice() - + ``` OH_AI_API void OH_AI_DeviceInfoSetProviderDevice (OH_AI_DeviceInfoHandle device_info, const char * device ) ``` -**Description**
+ +**Description** + Sets the name of a provider device. - **Parameters** +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance.| +| device | Name of the provider device, for example, CPU. | + + +### OH_AI_GetAllNNRTDeviceDescs() + + +``` +OH_AI_API NNRTDeviceDesc* OH_AI_GetAllNNRTDeviceDescs (size_t * num) +``` + +**Description** + +Obtains the descriptions of all NNRt devices in the system. + +**Parameters** + +| Name| Description | +| ---- | ------------------------ | +| num | Number of NNRt devices.| + +**Returns** + +Pointer to the array of the NNRt device descriptions. If the operation fails, **NULL** is returned. + +**Since** + +10 + + +### OH_AI_GetDeviceIdFromNNRTDeviceDesc() + + +``` +OH_AI_API size_t OH_AI_GetDeviceIdFromNNRTDeviceDesc (const NNRTDeviceDesc * desc) +``` + +**Description** + +Obtains the NNRt device ID from the specified NNRt device description. Note that this ID is valid only for NNRt devices. + +**Parameters** -| Name | Description | -| -------- | -------- | -| device_info | [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) that points to a device information instance. | -| device | Name of the provider device, for example, CPU. | +| Name| Description | +| ---- | -------------------------------- | +| desc | Pointer to the NNRt device description.| + +**Returns** + +NNRt device ID. + +**Since** + +10 + + +### OH_AI_GetNameFromNNRTDeviceDesc() + + +``` +OH_AI_API const char* OH_AI_GetNameFromNNRTDeviceDesc (const NNRTDeviceDesc * desc) +``` + +**Description** + +Obtains the NNRt device name from the specified NNRt device description. + +**Parameters** + +| Name| Description | +| ---- | -------------------------------- | +| desc | Pointer to the NNRt device description.| + +**Returns** + +NNRt device name. The value is a pointer that points to a constant string, which is held by **desc**. The caller does not need to destroy it separately. + +**Since** + +10 + + +### OH_AI_GetTypeFromNNRTDeviceDesc() + + +``` +OH_AI_API OH_AI_NNRTDeviceType OH_AI_GetTypeFromNNRTDeviceDesc (const NNRTDeviceDesc * desc) +``` + +**Description** + +Obtains the NNRt device type from the specified NNRt device description. + +**Parameters** + +| Name| Description | +| ---- | -------------------------------- | +| desc | Pointer to the NNRt device description.| + +**Returns** + +NNRt device type, which is specified by [OH_AI_NNRTDeviceType](#oh_ai_nnrtdevicetype). + +**Since** + +10 ### OH_AI_ModelBuild() - + ``` OH_AI_API OH_AI_Status OH_AI_ModelBuild (OH_AI_ModelHandle model, const void * model_data, size_t data_size, OH_AI_ModelType model_type, const OH_AI_ContextHandle model_context ) ``` -**Description**
+ +**Description** + Loads and builds a MindSpore model from the memory buffer. Note that the same {\@Link OH_AI_ContextHandle} object can only be passed to {\@Link OH_AI_ModelBuild} or {\@Link OH_AI_ModelBuildFromFile} once. If you call this function multiple times, make sure that you create multiple {\@Link OH_AI_ContextHandle} objects accordingly. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| model | Pointer to the model object. | -| model_data | Address of the loaded model data in the memory. | -| data_size | Length of the model data. | -| model_type | Type of the model file. For details, see [OH_AI_ModelType](#oh_ai_modeltype). | -| model_context | Context for model running. For details, see [OH_AI_ContextHandle](#oh_ai_contexthandle). | +| Name | Description | +| ------------- | ------------------------------------------------------------ | +| model | Pointer to the model object. | +| model_data | Address of the loaded model data in the memory. | +| data_size | Length of the model data. | +| model_type | Model file type, which is specified by [OH_AI_ModelType](#oh_ai_modeltype). | +| model_context | Model runtime context, which is specified by [OH_AI_ContextHandle](#oh_ai_contexthandle).| **Returns** -Status code enumerated by [OH_AI_Status](#oh_ai_status). The value **MSStatus::kMSStatusSuccess** indicates that the operation is successful. +Status code enumerated by [OH_AI_Status](#oh_ai_status-1). The value **MSStatus::kMSStatusSuccess** indicates that the operation is successful. ### OH_AI_ModelBuildFromFile() - + ``` OH_AI_API OH_AI_Status OH_AI_ModelBuildFromFile (OH_AI_ModelHandle model, const char * model_path, OH_AI_ModelType model_type, const OH_AI_ContextHandle model_context ) ``` -**Description**
+ +**Description** + Loads and builds a MindSpore model from a model file. Note that the same {\@Link OH_AI_ContextHandle} object can only be passed to {\@Link OH_AI_ModelBuild} or {\@Link OH_AI_ModelBuildFromFile} once. If you call this function multiple times, make sure that you create multiple {\@Link OH_AI_ContextHandle} objects accordingly. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| model | Pointer to the model object. | -| model_path | Path of the model file. | -| model_type | Type of the model file. For details, see [OH_AI_ModelType](#oh_ai_modeltype). | -| model_context | Context for model running. For details, see [OH_AI_ContextHandle](#oh_ai_contexthandle). | +| Name | Description | +| ------------- | ------------------------------------------------------------ | +| model | Pointer to the model object. | +| model_path | Path of the model file. | +| model_type | Model file type, which is specified by [OH_AI_ModelType](#oh_ai_modeltype). | +| model_context | Model runtime context, which is specified by [OH_AI_ContextHandle](#oh_ai_contexthandle).| **Returns** -Status code enumerated by [OH_AI_Status](#oh_ai_status). The value **MSStatus::kMSStatusSuccess** indicates that the operation is successful. +Status code enumerated by [OH_AI_Status](#oh_ai_status-1). The value **MSStatus::kMSStatusSuccess** indicates that the operation is successful. ### OH_AI_ModelCreate() - + ``` OH_AI_API OH_AI_ModelHandle OH_AI_ModelCreate () ``` -**Description**
+ +**Description** + Creates a model object. **Returns** @@ -889,35 +1456,39 @@ Pointer to the model object. ### OH_AI_ModelDestroy() - + ``` OH_AI_API void OH_AI_ModelDestroy (OH_AI_ModelHandle * model) ``` -**Description**
+ +**Description** + Destroys a model object. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| model | Pointer to the model object. | +| Name | Description | +| ----- | -------------- | +| model | Pointer to the model object.| ### OH_AI_ModelGetInputByTensorName() - + ``` OH_AI_API OH_AI_TensorHandle OH_AI_ModelGetInputByTensorName (const OH_AI_ModelHandle model, const char * tensor_name ) ``` -**Description**
+ +**Description** + Obtains the input tensor of a model by tensor name. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| model | Pointer to the model object. | -| tensor_name | Tensor name. | +| Name | Description | +| ----------- | -------------- | +| model | Pointer to the model object.| +| tensor_name | Tensor name. | **Returns** @@ -926,18 +1497,20 @@ Pointer to the input tensor indicated by **tensor_name**. If the tensor does not ### OH_AI_ModelGetInputs() - + ``` OH_AI_API OH_AI_TensorHandleArray OH_AI_ModelGetInputs (const OH_AI_ModelHandle model) ``` -**Description**
+ +**Description** + Obtains the input tensor array structure of a model. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| model | Pointer to the model object. | +| Name | Description | +| ----- | -------------- | +| model | Pointer to the model object.| **Returns** @@ -946,39 +1519,43 @@ Tensor array structure corresponding to the model input. ### OH_AI_ModelGetOutputByTensorName() - + ``` OH_AI_API OH_AI_TensorHandle OH_AI_ModelGetOutputByTensorName (const OH_AI_ModelHandle model, const char * tensor_name ) ``` -**Description**
+ +**Description** + Obtains the output tensor of a model by tensor name. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| model | Pointer to the model object. | -| tensor_name | Tensor name. | +| Name | Description | +| ----------- | -------------- | +| model | Pointer to the model object.| +| tensor_name | Tensor name. | **Returns** -Pointer to the output tensor indicated by **tensor_name**. If the tensor does not exist in the input, **null** will be returned. +Pointer to the input tensor indicated by **tensor_name**. If the tensor does not exist, **null** will be returned. ### OH_AI_ModelGetOutputs() - + ``` OH_AI_API OH_AI_TensorHandleArray OH_AI_ModelGetOutputs (const OH_AI_ModelHandle model) ``` -**Description**
+ +**Description** + Obtains the output tensor array structure of a model. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| model | Pointer to the model object. | +| Name | Description | +| ----- | -------------- | +| model | Pointer to the model object.| **Returns** @@ -987,126 +1564,138 @@ Tensor array structure corresponding to the model output. ### OH_AI_ModelPredict() - + ``` OH_AI_API OH_AI_Status OH_AI_ModelPredict (OH_AI_ModelHandle model, const OH_AI_TensorHandleArray inputs, OH_AI_TensorHandleArray * outputs, const OH_AI_KernelCallBack before, const OH_AI_KernelCallBack after ) ``` -**Description**
+ +**Description** + Performs model inference. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| model | Pointer to the model object. | -| inputs | Tensor array structure corresponding to the model input. | -| outputs | Pointer to the tensor array structure corresponding to the model output. | -| before | Callback function executed before model inference. | -| after | Callback function executed after model inference. | +| Name | Description | +| ------- | ------------------------------------ | +| model | Pointer to the model object. | +| inputs | Tensor array structure corresponding to the model input. | +| outputs | Pointer to the tensor array structure corresponding to the model output.| +| before | Callback function executed before model inference. | +| after | Callback function executed after model inference. | **Returns** -Status code enumerated by [OH_AI_Status](#oh_ai_status). The value **MSStatus::kMSStatusSuccess** indicates that the operation is successful. +Status code enumerated by [OH_AI_Status](#oh_ai_status-1). The value **MSStatus::kMSStatusSuccess** indicates that the operation is successful. ### OH_AI_ModelResize() - + ``` OH_AI_API OH_AI_Status OH_AI_ModelResize (OH_AI_ModelHandle model, const OH_AI_TensorHandleArray inputs, OH_AI_ShapeInfo * shape_infos, size_t shape_info_num ) ``` -**Description**
+ +**Description** + Adjusts the input tensor shapes of a built model. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| model | Pointer to the model object. | -| inputs | Tensor array structure corresponding to the model input. | -| shape_infos | Input shape array, which consists of tensor shapes arranged in the model input sequence. The model adjusts the tensor shapes in sequence. | -| shape_info_num | Length of the input shape array. | +| Name | Description | +| -------------- | ------------------------------------------------------------ | +| model | Pointer to the model object. | +| inputs | Tensor array structure corresponding to the model input. | +| shape_infos | Input shape information array, which consists of tensor shapes arranged in the model input sequence. The model adjusts the tensor shapes in sequence.| +| shape_info_num | Length of the shape information array. | **Returns** -Status code enumerated by [OH_AI_Status](#oh_ai_status). The value **MSStatus::kMSStatusSuccess** indicates that the operation is successful. +Status code enumerated by [OH_AI_Status](#oh_ai_status-1). The value **MSStatus::kMSStatusSuccess** indicates that the operation is successful. ### OH_AI_TensorClone() - + ``` OH_AI_API OH_AI_TensorHandle OH_AI_TensorClone (OH_AI_TensorHandle tensor) ``` -**Description**
+ +**Description** + Clones a tensor. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| tensor | Pointer to the tensor to clone. | +| Name | Description | +| ------ | ------------------ | +| tensor | Pointer to the tensor to clone.| **Returns** -Handle of the new tensor object. +Defines the handle of a tensor object. ### OH_AI_TensorCreate() - + ``` OH_AI_API OH_AI_TensorHandle OH_AI_TensorCreate (const char * name, OH_AI_DataType type, const int64_t * shape, size_t shape_num, const void * data, size_t data_len ) ``` -**Description**
+ +**Description** + Creates a tensor object. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| name | Tensor name. | -| type | Tensor data type. | -| shape | Tensor dimension array. | -| shape_num | Length of the tensor dimension array. | -| data | Data pointer. | -| data_len | Data length. | +| Name | Description | +| --------- | ------------------ | +| name | Tensor name. | +| type | Tensor data type. | +| shape | Tensor dimension array. | +| shape_num | Length of the tensor dimension array.| +| data | Data pointer. | +| data_len | Data length. | **Returns** -Handle of the tensor object. +Defines the handle of a tensor object. ### OH_AI_TensorDestroy() - + ``` OH_AI_API void OH_AI_TensorDestroy (OH_AI_TensorHandle * tensor) ``` -**Description**
+ +**Description** + Destroys a tensor object. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| tensor | Level-2 pointer to the tensor handle. | +| Name | Description | +| ------ | ------------------------ | +| tensor | Level-2 pointer to the tensor handle.| ### OH_AI_TensorGetData() - + ``` OH_AI_API const void* OH_AI_TensorGetData (const OH_AI_TensorHandle tensor) ``` -**Description**
+ +**Description** + Obtains the pointer to tensor data. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| tensor | Handle of the tensor object. | +| Name | Description | +| ------ | -------------- | +| tensor | Handle of the tensor object.| **Returns** @@ -1115,18 +1704,20 @@ Pointer to tensor data. ### OH_AI_TensorGetDataSize() - + ``` OH_AI_API size_t OH_AI_TensorGetDataSize (const OH_AI_TensorHandle tensor) ``` -**Description**
+ +**Description** + Obtains the number of bytes of the tensor data. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| tensor | Handle of the tensor object. | +| Name | Description | +| ------ | -------------- | +| tensor | Handle of the tensor object.| **Returns** @@ -1135,38 +1726,42 @@ Number of bytes of the tensor data. ### OH_AI_TensorGetDataType() - + ``` OH_AI_API OH_AI_DataType OH_AI_TensorGetDataType (const OH_AI_TensorHandle tensor) ``` -**Description**
-Obtains the data type of a tensor. - **Parameters** +**Description** + +Obtains the tensor type. -| Name | Description | -| -------- | -------- | -| tensor | Handle of the tensor object. | +**Parameters** + +| Name | Description | +| ------ | -------------- | +| tensor | Handle of the tensor object.| **Returns** -Data type of the tensor. +Tensor data type. ### OH_AI_TensorGetElementNum() - + ``` OH_AI_API int64_t OH_AI_TensorGetElementNum (const OH_AI_TensorHandle tensor) ``` -**Description**
+ +**Description** + Obtains the number of tensor elements. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| tensor | Handle of the tensor object. | +| Name | Description | +| ------ | -------------- | +| tensor | Handle of the tensor object.| **Returns** @@ -1175,18 +1770,20 @@ Number of tensor elements. ### OH_AI_TensorGetFormat() - + ``` OH_AI_API OH_AI_Format OH_AI_TensorGetFormat (const OH_AI_TensorHandle tensor) ``` -**Description**
+ +**Description** + Obtains the tensor data format. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| tensor | Handle of the tensor object. | +| Name | Description | +| ------ | -------------- | +| tensor | Handle of the tensor object.| **Returns** @@ -1195,38 +1792,42 @@ Tensor data format. ### OH_AI_TensorGetMutableData() - + ``` OH_AI_API void* OH_AI_TensorGetMutableData (const OH_AI_TensorHandle tensor) ``` -**Description**
+ +**Description** + Obtains the pointer to variable tensor data. If the data is empty, memory will be allocated. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| tensor | Handle of the tensor object. | +| Name | Description | +| ------ | -------------- | +| tensor | Handle of the tensor object.| **Returns** -Pointer to variable tensor data. +Pointer to tensor data. ### OH_AI_TensorGetName() - + ``` OH_AI_API const char* OH_AI_TensorGetName (const OH_AI_TensorHandle tensor) ``` -**Description**
+ +**Description** + Obtains the name of a tensor. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| tensor | Handle of the tensor object. | +| Name | Description | +| ------ | -------------- | +| tensor | Handle of the tensor object.| **Returns** @@ -1235,106 +1836,118 @@ Tensor name. ### OH_AI_TensorGetShape() - + ``` OH_AI_API const int64_t* OH_AI_TensorGetShape (const OH_AI_TensorHandle tensor, size_t * shape_num ) ``` -**Description**
-Obtains the shape of a tensor. - **Parameters** +**Description** -| Name | Description | -| -------- | -------- | -| tensor | Handle of the tensor object. | -| shape_num | Length of the tensor shape array. | +Obtains the tensor shape. + +**Parameters** + +| Name | Description | +| --------- | ---------------------------------------------- | +| tensor | Handle of the tensor object. | +| shape_num | Length of the tensor shape array.| **Returns** -Tensor shape array. +Shape array. ### OH_AI_TensorSetData() - + ``` OH_AI_API void OH_AI_TensorSetData (OH_AI_TensorHandle tensor, void * data ) ``` -**Description**
+ +**Description** + Sets the tensor data. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| tensor | Handle of the tensor object. | -| data | Data pointer. | +| Name | Description | +| ------ | ---------------- | +| tensor | Handle of the tensor object. | +| data | Data pointer.| ### OH_AI_TensorSetDataType() - + ``` OH_AI_API void OH_AI_TensorSetDataType (OH_AI_TensorHandle tensor, OH_AI_DataType type ) ``` -**Description**
-Sets the data type of a tensor. - **Parameters** +**Description** + +Sets the tensor data type. -| Name | Description | -| -------- | -------- | -| tensor | Handle of the tensor object. | -| type | Data type. For details, see [OH_AI_DataType](#oh_ai_datatype). | +**Parameters** + +| Name | Description | +| ------ | --------------------------------------------------- | +| tensor | Handle of the tensor object. | +| type | Data type, which is specified by [OH_AI_DataType](#oh_ai_datatype).| ### OH_AI_TensorSetFormat() - + ``` OH_AI_API void OH_AI_TensorSetFormat (OH_AI_TensorHandle tensor, OH_AI_Format format ) ``` -**Description**
+ +**Description** + Sets the tensor data format. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| tensor | Handle of the tensor object. | -| format | Tensor data format. | +| Name | Description | +| ------ | ------------------ | +| tensor | Handle of the tensor object. | +| format | Tensor data format.| ### OH_AI_TensorSetName() - + ``` -OH_AI_API void OH_AI_TensorSetName (OH_AI_TensorHandle tensor, const char * name ) +OH_AI_API void OH_AI_TensorSetName (OH_AI_TensorHandle tensor, const char *name ) ``` -**Description**
-Sets the name of a tensor. - **Parameters** +**Description** + +Sets the tensor name. + +**Parameters** -| Name | Description | -| -------- | -------- | -| tensor | Handle of the tensor object. | -| name | Tensor name. | +| Name | Description | +| ------ | -------------- | +| tensor | Handle of the tensor object.| +| name | Tensor name. | ### OH_AI_TensorSetShape() - + ``` OH_AI_API void OH_AI_TensorSetShape (OH_AI_TensorHandle tensor, const int64_t * shape, size_t shape_num ) ``` -**Description**
-Sets the shape of a tensor. - **Parameters** +**Description** + +Sets the tensor shape. + +**Parameters** -| Name | Description | -| -------- | -------- | -| tensor | Handle of the tensor object. | -| shape | Tensor shape array. | -| shape_num | Length of the tensor shape array. | +| Name | Description | +| --------- | ------------------ | +| tensor | Handle of the tensor object. | +| shape | Shape array. | +| shape_num | Length of the tensor shape array.| diff --git a/en/application-dev/reference/native-apis/_o_h___cursor.md b/en/application-dev/reference/native-apis/_o_h___cursor.md new file mode 100644 index 0000000000000000000000000000000000000000..d2574c8aba7d46bc93c9ed77920d6990562834c8 --- /dev/null +++ b/en/application-dev/reference/native-apis/_o_h___cursor.md @@ -0,0 +1,39 @@ +# OH_Cursor + + +## Overview + +Defines a result set. + +It provides APIs to access the result set obtained by querying the RDB store. + +**Since** + +10 + +**Related Modules** + +[RDB](_r_d_b.md) + + +## Summary + + +### Member Variables + +| Name| Description| +| -------- | -------- | +| [id](_r_d_b.md) | Unique identifier of the **OH_Cursor** struct.| +| [getColumnCount](_r_d_b.md#getcolumncount) | Pointer to the function used to obtain the number of columns in the result set.| +| [getColumnType](_r_d_b.md#getcolumntype) | Pointer to the function used to obtain the column type based on the specified column index.| +| [getColumnIndex](_r_d_b.md#getcolumnindex) | Pointer to the function used to obtain the column index based on the specified column name.| +| [getColumnName](_r_d_b.md#getcolumnname) | Pointer to the function used to obtain the column name based on the specified column index.| +| [getRowCount](_r_d_b.md#getrowcount) | Pointer to the function used to obtain the number of rows in the result set.| +| [goToNextRow](_r_d_b.md#gotonextrow) | Pointer to the function used to go to the next row of the result set.| +| [getSize](_r_d_b.md#getsize) | Pointer to the function used to obtain information about the memory required when the column data type in the result set is **BLOB** or **TEXT**.| +| [getText](_r_d_b.md#gettext) | Pointer to the function used to obtain the value in the form of a string based on the specified column and the current row.| +| [getInt64](_r_d_b.md#getint64) | Pointer to the function used to obtain the value of the int64_t type based on the specified column and the current row.| +| [getReal](_r_d_b.md#getreal) | Pointer to the function used to obtain the value of the double type based on the specified column and the current row.| +| [getBlob](_r_d_b.md#getblob) | Pointer to the function used to obtain the value in the form of a byte array based on the specified column and the current row.| +| [isNull](_r_d_b.md#isnull-12) | Pointer to the function used to check whether the value in the specified column is null.| +| [close](_r_d_b.md#close) | Pointer to the function used to close a result set.| diff --git a/en/application-dev/reference/native-apis/_o_h___predicates.md b/en/application-dev/reference/native-apis/_o_h___predicates.md new file mode 100644 index 0000000000000000000000000000000000000000..c02ac4d93e38e7bd4437eb2f697724c29234812c --- /dev/null +++ b/en/application-dev/reference/native-apis/_o_h___predicates.md @@ -0,0 +1,48 @@ +# OH_Predicates + + +## Overview + +Defines the predicates. + +**Since** + +10 + +**Related Modules** + +[RDB](_r_d_b.md) + + +## Summary + + +### Member Variables + +| Name| Description| +| -------- | -------- | +| [id](_r_d_b.md#id-14) | Unique identifier of the **OH_Predicates** struct.| +| [equalTo](_r_d_b.md#equalto) | Pointer to the function used to set a predicates object to match the field whose value is equal to the specified value.| +| [notEqualTo](_r_d_b.md#notequalto) | Pointer to the function used to set a predicates object to match the field whose value is not equal to the specified value.| +| [beginWrap](_r_d_b.md#beginwrap) | Pointer to the function used to add a left parenthesis to the predicates.| +| [endWrap](_r_d_b.md#endwrap) | Pointer to the function used to add a right parenthesis to the predicates.| +| [orOperate](_r_d_b.md#oroperate) | Pointer to the function used to add the OR operator to the predicates.| +| [andOperate](_r_d_b.md#andoperate) | Pointer to the function used to add the AND operator to the predicates.| +| [isNull](_r_d_b.md#isnull-22) | Pointer to the function used to set a predicates object to match the field whose value is null.| +| [isNotNull](_r_d_b.md#isnotnull) | Pointer to the function used to set a predicates object to match the field whose value is not null.| +| [like](_r_d_b.md#like) | Pointer to the function used to set a predicates object to match a string that is similar to the specified value.| +| [between](_r_d_b.md#between) | Pointer to the function used to set a predicates object to match the field whose value is within the specified range.| +| [notBetween](_r_d_b.md#notbetween) | Pointer to the function used to set a predicates object to match the field whose value is out of the specified range.| +| [greaterThan](_r_d_b.md#greaterthan) | Pointer to the function used to set a predicates object to match the field with value greater than the specified value.| +| [lessThan](_r_d_b.md#lessthan) | Pointer to the function used to set a predicates object to match the field with value less than the specified value.| +| [greaterThanOrEqualTo](_r_d_b.md#greaterthanorequalto) | Pointer to the function used to set a predicates object to match the field with value greater than or equal to the specified value.| +| [lessThanOrEqualTo](_r_d_b.md#lessthanorequalto) | Pointer to the function used to set a predicates object to match the field with value less than or equal to the specified value.| +| [orderBy](_r_d_b.md#orderby) | Pointer to the function used to set a predicates object to sort the values in a column in ascending or descending order.| +| [distinct](_r_d_b.md#distinct) | Pointer to the function used to set a predicates object to filter out duplicate records.| +| [limit](_r_d_b.md#limit) | Pointer to the function used to set a predicates object to specify the maximum number of records.| +| [offset](_r_d_b.md#offset) | Pointer to the function used to set a predicates object to specify the start position of the returned result.| +| [groupBy](_r_d_b.md#groupby) | Pointer to the function used to set a predicates object to group rows that have the same value into summary rows.| +| [in](_r_d_b.md#in) | Pointer to the function used to set a predicates object to match the field with the value within the specified range.| +| [notIn](_r_d_b.md#notin) | Pointer to the function used to set a predicates object to match the field with the value out of the specified range.| +| [clear](_r_d_b.md#clear-12) | Pointer to the function used to clear a predicates instance.| +| [destroyPredicates](_r_d_b.md#destroypredicates) | Destroys an **OH_Predicates** object and reclaims the memory occupied.| diff --git a/en/application-dev/reference/native-apis/_o_h___rdb___config.md b/en/application-dev/reference/native-apis/_o_h___rdb___config.md new file mode 100644 index 0000000000000000000000000000000000000000..dd038af19093f2130667e78a7b38e0dc43d9c448 --- /dev/null +++ b/en/application-dev/reference/native-apis/_o_h___rdb___config.md @@ -0,0 +1,26 @@ +# OH_Rdb_Config + + +## Overview + +Defines the RDB store configuration. + +**Since** + +10 + +**Related Modules** + +[RDB](_r_d_b.md) + + +## Summary + + +### Member Variables + +| Name| Description| +| -------- | -------- | +| [path](_r_d_b.md#path) | Path of the database file.| +| [isEncrypt](_r_d_b.md#isencrypt) | Whether to encrypt the RDB store.| +| [securityLevel](_r_d_b.md#securitylevel) | RDB store security level [OH_Rdb_SecurityLevel](_r_d_b.md#oh_rdb_securitylevel).| diff --git a/en/application-dev/reference/native-apis/_o_h___rdb___store.md b/en/application-dev/reference/native-apis/_o_h___rdb___store.md new file mode 100644 index 0000000000000000000000000000000000000000..c57ebe39dbf8739ce7b1f62340e0a404454e4926 --- /dev/null +++ b/en/application-dev/reference/native-apis/_o_h___rdb___store.md @@ -0,0 +1,24 @@ +# OH_Rdb_Store + + +## Overview + +Defines the RDB store type. + +**Since** + +10 + +**Related Modules** + +[RDB](_r_d_b.md) + + +## Summary + + +### Member Variables + +| Name| Description| +| -------- | -------- | +| [id](_r_d_b.md#id-44) | Unique identifier of the **OH_Rdb_Store** struct.| diff --git a/en/application-dev/reference/native-apis/_o_h___v_bucket.md b/en/application-dev/reference/native-apis/_o_h___v_bucket.md new file mode 100644 index 0000000000000000000000000000000000000000..ff0386db852df79e82e58139dfb1177a26b79036 --- /dev/null +++ b/en/application-dev/reference/native-apis/_o_h___v_bucket.md @@ -0,0 +1,32 @@ +# OH_VBucket + + +## Overview + +Defines the types of the key and value in a KV pair. + +**Since** + +10 + +**Related Modules** + +[RDB](_r_d_b.md) + + +## Summary + + +### Member Variables + +| Name| Description| +| -------- | -------- | +| [id](_r_d_b.md#id-34) | Unique identifier of the **OH_VBucket** struct.| +| [capability](_r_d_b.md#capability) | Number of the KV pairs in the struct.| +| [putText](_r_d_b.md#puttext-12) | Puts a char value into the **OH_VBucket** object in the given column.| +| [putInt64](_r_d_b.md#putint64-12) | Puts an int64_t value into the **OH_VBucket** object in the given column.| +| [putReal](_r_d_b.md#putreal) | Puts a double value into the **OH_VBucket** object in the given column.| +| [putBlob](_r_d_b.md#putblob) | Puts a const uint8_t value into the **OH_VBucket** object in the given column.| +| [putNull](_r_d_b.md#putnull) | Puts a null value into the **OH_VBucket** object in the given column.| +| [clear](_r_d_b.md#clear-22) | Clears an **OH_VBucket** object.| +| [destroyValuesBucket](_r_d_b.md#destroyvaluesbucket) | Destroys an **OH_VBucket** object and reclaims the memory occupied.| diff --git a/en/application-dev/reference/native-apis/_o_h___v_object.md b/en/application-dev/reference/native-apis/_o_h___v_object.md new file mode 100644 index 0000000000000000000000000000000000000000..4c6232eecf485ea13ba9496e32265ff2af56a461 --- /dev/null +++ b/en/application-dev/reference/native-apis/_o_h___v_object.md @@ -0,0 +1,29 @@ +# OH_VObject + + +## Overview + +Defines the allowed data field types. + +**Since** + +10 + +**Related Modules** + +[RDB](_r_d_b.md) + + +## Summary + + +### Member Variables + +| Name| Description| +| -------- | -------- | +| [id](_r_d_b.md#id-24) | Unique identifier of the **OH_VObject** struct.| +| [putInt64](_r_d_b.md#putint64-22) | Converts a single parameter or an array of the int64 type into a value of the OH_VObject type.| +| [putDouble](_r_d_b.md#putdouble) | Converts a single parameter or an array of the int64 type into a value of the OH_VObject type.| +| [putText](_r_d_b.md#puttext-22) | Converts a character array of the char type to a value of the OH_VObject type.| +| [putTexts](_r_d_b.md#puttexts) | Converts a string array of the char type to a value of the OH_VObject type.| +| [destroyValueObject](_r_d_b.md#destroyvalueobject) | Destroys an OH_VObject object and reclaims the memory occupied.| diff --git a/en/application-dev/reference/native-apis/_r_d_b.md b/en/application-dev/reference/native-apis/_r_d_b.md new file mode 100644 index 0000000000000000000000000000000000000000..48b4394514d3da53f00cfc0272496f8b864220e2 --- /dev/null +++ b/en/application-dev/reference/native-apis/_r_d_b.md @@ -0,0 +1,2323 @@ +# RDB + + +## Overview + +The relational database (RDB) store manages data based on relational models. The RDB store provides a complete mechanism for managing local databases based on the underlying SQLite. It provides a series of methods for performing operations, such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements to satisfy different needs in complicated scenarios. + +\@syscap SystemCapability.DistributedDataManager.RelationalStore.Core + +**Since** + +10 + + +## Summary + + +### Files + +| Name| Description| +| -------- | -------- | +| [oh_cursor.h](oh__cursor_8h.md) | Provides APIs to access the result set obtained by querying the RDB store.
File to include: \| +| [oh_predicates.h](oh__predicates_8h.md) | Defines the predicates for RDB stores.
File to include: \| +| [oh_value_object.h](oh__value__object_8h.md) | Provides type conversion methods.
File to include: \| +| [oh_values_bucket.h](oh__values__bucket_8h.md) | Defines the types of the key and value in a key-value (KV) pair.
File to include: \| +| [relational_store.h](relational__store_8h.md) | Provides APIs to manage an RDB store.
File to include: \| +| [relational_store_error_code.h](relational__store__error__code_8h.md) | Declares the error codes used for RDB stores.
File to include: \| + + +### Structs + +| Name| Description| +| -------- | -------- | +| [OH_Cursor](_o_h___cursor.md) | Defines a result set.| +| [OH_Predicates](_o_h___predicates.md) | Defines a **predicates** object.| +| [OH_VObject](_o_h___v_object.md) | Defines the allowed data field types.| +| [OH_VBucket](_o_h___v_bucket.md) | Defines the types of the key and value in a KV pair.| +| [OH_Rdb_Config](_o_h___rdb___config.md) | Defines the RDB store configuration.| +| [OH_Rdb_Store](_o_h___rdb___store.md) | Defines the RDB store type.| + + +### Types + +| Name| Description| +| -------- | -------- | +| [OH_Cursor](#oh_cursor) | Indicates a result set.| +| [OH_Predicates](#oh_predicates) | Indicates a **predicates** object.| +| [OH_VObject](#oh_vobject) | Indicates the allowed data field types.| +| [OH_VBucket](#oh_vbucket) | Indicates the types of the key and value in a KV pair.| +| [OH_Rdb_ErrCode](#oh_rdb_errcode) | Indicates error codes.| + + +### Enums + +| Name| Description| +| -------- | -------- | +| [OH_ColumnType](#oh_columntype) {
TYPE_NULL = 0, TYPE_INT64, TYPE_REAL, TYPE_TEXT,
TYPE_BLOB
} | Enumerates the field types in an RDB store.| +| [OH_OrderType](#oh_ordertype) { ASC = 0, DESC = 1 } | Enumerates the sorting types.| +| [OH_Rdb_SecurityLevel](#oh_rdb_securitylevel) { S1 = 1, S2, S3, S4 } | Enumerates the RDB store security levels.| +| [OH_Rdb_ErrCode](#oh_rdb_errcode) {
RDB_ERR = -1, RDB_OK = 0, E_BASE = 14800000, RDB_E_NOT_SUPPORTED = 801,
RDB_E_ERROR = E_BASE, RDB_E_INVALID_ARGS = (E_BASE + 1), RDB_E_CANNOT_UPDATE_READONLY = (E_BASE + 2), RDB_E_REMOVE_FILE = (E_BASE + 3),
RDB_E_EMPTY_TABLE_NAME = (E_BASE + 5), RDB_E_EMPTY_VALUES_BUCKET = (E_BASE + 6), RDB_E_EXECUTE_IN_STEP_QUERY = (E_BASE + 7), RDB_E_INVALID_COLUMN_INDEX = (E_BASE + 8),
RDB_E_INVALID_COLUMN_TYPE = (E_BASE + 9), RDB_E_EMPTY_FILE_NAME = (E_BASE + 10), RDB_E_INVALID_FILE_PATH = (E_BASE + 11), RDB_E_TRANSACTION_IN_EXECUTE = (E_BASE + 12),
RDB_E_INVALID_STATEMENT = (E_BASE + 13), RDB_E_EXECUTE_WRITE_IN_READ_CONNECTION = (E_BASE + 14), RDB_E_BEGIN_TRANSACTION_IN_READ_CONNECTION = (E_BASE + 15), RDB_E_NO_TRANSACTION_IN_SESSION = (E_BASE + 16),
RDB_E_MORE_STEP_QUERY_IN_ONE_SESSION = (E_BASE + 17), RDB_E_NO_ROW_IN_QUERY = (E_BASE + 18), RDB_E_INVALID_BIND_ARGS_COUNT = (E_BASE + 19), RDB_E_INVALID_OBJECT_TYPE = (E_BASE + 20),
RDB_E_INVALID_CONFLICT_FLAG = (E_BASE + 21), RDB_E_HAVING_CLAUSE_NOT_IN_GROUP_BY = (E_BASE + 22), RDB_E_NOT_SUPPORTED_BY_STEP_RESULT_SET = (E_BASE + 23), RDB_E_STEP_RESULT_SET_CROSS_THREADS = (E_BASE + 24),
RDB_E_STEP_RESULT_QUERY_NOT_EXECUTED = (E_BASE + 25), RDB_E_STEP_RESULT_IS_AFTER_LAST = (E_BASE + 26), RDB_E_STEP_RESULT_QUERY_EXCEEDED = (E_BASE + 27), RDB_E_STATEMENT_NOT_PREPARED = (E_BASE + 28),
RDB_E_EXECUTE_RESULT_INCORRECT = (E_BASE + 29), RDB_E_STEP_RESULT_CLOSED = (E_BASE + 30), RDB_E_RELATIVE_PATH = (E_BASE + 31), RDB_E_EMPTY_NEW_ENCRYPT_KEY = (E_BASE + 32),
RDB_E_CHANGE_UNENCRYPTED_TO_ENCRYPTED = (E_BASE + 33), RDB_E_CHANGE_ENCRYPT_KEY_IN_BUSY = (E_BASE + 34), RDB_E_STEP_STATEMENT_NOT_INIT = (E_BASE + 35), RDB_E_NOT_SUPPORTED_ATTACH_IN_WAL_MODE = (E_BASE + 36),
RDB_E_CREATE_FOLDER_FAIL = (E_BASE + 37), RDB_E_SQLITE_SQL_BUILDER_NORMALIZE_FAIL = (E_BASE + 38), RDB_E_STORE_SESSION_NOT_GIVE_CONNECTION_TEMPORARILY = (E_BASE + 39), RDB_E_STORE_SESSION_NO_CURRENT_TRANSACTION = (E_BASE + 40),
RDB_E_NOT_SUPPORT = (E_BASE + 41), RDB_E_INVALID_PARCEL = (E_BASE + 42), RDB_E_QUERY_IN_EXECUTE = (E_BASE + 43), RDB_E_SET_PERSIST_WAL = (E_BASE + 44),
RDB_E_DB_NOT_EXIST = (E_BASE + 45), RDB_E_ARGS_READ_CON_OVERLOAD = (E_BASE + 46), RDB_E_WAL_SIZE_OVER_LIMIT = (E_BASE + 47), RDB_E_CON_OVER_LIMIT = (E_BASE + 48)
} | Enumerates the RDB store error codes.| + + +### Functions + +| Name| Description| +| -------- | -------- | +| [OH_Rdb_CreateValueObject](#oh_rdb_createvalueobject) (void) | Creates an [OH_VObject](_o_h___v_object.md) instance.| +| [OH_Rdb_CreateValuesBucket](#oh_rdb_createvaluesbucket) (void) | Creates an [OH_VBucket](_o_h___v_bucket.md) instance.| +| [OH_Rdb_CreatePredicates](#oh_rdb_createpredicates) (const char \*table) | Creates an [OH_Predicates](_o_h___predicates.md) instance.| +| [OH_Rdb_GetOrOpen](#oh_rdb_getoropen) (const [OH_Rdb_Config](_o_h___rdb___config.md) \*config, int \*errCode) | Obtains an [OH_Rdb_Store](_o_h___rdb___store.md) instance for RDB store operations.| +| [OH_Rdb_CloseStore](#oh_rdb_closestore) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store) | Destroys an [OH_Rdb_Store](_o_h___rdb___store.md) object and reclaims the memory occupied by the object.| +| [OH_Rdb_DeleteStore](#oh_rdb_deletestore) (const char \*path) | Deletes an RDB store with the specified database file configuration.| +| [OH_Rdb_Insert](#oh_rdb_insert) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*table, [OH_VBucket](_o_h___v_bucket.md) \*valuesBucket) | Inserts a row of data into a table.| +| [OH_Rdb_Update](#oh_rdb_update) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_VBucket](_o_h___v_bucket.md) \*valuesBucket, [OH_Predicates](_o_h___predicates.md) \*predicates) | Updates data in an RDB store based on specified conditions.| +| [OH_Rdb_Delete](#oh_rdb_delete) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_Predicates](_o_h___predicates.md) \*predicates) | Deletes data from an RDB store based on specified conditions.| +| [OH_Rdb_Query](#oh_rdb_query) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_Predicates](_o_h___predicates.md) \*predicates, const char \*const \*columnNames, int length) | Queries data in an RDB store based on specified conditions.| +| [OH_Rdb_Execute](#oh_rdb_execute) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*sql) | Executes an SQL statement but returns no value.| +| [OH_Rdb_ExecuteQuery](#oh_rdb_executequery) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*sql) | Executes the SQL statement to query data in an RDB store.| +| [OH_Rdb_BeginTransaction](#oh_rdb_begintransaction) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store) | Starts the transaction before executing the SQL statement.| +| [OH_Rdb_RollBack](#oh_rdb_rollback) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store) | Rolls back the SQL statements executed.| +| [OH_Rdb_Commit](#oh_rdb_commit) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store) | Commits the executed SQL statements.| +| [OH_Rdb_Backup](#oh_rdb_backup) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*databasePath) | Backs up an RDB store in the specified directory.| +| [OH_Rdb_Restore](#oh_rdb_restore) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*databasePath) | Restores an RDB store from the specified database backup file.| +| [OH_Rdb_GetVersion](#oh_rdb_getversion) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, int \*version) | Obtains the RDB store version.| +| [OH_Rdb_SetVersion](#oh_rdb_setversion) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, int version) | Sets the RDB store version.| + + +### Variables + +| Name| Description| +| -------- | -------- | +| OH_Cursor::id | Unique identifier of the **OH_Cursor** struct.| +| [OH_Cursor::getColumnCount](#getcolumncount) | Pointer to the function used to obtain the number of columns in the result set.| +| [OH_Cursor::getColumnType](#getcolumntype) | Pointer to the function used to obtain the column type based on the specified column index.| +| [OH_Cursor::getColumnIndex](#getcolumnindex) | Pointer to the function used to obtain the column index based on the specified column name.| +| [OH_Cursor::getColumnName](#getcolumnname) | Pointer to the function used to obtain the column name based on the specified column index.| +| [OH_Cursor::getRowCount](#getrowcount) | Pointer to the function used to obtain the number of rows in the result set.| +| [OH_Cursor::goToNextRow](#gotonextrow) | Pointer to the function used to go to the next row of the result set.| +| [OH_Cursor::getSize](#getsize) | Pointer to the function used to obtain information about the memory required when the column data type in the result set is **BLOB** or **TEXT**.| +| [OH_Cursor::getText](#gettext) | Pointer to the function used to obtain the value in the form of a string based on the specified column and the current row.| +| [OH_Cursor::getInt64](#getint64) | Pointer to the function used to obtain the value of the int64_t type based on the specified column and the current row.| +| [OH_Cursor::getReal](#getreal) | Pointer to the function used to obtain the value of the double type based on the specified column and the current row.| +| [OH_Cursor::getBlob](#getblob) | Pointer to the function used to obtain the value in the form of a byte array based on the specified column and the current row.| +| [OH_Cursor::isNull](#isnull-12) | Pointer to the function used to check whether the value in the specified column is null.| +| [OH_Cursor::close](#close) | Pointer to the function used to close a result set. | +| [OH_Predicates::id](#id-14) | Unique identifier of the **OH_Predicates** struct.| +| [OH_Predicates::equalTo](#equalto) | Pointer to the function used to set a predicates object to match the field whose value is equal to the specified value.| +| [OH_Predicates::notEqualTo](#notequalto) | Pointer to the function used to set a predicates object to match the field whose value is not equal to the specified value.| +| [OH_Predicates::beginWrap](#beginwrap) | Pointer to the function used to add a left parenthesis to the predicates.| +| [OH_Predicates::endWrap](#endwrap) | Pointer to the function used to add a right parenthesis to the predicates.| +| [OH_Predicates::orOperate](#oroperate) | Pointer to the function used to add the OR operator to the predicates.| +| [OH_Predicates::andOperate](#andoperate) | Pointer to the function used to add the AND operator to the predicates.| +| [OH_Predicates::isNull](#isnull-22) | Pointer to the function used to set a predicates object to match the field whose value is null.| +| [OH_Predicates::isNotNull](#isnotnull) | Pointer to the function used to set a predicates object to match the field whose value is not null.| +| [OH_Predicates::like](#like) | Pointer to the function used to set a predicates object to match a string that is similar to the specified value.| +| [OH_Predicates::between](#between) | Pointer to the function used to set a predicates object to match the field whose value is within the specified range.| +| [OH_Predicates::notBetween](#notbetween) | Pointer to the function used to set a predicates object to match the field whose value is out of the specified range.| +| [OH_Predicates::greaterThan](#greaterthan) | Pointer to the function used to set a predicates object to match the field with value greater than the specified value.| +| [OH_Predicates::lessThan](#lessthan) | Pointer to the function used to set a predicates object to match the field with value less than the specified value.| +| [OH_Predicates::greaterThanOrEqualTo](#greaterthanorequalto) | Pointer to the function used to set a predicates object to match the field with value greater than or equal to the specified value.| +| [OH_Predicates::lessThanOrEqualTo](#lessthanorequalto) | Pointer to the function used to set a predicates object to match the field with value less than or equal to the specified value.| +| [OH_Predicates::orderBy](#orderby) | Pointer to the function used to set a predicates object to sort the values in a column in ascending or descending order.| +| [OH_Predicates::distinct](#distinct) | Pointer to the function used to set a predicates object to filter out duplicate records.| +| [OH_Predicates::limit](#limit) | Pointer to the function used to set a predicates object to specify the maximum number of records.| +| [OH_Predicates::offset](#offset) | Pointer to the function used to set a predicates object to specify the start position of the returned result.| +| [OH_Predicates::groupBy](#groupby) | Pointer to the function used to set a predicates object to group rows that have the same value into summary rows.| +| [OH_Predicates::in](#in) | Pointer to the function used to set a predicates object to match the field with the value within the specified range.| +| [OH_Predicates::notIn](#notin) | Pointer to the function used to set a predicates object to match the field with the value out of the specified range.| +| [OH_Predicates::clear](#clear-12) | Pointer to the function used to clear a predicates instance.| +| [OH_Predicates::destroyPredicates](#destroypredicates) | Destroys an [OH_Predicates](_o_h___predicates.md) object and reclaims the memory occupied.| +| [OH_VObject::id](#id-24) | Unique identifier of the **OH_VObject** struct.| +| [OH_VObject::putInt64](#putint64-22) | Converts a single parameter or an array of the int64 type into a value of the [OH_VObject](_o_h___v_object.md) type.| +| [OH_VObject::putDouble](#putdouble) | Converts a single parameter or an array of the double type into a value of the [OH_VObject](_o_h___v_object.md) type.| +| [OH_VObject::putText](#puttext-22) | Converts a character array of the char type to a value of the [OH_VObject](_o_h___v_object.md) type.| +| [OH_VObject::putTexts](#puttexts) | Converts a string array of the char type to a value of the [OH_VObject](_o_h___v_object.md) type.| +| [OH_VObject::destroyValueObject](#destroyvalueobject) | Destroys an [OH_VObject](_o_h___v_object.md) object and reclaims the memory occupied.| +| [OH_VBucket::id](#id-34) | Unique identifier of the **OH_VBucket** struct.| +| [OH_VBucket::capability](#capability) | Number of the KV pairs in the struct.| +| [OH_VBucket::putText](#puttext-12) | Puts a char value into the [OH_VBucket](_o_h___v_bucket.md) object in the given column.| +| [OH_VBucket::putInt64](#putint64-12) | Puts an int64_t value into the [OH_VBucket](_o_h___v_bucket.md) object in the given column.| +| [OH_VBucket::putReal](#putreal) | Puts a double value into the [OH_VBucket](_o_h___v_bucket.md) object in the given column.| +| [OH_VBucket::putBlob](#putblob) | Puts a const uint8_t value into the [OH_VBucket](_o_h___v_bucket.md) object in the given column.| +| [OH_VBucket::putNull](#putnull) | Puts a null value into the [OH_VBucket](_o_h___v_bucket.md) object in the given column.| +| [OH_VBucket::clear](#clear-22) | Clears an [OH_VBucket](_o_h___v_bucket.md) object.| +| [OH_VBucket::destroyValuesBucket](#destroyvaluesbucket) | Destroys an [OH_VBucket](_o_h___v_bucket.md) object and reclaims the memory occupied.| +| [OH_Rdb_Config::path](#path) | Path of the database file.| +| [OH_Rdb_Config::isEncrypt](#isencrypt) | Whether to encrypt the RDB store.| +| [OH_Rdb_Config::securityLevel](#securitylevel) | Set the RDB store security level [OH_Rdb_SecurityLevel](#oh_rdb_securitylevel).| +| [OH_Rdb_Store::id](#id-44) | Unique identifier of the **OH_Rdb_Store** struct.| + + +## Type Description + + +### OH_Cursor + + +``` +typedef struct OH_Cursor OH_Cursor +``` + +**Description** + +Indicates a result set. + +It provides APIs to access the result set obtained by querying the RDB store. + + +### OH_Predicates + + +``` +typedef struct OH_Predicates OH_Predicates +``` + +**Description** + +Indicates a **predicates** object. + + +### OH_Rdb_ErrCode + + +``` +typedef enum OH_Rdb_ErrCode OH_Rdb_ErrCode +``` + +**Description** + +Indicates an error code. + + +### OH_VBucket + + +``` +typedef struct OH_VBucket OH_VBucket +``` + +**Description** + +Indicates the types of the key and value in a KV pair. + + +### OH_VObject + + +``` +typedef struct OH_VObject OH_VObject +``` + +**Description** + +Indicates the allowed data field types. + + +## Enum Description + + +### OH_ColumnType + + +``` +enum OH_ColumnType +``` + +**Description** + +Enumerates the field types in an RDB store. + +| Value| Description| +| -------- | -------- | +| TYPE_NULL | NULL type.| +| TYPE_INT64 | INT64 type.| +| TYPE_REAL | REAL type.| +| TYPE_TEXT | TEXT type.| +| TYPE_BLOB | BLOB type.| + + +### OH_OrderType + + +``` +enum OH_OrderType +``` + +**Description** + +Enumerates the sorting types. + +| Value| Description| +| -------- | -------- | +| ASC | Ascending order.| +| DESC | Descending order.| + + +### OH_Rdb_ErrCode + + +``` +enum OH_Rdb_ErrCode +``` + +**Description** + +Enumerates the error codes. + +| Value| Description| +| -------- | -------- | +| RDB_ERR | Execution failed.| +| RDB_OK | Execution successful.| +| E_BASE | Base of the error code.| +| RDB_E_NOT_SUPPORTED | The RDB store does not have this capability.| +| RDB_E_ERROR | Common exception.| +| RDB_E_INVALID_ARGS | Invalid parameter.| +| RDB_E_CANNOT_UPDATE_READONLY | Failed to update data because the RDB store is read-only.| +| RDB_E_REMOVE_FILE | Failed to delete the file.| +| RDB_E_EMPTY_TABLE_NAME | The table name is empty.| +| RDB_E_EMPTY_VALUES_BUCKET | The content of the KV pair is empty.| +| RDB_E_EXECUTE_IN_STEP_QUERY | The SQL statement executed during the query is incorrect.| +| RDB_E_INVALID_COLUMN_INDEX | The column index is invalid.| +| RDB_E_INVALID_COLUMN_TYPE | The column type is invalid.| +| RDB_E_EMPTY_FILE_NAME | The file name is empty.| +| RDB_E_INVALID_FILE_PATH | The file path is invalid.| +| RDB_E_TRANSACTION_IN_EXECUTE | Failed to start the transaction.| +| RDB_E_INVALID_STATEMENT | Failed to precompile the SQL statement.| +| RDB_E_EXECUTE_WRITE_IN_READ_CONNECTION | Failed to perform a write operation in a read connection.| +| RDB_E_BEGIN_TRANSACTION_IN_READ_CONNECTION | Failed to start the transaction in a read connection.| +| RDB_E_NO_TRANSACTION_IN_SESSION | The transaction to start does not exist in the database session.| +| RDB_E_MORE_STEP_QUERY_IN_ONE_SESSION | Multiple queries are executed in a database session.| +| RDB_E_NO_ROW_IN_QUERY | The result set does not contain any record.| +| RDB_E_INVALID_BIND_ARGS_COUNT | The number of parameters bound in the SQL statement is invalid.| +| RDB_E_INVALID_OBJECT_TYPE | The object type is invalid.| +| RDB_E_INVALID_CONFLICT_FLAG | The conflict resolution type is invalid.| +| RDB_E_HAVING_CLAUSE_NOT_IN_GROUP_BY | The HAVING keyword can be used only after GROUP BY.| +| RDB_E_NOT_SUPPORTED_BY_STEP_RESULT_SET | The result set by step is not supported.| +| RDB_E_STEP_RESULT_SET_CROSS_THREADS | Failed to obtain the result set.| +| RDB_E_STEP_RESULT_QUERY_NOT_EXECUTED | The result set query statement is not executed.| +| RDB_E_STEP_RESULT_IS_AFTER_LAST | The cursor of the result set is already in the last row.| +| RDB_E_STEP_RESULT_QUERY_EXCEEDED | The number of result set query times exceeds the limit.| +| RDB_E_STATEMENT_NOT_PREPARED | The SQL statement is not precompiled.| +| RDB_E_EXECUTE_RESULT_INCORRECT | The database execution result is incorrect.| +| RDB_E_STEP_RESULT_CLOSED | The result set has been closed.| +| RDB_E_RELATIVE_PATH | The file path is a relative path.| +| RDB_E_EMPTY_NEW_ENCRYPT_KEY | The new encrypt key is empty.| +| RDB_E_CHANGE_UNENCRYPTED_TO_ENCRYPTED | The RDB store is non-encrypted and cannot be changed.| +| RDB_E_CHANGE_ENCRYPT_KEY_IN_BUSY | The database does not respond when the database key is updated.| +| RDB_E_STEP_STATEMENT_NOT_INIT | The precompiled SQL statement is not initialized.| +| RDB_E_NOT_SUPPORTED_ATTACH_IN_WAL_MODE | The WAL mode does not support the ATTACH operation.| +| RDB_E_CREATE_FOLDER_FAIL | Failed to create the folder.| +| RDB_E_SQLITE_SQL_BUILDER_NORMALIZE_FAIL | Failed to build the SQL statement.| +| RDB_E_STORE_SESSION_NOT_GIVE_CONNECTION_TEMPORARILY | The database session does not provide a connection.| +| RDB_E_STORE_SESSION_NO_CURRENT_TRANSACTION | The transaction does not exist in the database session.| +| RDB_E_NOT_SUPPORT | The current operation is not supported.| +| RDB_E_INVALID_PARCEL | The current PARCEL is invalid.| +| RDB_E_QUERY_IN_EXECUTE | Failed to execute query.| +| RDB_E_SET_PERSIST_WAL | Failed to set the persistence of the database file in WAL mode.| +| RDB_E_DB_NOT_EXIST | The database does not exist.| +| RDB_E_ARGS_READ_CON_OVERLOAD | The number of read connections to set is greater than the limit.| +| RDB_E_WAL_SIZE_OVER_LIMIT | The WAL log file size exceeds the default value.| +| RDB_E_CON_OVER_LIMIT | The number of database connections has reached the limit.| + + +### OH_Rdb_SecurityLevel + + +``` +enum OH_Rdb_SecurityLevel +``` + +**Description** + +Enumerates the RDB store security levels. + +| Value| Description| +| -------- | -------- | +| S1 | The security level of the RDB store is low.
If data leakage occurs, minor impact will be caused.| +| S2 | The security level of the RDB store is medium.
If data leakage occurs, moderate impact will be caused.| +| S3 | The security level of the RDB store is high.
If data leakage occurs, major impact will be caused.| +| S4 | The security level of the RDB store is critical.
If data leakage occurs, critical impact will be caused.| + + +## Function Description + + +### OH_Rdb_Backup() + + +``` +int OH_Rdb_Backup (OH_Rdb_Store * store, const char * databasePath ) +``` + +**Description** + +Backs up an RDB store in the specified directory. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| +| databasePath | Pointer to the destination directory in which the RDB store is backed up.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_Rdb_Store](_o_h___rdb___store.md). + + +### OH_Rdb_BeginTransaction() + + +``` +int OH_Rdb_BeginTransaction (OH_Rdb_Store * store) +``` + +**Description** + +Starts the transaction before executing the SQL statement. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_Rdb_Store](_o_h___rdb___store.md). + + +### OH_Rdb_CloseStore() + + +``` +int OH_Rdb_CloseStore (OH_Rdb_Store * store) +``` + +**Description** + +Destroys an [OH_Rdb_Store](_o_h___rdb___store.md) object and reclaims the memory occupied. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_Rdb_Store](_o_h___rdb___store.md). + + +### OH_Rdb_Commit() + + +``` +int OH_Rdb_Commit (OH_Rdb_Store * store) +``` + +**Description** + +Commits the executed SQL statements. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_Rdb_Store](_o_h___rdb___store.md). + + +### OH_Rdb_CreatePredicates() + + +``` +OH_Predicates* OH_Rdb_CreatePredicates (const char * table) +``` + +**Description** + +Creates an [OH_Predicates](_o_h___predicates.md) instance. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| table | Pointer to the name of the database table.| + +**Returns** + +Returns the pointer to the [OH_Predicates](_o_h___predicates.md) instance created if the operation is successful; returns null otherwise. + +**See** + +[OH_Predicates](_o_h___predicates.md). + + +### OH_Rdb_CreateValueObject() + + +``` +OH_VObject* OH_Rdb_CreateValueObject (void ) +``` + +**Description** + +Creates an [OH_VObject](_o_h___v_object.md) instance. + +**Returns** + +Returns the pointer to the [OH_VObject](_o_h___v_object.md) instance created if the operation is successful; returns null otherwise. + +**See** + +[OH_VObject](_o_h___v_object.md). + + +### OH_Rdb_CreateValuesBucket() + + +``` +OH_VBucket* OH_Rdb_CreateValuesBucket (void ) +``` + +**Description** + +Creates an [OH_VBucket](_o_h___v_bucket.md) instance. + +**Returns** + +Returns the pointer to the [OH_VBucket](_o_h___v_bucket.md) instance created if the operation is successful; returns null otherwise. + +**See** + +[OH_VBucket](_o_h___v_bucket.md). + + +### OH_Rdb_Delete() + + +``` +int OH_Rdb_Delete (OH_Rdb_Store * store, OH_Predicates * predicates ) +``` + +**Description** + +Deletes data from an RDB store based on specified conditions. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance, which specifies the deletion conditions.| + +**Returns** + +Returns the number of affected rows if the operation is successful; returns an error code otherwise. + +**See** + +[OH_Rdb_Store](_o_h___rdb___store.md), [OH_Predicates](_o_h___predicates.md). + + +### OH_Rdb_DeleteStore() + + +``` +int OH_Rdb_DeleteStore (const char * path) +``` + +**Description** + +Deletes an RDB store with the specified database file configuration. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| path | Pointer to the database path.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + + +### OH_Rdb_Execute() + + +``` +int OH_Rdb_Execute (OH_Rdb_Store * store, const char * sql ) +``` + +**Description** + +Executes an SQL statement but returns no value. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| +| sql | Pointer to the SQL statement to execute.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_Rdb_Store](_o_h___rdb___store.md). + + +### OH_Rdb_ExecuteQuery() + + +``` +OH_Cursor* OH_Rdb_ExecuteQuery (OH_Rdb_Store * store, const char * sql ) +``` + +**Description** + +Executes the SQL statement to query data in an RDB store. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| +| sql | Pointer to the SQL statement to execute.| + +**Returns** + +Returns the pointer to the [OH_Cursor](_o_h___cursor.md) instance if the operation is successful; returns null otherwise. + +**See** + +[OH_Rdb_Store](_o_h___rdb___store.md). + + +### OH_Rdb_GetOrOpen() + + +``` +OH_Rdb_Store* OH_Rdb_GetOrOpen (const OH_Rdb_Config * config, int * errCode ) +``` + +**Description** + +Obtains an [OH_Rdb_Store](_o_h___rdb___store.md) instance for RDB store operations. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| config | Pointer to the [OH_Rdb_Config](_o_h___rdb___config.md) instance, which specifies the database configuration.| +| errCode | Function execution status.| + +**Returns** + +Returns the pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance created if the operation is successful; returns null otherwise. + +**See** + +[OH_Rdb_Config](_o_h___rdb___config.md), [OH_Rdb_Store](_o_h___rdb___store.md). + + +### OH_Rdb_GetVersion() + + +``` +int OH_Rdb_GetVersion (OH_Rdb_Store * store, int * version ) +``` + +**Description** + +Obtains the RDB store version. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| +| version | Pointer to the version number.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_Rdb_Store](_o_h___rdb___store.md). + + +### OH_Rdb_Insert() + + +``` +int OH_Rdb_Insert (OH_Rdb_Store * store, const char * table, OH_VBucket * valuesBucket ) +``` + +**Description** + +Inserts a row of data into a table. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| +| table | Pointer to the target table.| +| valuesBucket | Pointer to the data [OH_VBucket](_o_h___v_bucket.md) to insert.| + +**Returns** + +Returns the row ID if the operation is successful; returns an error code otherwise. + +**See** + +[OH_Rdb_Store](_o_h___rdb___store.md), [OH_VBucket](_o_h___v_bucket.md). + + +### OH_Rdb_Query() + + +``` +OH_Cursor* OH_Rdb_Query (OH_Rdb_Store * store, OH_Predicates * predicates, const char *const * columnNames, int length ) +``` + +**Description** + +Queries data in an RDB store based on specified conditions. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance, which specifies the query conditions.| +| columnNames | Pointer to the columns to query. If this parameter is not specified, data of columns will be queried.| +| length | Length of the **columnNames** array.| + +**Returns** + +Returns the pointer to the [OH_Cursor](_o_h___cursor.md) instance if the operation is successful; returns null otherwise. + +**See** + +[OH_Rdb_Store](_o_h___rdb___store.md), [OH_Predicates](_o_h___predicates.md), [OH_Cursor](_o_h___cursor.md). + + +### OH_Rdb_Restore() + + +``` +int OH_Rdb_Restore (OH_Rdb_Store * store, const char * databasePath ) +``` + +**Description** + +Restores an RDB store from the specified database backup file. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| +| databasePath | Pointer to the path of the RDB store backup file.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_Rdb_Store](_o_h___rdb___store.md). + + +### OH_Rdb_RollBack() + + +``` +int OH_Rdb_RollBack (OH_Rdb_Store * store) +``` + +**Description** + +Rolls back the SQL statements executed. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_Rdb_Store](_o_h___rdb___store.md). + + +### OH_Rdb_SetVersion() + + +``` +int OH_Rdb_SetVersion (OH_Rdb_Store * store, int version ) +``` + +**Description** + +Sets the RDB store version. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| +| version | Version number to set.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_Rdb_Store](_o_h___rdb___store.md). + + +### OH_Rdb_Update() + + +``` +int OH_Rdb_Update (OH_Rdb_Store * store, OH_VBucket * valuesBucket, OH_Predicates * predicates ) +``` + +**Description** + +Updates data in an RDB store based on specified conditions. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| +| valuesBucket | Pointer to the new data [OH_VBucket](_o_h___v_bucket.md) to be updated to the table.| +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance, specifying the update conditions.| + +**Returns** + +Returns the number of affected rows if the operation is successful; returns an error code otherwise. + +**See** + +[OH_Rdb_Store](_o_h___rdb___store.md), OH_Bucket, [OH_Predicates](_o_h___predicates.md). + + +## Variable Description + + +### andOperate + + +``` +OH_Predicates*(* OH_Predicates::andOperate) (OH_Predicates *predicates) +``` + +**Description** + +Pointer to the function used to add the AND operator to the predicates. + +This method is equivalent to **AND** in SQL statements. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| + +**Returns** + +Returns the predicates with the AND operator. + +**See** + +[OH_Predicates](_o_h___predicates.md). + + +### beginWrap + + +``` +OH_Predicates*(* OH_Predicates::beginWrap) (OH_Predicates *predicates) +``` + +**Description** + +Pointer to the function used to add a left parenthesis to the predicates. + +This method is equivalent to "(" in SQL statements. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| + +**Returns** + +Returns the predicates with a left parenthesis. + +**See** + +[OH_Predicates](_o_h___predicates.md). + + +### between + + +``` +OH_Predicates*(* OH_Predicates::between) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) +``` + +**Description** + +Pointer to the function used to set a predicates object to match the field whose value is within the specified range. + +This method is equivalent to **BETWEEN** in SQL statements. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| +| field | Pointer to the column name in the database table.| +| valueObject | Pointer to the [OH_VObject](_o_h___v_object.md) instance, which specifies the start and end values.| + +**Returns** + +Returns the predicates created. + +**See** + +[OH_Predicates](_o_h___predicates.md), [OH_VObject](_o_h___v_object.md). + + +### capability + + +``` +uint16_t OH_VBucket::capability +``` + +**Description** + +Number of the KV pairs in the struct. + + +### clear [1/2] + + +``` +OH_Predicates*(* OH_Predicates::clear) (OH_Predicates *predicates) +``` + +**Description** + +Pointer to the function used to clear a predicates instance. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| + +**Returns** + +Returns the cleared predicates. + +**See** + +[OH_Predicates](_o_h___predicates.md). + + +### clear [2/2] + + +``` +int(* OH_VBucket::clear) (OH_VBucket *bucket) +``` + +**Description** + +Clears an [OH_VBucket](_o_h___v_bucket.md) object. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| bucket | Pointer to the [OH_VBucket](_o_h___v_bucket.md) instance.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_VBucket](_o_h___v_bucket.md). + + +### close + + +``` +int(* OH_Cursor::close) (OH_Cursor *cursor) +``` + +**Description** + +Pointer to the function used to close a result set. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_Cursor](_o_h___cursor.md). + + +### destroyPredicates + + +``` +int(* OH_Predicates::destroyPredicates) (OH_Predicates *predicates) +``` + +**Description** + +Destroys an [OH_Predicates](_o_h___predicates.md) object and reclaims the memory occupied. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_Predicates](_o_h___predicates.md). + + +### destroyValueObject + + +``` +int(* OH_VObject::destroyValueObject) (OH_VObject *valueObject) +``` + +**Description** + +Destroys an [OH_VObject](_o_h___v_object.md) object and reclaims the memory occupied. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| valueObject | Pointer to the [OH_VObject](_o_h___v_object.md) instance.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_VObject](_o_h___v_object.md). + + +### destroyValuesBucket + + +``` +int(* OH_VBucket::destroyValuesBucket) (OH_VBucket *bucket) +``` + +**Description** + +Destroys an [OH_VBucket](_o_h___v_bucket.md) object and reclaims the memory occupied. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| bucket | Pointer to the [OH_VBucket](_o_h___v_bucket.md) instance.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_VBucket](_o_h___v_bucket.md). + + +### distinct + + +``` +OH_Predicates*(* OH_Predicates::distinct) (OH_Predicates *predicates) +``` + +**Description** + +Pointer to the function used to set a predicates object to filter out duplicate records. + +This method is equivalent to **DISTINCT** in SQL statements. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| + +**Returns** + +Returns the predicates created. + +**See** + +[OH_Predicates](_o_h___predicates.md). + + +### endWrap + + +``` +OH_Predicates*(* OH_Predicates::endWrap) (OH_Predicates *predicates) +``` + +**Description** + +Pointer to the function used to add a right parenthesis to the predicates. + +This method is equivalent to ")" in SQL statements. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| + +**Returns** + +Returns the predicates object with a right parenthesis. + +**See** + +[OH_Predicates](_o_h___predicates.md). + + +### equalTo + + +``` +OH_Predicates*(* OH_Predicates::equalTo) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) +``` + +**Description** + +Pointer to the function used to set a predicates object to match the field whose value is equal to the specified value. + +This method is equivalent to "=" in SQL statements. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| +| field | Pointer to the column name in the database table.| +| valueObject | Pointer to the [OH_VObject](_o_h___v_object.md) instance, which specifies the value to match.| + +**Returns** + +Returns the predicates created. + +**See** + +[OH_Predicates](_o_h___predicates.md), [OH_VObject](_o_h___v_object.md). + + +### getBlob + + +``` +int(* OH_Cursor::getBlob) (OH_Cursor *cursor, int32_t columnIndex, unsigned char *value, int length) +``` + +**Description** + +Pointer to the function used to obtain the value in the form of a byte array based on the specified column and the current row. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| +| columnIndex | Column index.| +| value | Pointer to the value in the form of a byte array obtained.| +| length | Length of the value, which can be obtained by **getSize()**.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_Cursor](_o_h___cursor.md). + + +### getColumnCount + + +``` +int(* OH_Cursor::getColumnCount) (OH_Cursor *cursor, int *count) +``` + +**Description** + +Pointer to the function used to obtain the number of columns in the result set. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| +| count | Pointer to the number of columns in the result set obtained.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_Cursor](_o_h___cursor.md). + + +### getColumnIndex + + +``` +int(* OH_Cursor::getColumnIndex) (OH_Cursor *cursor, const char *name, int *columnIndex) +``` + +**Description** + +Pointer to the function used to obtain the column index based on the specified column name. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| +| name | Pointer to the column name in the result set.| +| columnIndex | Pointer to the column index obtained.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_Cursor](_o_h___cursor.md). + + +### getColumnName + + +``` +int(* OH_Cursor::getColumnName) (OH_Cursor *cursor, int32_t columnIndex, char *name, int length) +``` + +**Description** + +Pointer to the function used to obtain the column name based on the specified column index. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| +| columnIndex | Column index.| +| name | Pointer to the column name obtained.| +| length | Length of a column name.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_Cursor](_o_h___cursor.md). + + +### getColumnType + + +``` +int(* OH_Cursor::getColumnType) (OH_Cursor *cursor, int32_t columnIndex, OH_ColumnType *columnType) +``` + +**Description** + +Pointer to the function used to obtain the column type based on the specified column index. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| +| columnIndex | Column index.| +| columnType | Pointer to the [OH_ColumnType](#oh_columntype) obtained.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_Cursor](_o_h___cursor.md), [OH_ColumnType](#oh_columntype). + + +### getInt64 + + +``` +int(* OH_Cursor::getInt64) (OH_Cursor *cursor, int32_t columnIndex, int64_t *value) +``` + +**Description** + +Pointer to the function used to obtain the value of the int64_t type based on the specified column and the current row. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| +| columnIndex | Column index.| +| value | Pointer to the value obtained.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_Cursor](_o_h___cursor.md). + + +### getReal + + +``` +int(* OH_Cursor::getReal) (OH_Cursor *cursor, int32_t columnIndex, double *value) +``` + +**Description** + +Pointer to the function used to obtain the value of the double type based on the specified column and the current row. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| +| columnIndex | Column index.| +| value | Pointer to the value obtained.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_Cursor](_o_h___cursor.md). + + +### getRowCount + + +``` +int(* OH_Cursor::getRowCount) (OH_Cursor *cursor, int *count) +``` + +**Description** + +Pointer to the function used to obtain the number of rows in the result set. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| +| count | Pointer to the number of columns in the result set obtained.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_Cursor](_o_h___cursor.md). + + +### getSize + + +``` +int(* OH_Cursor::getSize) (OH_Cursor *cursor, int32_t columnIndex, size_t *size) +``` + +**Description** + +Pointer to the function used to obtain information about the memory required when the column data type in the result set is **BLOB** or **TEXT**. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| +| columnIndex | Column index.| +| size | Pointer to the memory size obtained.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_Cursor](_o_h___cursor.md). + + +### getText + + +``` +int(* OH_Cursor::getText) (OH_Cursor *cursor, int32_t columnIndex, char *value, int length) +``` + +**Description** + +Pointer to the function used to obtain the value in the form of a string based on the specified column and the current row. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| +| columnIndex | Column index.| +| value | Pointer to the value in the form of a string obtained.| +| length | Length of the value, which can be obtained by **getSize()**.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_Cursor](_o_h___cursor.md). + + +### goToNextRow + + +``` +int(* OH_Cursor::goToNextRow) (OH_Cursor *cursor) +``` + +**Description** + +Pointer to the function used to go to the next row of the result set. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_Cursor](_o_h___cursor.md). + + +### greaterThan + + +``` +OH_Predicates*(* OH_Predicates::greaterThan) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) +``` + +**Description** + +Pointer to the function used to set a predicates object to match the field with value greater than the specified value. + +This method is equivalent to ">" in SQL statements. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| +| field | Pointer to the column name in the database table.| +| valueObject | Pointer to the [OH_VObject](_o_h___v_object.md) instance, which specifies the value to match.| + +**Returns** + +Returns the predicates created. + +**See** + +[OH_Predicates](_o_h___predicates.md), [OH_VObject](_o_h___v_object.md). + + +### greaterThanOrEqualTo + + +``` +OH_Predicates*(* OH_Predicates::greaterThanOrEqualTo) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) +``` + +**Description** + +Pointer to the function used to set a predicates object to match the field with value greater than or equal to the specified value. + +This method is equivalent to ">=" in SQL statements. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| +| field | Pointer to the column name in the database table.| +| valueObject | Pointer to the [OH_VObject](_o_h___v_object.md) instance, which specifies the value to match.| + +**Returns** + +Returns the predicates created. + +**See** + +[OH_Predicates](_o_h___predicates.md), [OH_VObject](_o_h___v_object.md). + + +### groupBy + + +``` +OH_Predicates*(* OH_Predicates::groupBy) (OH_Predicates *predicates, char const *const *fields, int length) +``` + +**Description** + +Pointer to the function used to set a predicates object to group rows that have the same value into summary rows. + +This method is equivalent to **GROUP BY** in the SQL statement. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| +| fields | Pointer to the names of the columns by which the records are grouped.| +| length | Length of the **fields** value.| + +**Returns** + +Returns the predicates created. + +**See** + +[OH_Predicates](_o_h___predicates.md). + + +### id [1/4] + + +``` +int64_t OH_Predicates::id +``` + +**Description** + +Unique identifier of the **OH_Predicates** struct. + + +### id [2/4] + + +``` +int64_t OH_VObject::id +``` + +**Description** + +Unique identifier of the **OH_VObject** struct. + + +### id [3/4] + + +``` +int64_t OH_VBucket::id +``` + +**Description** + +Unique identifier of the **OH_VBucket** struct. + + +### id [4/4] + + +``` +int64_t OH_Rdb_Store::id +``` + +**Description** + +Unique identifier of the **OH_Rdb_Store** struct. + + +### in + + +``` +OH_Predicates*(* OH_Predicates::in) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) +``` + +**Description** + +Pointer to the function used to set a predicates object to match the field with the value within the specified range. + +This method is equivalent to **IN** in SQL statements. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| +| field | Pointer to the column name in the database table.| +| valueObject | Pointer to the [OH_VObject](_o_h___v_object.md) instance, which specifies the value range.| + +**Returns** + +Returns the predicates created. + +**See** + +[OH_Predicates](_o_h___predicates.md), [OH_VObject](_o_h___v_object.md). + + +### isEncrypt + + +``` +bool OH_Rdb_Config::isEncrypt +``` + +**Description** + +Whether to encrypt the RDB store. + + +### isNotNull + + +``` +OH_Predicates*(* OH_Predicates::isNotNull) (OH_Predicates *predicates, const char *field) +``` + +**Description** + +Pointer to the function used to set a predicates object to match the field whose value is not null. + +This method is equivalent to **IS NOT NULL** in SQL statements. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| +| field | Pointer to the column name in the database table.| + +**Returns** + +Returns the predicates created. + +**See** + +[OH_Predicates](_o_h___predicates.md). + + +### isNull [1/2] + + +``` +int(* OH_Cursor::isNull) (OH_Cursor *cursor, int32_t columnIndex, bool *isNull) +``` + +**Description** + +Pointer to the function used to check whether the value in the specified column is null. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| +| columnIndex | Column index.| +| isNull | Pointer to the value returned. The value **true** means the value is null; the value **false** means the opposite.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_Cursor](_o_h___cursor.md). + + +### isNull [2/2] + + +``` +OH_Predicates*(* OH_Predicates::isNull) (OH_Predicates *predicates, const char *field) +``` + +**Description** + +Pointer to the function used to set a predicates object to match the field whose value is null. + +This method is equivalent to **IS NULL** in SQL statements. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| +| field | Pointer to the column name in the database table.| + +**Returns** + +Returns the predicates created. + +**See** + +[OH_Predicates](_o_h___predicates.md). + + +### lessThan + + +``` +OH_Predicates*(* OH_Predicates::lessThan) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) +``` + +**Description** + +Pointer to the function used to set a predicates object to match the field with value less than the specified value. + +This method is equivalent to "<" in SQL statements. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| +| field | Pointer to the column name in the database table.| +| valueObject | Pointer to the [OH_VObject](_o_h___v_object.md) instance, which specifies the value to match.| + +**Returns** + +Returns the predicates created. + +**See** + +[OH_Predicates](_o_h___predicates.md), [OH_VObject](_o_h___v_object.md). + + +### lessThanOrEqualTo + + +``` +OH_Predicates*(* OH_Predicates::lessThanOrEqualTo) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) +``` + +**Description** + +Pointer to the function used to set a predicates object to match the field with value less than or equal to the specified value. + +This method is equivalent to "<=" in SQL statements. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| +| field | Pointer to the column name in the database table.| +| valueObject | Pointer to the [OH_VObject](_o_h___v_object.md) instance, which specifies the value to match.| + +**Returns** + +Returns the predicates created. + +**See** + +[OH_Predicates](_o_h___predicates.md), [OH_VObject](_o_h___v_object.md). + + +### like + + +``` +OH_Predicates*(* OH_Predicates::like) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) +``` + +**Description** + +Pointer to the function used to set a predicates object to match a string that is similar to the specified value. + +This method is equivalent to **LIKE** in SQL statements. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| +| field | Pointer to the column name in the database table.| +| valueObject | Pointer to the [OH_VObject](_o_h___v_object.md) instance, which specifies the value to match.| + +**Returns** + +Returns the predicates created. + +**See** + +[OH_Predicates](_o_h___predicates.md), [OH_VObject](_o_h___v_object.md). + + +### limit + + +``` +OH_Predicates*(* OH_Predicates::limit) (OH_Predicates *predicates, unsigned int value) +``` + +**Description** + +Pointer to the function used to set a predicates object to specify the maximum number of records. + +This method is equivalent to **LIMIT** in SQL statements. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| +| value | Maximum number of data records.| + +**Returns** + +Returns the predicates created. + +**See** + +[OH_Predicates](_o_h___predicates.md). + + +### notBetween + + +``` +OH_Predicates*(* OH_Predicates::notBetween) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) +``` + +**Description** + +Pointer to the function used to set a predicates object to match the field whose value is out of the specified range. + +This method is equivalent to **NOT BETWEEN** in SQL statements. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| +| field | Pointer to the column name in the database table.| +| valueObject | Pointer to the [OH_VObject](_o_h___v_object.md) instance, which specifies the value to match.| + +**Returns** + +Returns the predicates created. + +**See** + +[OH_Predicates](_o_h___predicates.md), [OH_VObject](_o_h___v_object.md). + + +### notEqualTo + + +``` +OH_Predicates*(* OH_Predicates::notEqualTo) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) +``` + +**Description** + +Pointer to the function used to set a predicates object to match the field whose value is not equal to the specified value. + +This method is equivalent to "!=" in SQL statements. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| +| field | Pointer to the column name in the database table.| +| valueObject | Pointer to the [OH_VObject](_o_h___v_object.md) instance, which specifies the value to match.| + +**Returns** + +Returns the predicates created. + +**See** + +[OH_Predicates](_o_h___predicates.md), [OH_VObject](_o_h___v_object.md). + + +### notIn + + +``` +OH_Predicates*(* OH_Predicates::notIn) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) +``` + +**Description** + +Pointer to the function used to set a predicates object to match the field with the value out of the specified range. + +This method is equivalent to **NOT IN** in SQL statements. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| +| field | Pointer to the column name in the database table.| +| valueObject | Pointer to the [OH_VObject](_o_h___v_object.md) instance, which specifies the value range to match.| + +**Returns** + +Returns the predicates created. + +**See** + +[OH_Predicates](_o_h___predicates.md), [OH_VObject](_o_h___v_object.md). + + +### offset + + +``` +OH_Predicates*(* OH_Predicates::offset) (OH_Predicates *predicates, unsigned int rowOffset) +``` + +**Description** + +Pointer to the function used to set a predicates object to specify the start position of the returned result. + +This method is equivalent to **OFFSET** in SQL statements. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| +| rowOffset | Start position of the returned result. The value is a positive integer.| + +**Returns** + +Returns the predicates created. + +**See** + +[OH_Predicates](_o_h___predicates.md). + + +### orderBy + + +``` +OH_Predicates*(* OH_Predicates::orderBy) (OH_Predicates *predicates, const char *field, OH_OrderType type) +``` + +**Description** + +Pointer to the function used to set a predicates object to sort the values in a column in ascending or descending order. + +This method is equivalent to **ORDER BY** in the SQL statement. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| +| field | Pointer to the column name in the database table.| +| type | Sorting type [OH_OrderType](#oh_ordertype).| + +**Returns** + +Returns the predicates created. + +**See** + +[OH_Predicates](_o_h___predicates.md), [OH_OrderType](#oh_ordertype). + + +### orOperate + + +``` +OH_Predicates*(* OH_Predicates::orOperate) (OH_Predicates *predicates) +``` + +**Description** + +Pointer to the function used to add the OR operator to the predicates. + +This method is equivalent to **OR** in SQL statements. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| + +**Returns** + +Returns the predicates with the OR operator. + +**See** + +[OH_Predicates](_o_h___predicates.md). + + +### path + + +``` +const char* OH_Rdb_Config::path +``` + +**Description** + +Path of the database file. + + +### putBlob + + +``` +int(* OH_VBucket::putBlob) (OH_VBucket *bucket, const char *field, const uint8_t *value, uint32_t size) +``` + +**Description** + +Puts a const uint8_t value into the [OH_VBucket](_o_h___v_bucket.md) object in the given column. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| bucket | Pointer to the [OH_VBucket](_o_h___v_bucket.md) instance.| +| field | Pointer to the column name in the database table.| +| value | Pointer to the value to put.| +| size | Length of the value.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_VBucket](_o_h___v_bucket.md). + + +### putDouble + + +``` +int(* OH_VObject::putDouble) (OH_VObject *valueObject, double *value, uint32_t count) +``` + +**Description** + +Converts a single parameter or an array of the double type into a value of the [OH_VObject](_o_h___v_object.md) type. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| valueObject | Pointer to the [OH_VObject](_o_h___v_object.md) instance.| +| value | Pointer to the data to covert.| +| count | If **value** points to a single parameter, **count** is **1**. If **value** points to an array, **count** specifies the length of the array.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_VObject](_o_h___v_object.md). + + +### putInt64 [1/2] + + +``` +int(* OH_VBucket::putInt64) (OH_VBucket *bucket, const char *field, int64_t value) +``` + +**Description** + +Puts an int64_t value into the [OH_VBucket](_o_h___v_bucket.md) object in the given column. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| bucket | Pointer to the [OH_VBucket](_o_h___v_bucket.md) instance.| +| field | Pointer to the column name in the database table.| +| value | Value to put.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_VBucket](_o_h___v_bucket.md). + + +### putInt64 [2/2] + + +``` +int(* OH_VObject::putInt64) (OH_VObject *valueObject, int64_t *value, uint32_t count) +``` + +**Description** + +Converts a single parameter or an array of the int64 type into a value of the [OH_VObject](_o_h___v_object.md) type. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| valueObject | Pointer to the [OH_VObject](_o_h___v_object.md) instance.| +| value | Pointer to the data to covert.| +| count | If **value** points to a single parameter, **count** is **1**. If **value** points to an array, **count** specifies the length of the array.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_VObject](_o_h___v_object.md). + + +### putNull + + +``` +int(* OH_VBucket::putNull) (OH_VBucket *bucket, const char *field) +``` + +**Description** + +Puts a null value into the [OH_VBucket](_o_h___v_bucket.md) object in the given column. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| bucket | Pointer to the [OH_VBucket](_o_h___v_bucket.md) instance.| +| field | Pointer to the column name in the database table.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_VBucket](_o_h___v_bucket.md). + + +### putReal + + +``` +int(* OH_VBucket::putReal) (OH_VBucket *bucket, const char *field, double value) +``` + +**Description** + +Puts the double value into the {OH_VBucket} object of the given column name. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| bucket | Pointer to the [OH_VBucket](_o_h___v_bucket.md) instance.| +| field | Pointer to the column name in the database table.| +| value | Value to put.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_VBucket](_o_h___v_bucket.md). + + +### putText [1/2] + + +``` +int(* OH_VBucket::putText) (OH_VBucket *bucket, const char *field, const char *value) +``` + +**Description** + +Puts a char value into the [OH_VBucket](_o_h___v_bucket.md) object in the given column. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| bucket | Pointer to the [OH_VBucket](_o_h___v_bucket.md) instance.| +| field | Pointer to the column name in the database table.| +| value | Pointer to the char value to put.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_VBucket](_o_h___v_bucket.md). + + +### putText [2/2] + + +``` +int(* OH_VObject::putText) (OH_VObject *valueObject, const char *value) +``` + +**Description** + +Converts a character array of the char type to a value of the [OH_VObject](_o_h___v_object.md) type. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| valueObject | Pointer to the [OH_VObject](_o_h___v_object.md) instance.| +| value | Pointer to the character array to convert.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_VObject](_o_h___v_object.md). + + +### putTexts + + +``` +int(* OH_VObject::putTexts) (OH_VObject *valueObject, const char **value, uint32_t count) +``` + +**Description** + +Converts a string array of the char type to a value of the [OH_VObject](_o_h___v_object.md) type. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| valueObject | Pointer to the [OH_VObject](_o_h___v_object.md) instance.| +| value | Pointer to the string array to convert.| +| count | Length of the string array to convert.| + +**Returns** + +Returns **RDB_OK** is the operation is successful; returns an error code otherwise. + +**See** + +[OH_VObject](_o_h___v_object.md). + + +### securityLevel + + +``` +enum OH_Rdb_SecurityLevel OH_Rdb_Config::securityLevel +``` + +**Description** + +Set the RDB store security level [OH_Rdb_SecurityLevel](#oh_rdb_securitylevel). diff --git a/en/application-dev/reference/native-apis/context_8h.md b/en/application-dev/reference/native-apis/context_8h.md index f73e70d24871b35a026b39befa08fbebeee5380a..743fdbc9dbfe3d3d4b3b464b0301999631980790 100644 --- a/en/application-dev/reference/native-apis/context_8h.md +++ b/en/application-dev/reference/native-apis/context_8h.md @@ -5,10 +5,11 @@ Provides **Context** APIs for configuring runtime information. -**Since:** +**Since** + 9 -**Related Modules:** +**Related Modules** [MindSpore](_mind_spore.md) @@ -18,35 +19,48 @@ Provides **Context** APIs for configuring runtime information. ### Types -| Name | Description | +| Name| Description| | -------- | -------- | -| [OH_AI_ContextHandle](_mind_spore.md#oh_ai_contexthandle) | Defines the pointer to the MindSpore context. | -| [OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) | Defines the pointer to the MindSpore device information. | +| [OH_AI_ContextHandle](_mind_spore.md#oh_ai_contexthandle) | Defines the pointer to the MindSpore context. | +| [OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) | Defines the pointer to the MindSpore device information.| ### Functions -| Name | Description | +| Name| Description| | -------- | -------- | -| [OH_AI_ContextCreate](_mind_spore.md#oh_ai_contextcreate) () | Creates a context object. | -| [OH_AI_ContextDestroy](_mind_spore.md#oh_ai_contextdestroy) ([OH_AI_ContextHandle](_mind_spore.md#oh_ai_contexthandle) \*context) | Destroys a context object. | -| [OH_AI_ContextSetThreadNum](_mind_spore.md#oh_ai_contextsetthreadnum) ([OH_AI_ContextHandle](_mind_spore.md#oh_ai_contexthandle) context, int32_t thread_num) | Sets the number of runtime threads. | -| [OH_AI_ContextGetThreadNum](_mind_spore.md#oh_ai_contextgetthreadnum) (const [OH_AI_ContextHandle](_mind_spore.md#oh_ai_contexthandle) context) | Obtains the number of threads. | -| [OH_AI_ContextSetThreadAffinityMode](_mind_spore.md#oh_ai_contextsetthreadaffinitymode) ([OH_AI_ContextHandle](_mind_spore.md#oh_ai_contexthandle) context, int mode) | Sets the affinity mode for binding runtime threads to CPU cores, which are categorized into little cores and big cores depending on the CPU frequency. | -| [OH_AI_ContextGetThreadAffinityMode](_mind_spore.md#oh_ai_contextgetthreadaffinitymode) (const [OH_AI_ContextHandle](_mind_spore.md#oh_ai_contexthandle) context) | Obtains the affinity mode for binding runtime threads to CPU cores. | -| [OH_AI_ContextSetThreadAffinityCoreList](_mind_spore.md#oh_ai_contextsetthreadaffinitycorelist) ([OH_AI_ContextHandle](_mind_spore.md#oh_ai_contexthandle) context, const int32_t \*core_list, size_t core_num) | Sets the list of CPU cores bound to a runtime thread. | -| [OH_AI_ContextGetThreadAffinityCoreList](_mind_spore.md#oh_ai_contextgetthreadaffinitycorelist) (const [OH_AI_ContextHandle](_mind_spore.md#oh_ai_contexthandle) context, size_t \*core_num) | Obtains the list of bound CPU cores. | -| [OH_AI_ContextSetEnableParallel](_mind_spore.md#oh_ai_contextsetenableparallel) ([OH_AI_ContextHandle](_mind_spore.md#oh_ai_contexthandle) context, bool is_parallel) | Sets whether to enable parallelism between operators. | -| [OH_AI_ContextGetEnableParallel](_mind_spore.md#oh_ai_contextgetenableparallel) (const [OH_AI_ContextHandle](_mind_spore.md#oh_ai_contexthandle) context) | Checks whether parallelism between operators is supported. | -| [OH_AI_ContextAddDeviceInfo](_mind_spore.md#oh_ai_contextadddeviceinfo) ([OH_AI_ContextHandle](_mind_spore.md#oh_ai_contexthandle) context, [OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info) | Adds information about a running device. | -| [OH_AI_DeviceInfoCreate](_mind_spore.md#oh_ai_deviceinfocreate) ([OH_AI_DeviceType](_mind_spore.md#oh_ai_devicetype) device_type) | Creates a device information object. | -| [OH_AI_DeviceInfoDestroy](_mind_spore.md#oh_ai_deviceinfodestroy) ([OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) \*device_info) | Destroys a device information instance. | -| [OH_AI_DeviceInfoSetProvider](_mind_spore.md#oh_ai_deviceinfosetprovider) ([OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info, const char \*provider) | Sets the name of a provider. | -| [OH_AI_DeviceInfoGetProvider](_mind_spore.md#oh_ai_deviceinfogetprovider) (const [OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info) | Obtains the provider name. | -| [OH_AI_DeviceInfoSetProviderDevice](_mind_spore.md#oh_ai_deviceinfosetproviderdevice) ([OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info, const char \*device) | Sets the name of a provider device. | -| [OH_AI_DeviceInfoGetProviderDevice](_mind_spore.md#oh_ai_deviceinfogetproviderdevice) (const [OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info) | Obtains the name of a provider device. | -| [OH_AI_DeviceInfoGetDeviceType](_mind_spore.md#oh_ai_deviceinfogetdevicetype) (const [OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info) | Obtains the type of a provider device. | -| [OH_AI_DeviceInfoSetEnableFP16](_mind_spore.md#oh_ai_deviceinfosetenablefp16) ([OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info, bool is_fp16) | Sets whether to enable float16 inference. This function is available only for CPU/GPU devices. | -| [OH_AI_DeviceInfoGetEnableFP16](_mind_spore.md#oh_ai_deviceinfogetenablefp16) (const [OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info) | Checks whether float16 inference is enabled. This function is available only for CPU/GPU devices. | -| [OH_AI_DeviceInfoSetFrequency](_mind_spore.md#oh_ai_deviceinfosetfrequency) ([OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info, int frequency) | Sets the NPU frequency type. This function is available only for NPU devices. | -| [OH_AI_DeviceInfoGetFrequency](_mind_spore.md#oh_ai_deviceinfogetfrequency) (const [OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info) | Obtains the NPU frequency type. This function is available only for NPU devices. | +| [OH_AI_ContextCreate](_mind_spore.md#oh_ai_contextcreate) () | Creates a context object.| +| [OH_AI_ContextDestroy](_mind_spore.md#oh_ai_contextdestroy) ([OH_AI_ContextHandle](_mind_spore.md#oh_ai_contexthandle) \*context) | Destroys a context object.| +| [OH_AI_ContextSetThreadNum](_mind_spore.md#oh_ai_contextsetthreadnum) ([OH_AI_ContextHandle](_mind_spore.md#oh_ai_contexthandle) context, int32_t thread_num) | Sets the number of runtime threads.| +| [OH_AI_ContextGetThreadNum](_mind_spore.md#oh_ai_contextgetthreadnum) (const [OH_AI_ContextHandle](_mind_spore.md#oh_ai_contexthandle) context) | Obtains the number of threads.| +| [OH_AI_ContextSetThreadAffinityMode](_mind_spore.md#oh_ai_contextsetthreadaffinitymode) ([OH_AI_ContextHandle](_mind_spore.md#oh_ai_contexthandle) context, int mode) | Sets the affinity mode for binding runtime threads to CPU cores, which are classified into large, medium, and small cores based on the CPU frequency. You only need to bind the large or medium cores, but not small cores.| +| [OH_AI_ContextGetThreadAffinityMode](_mind_spore.md#oh_ai_contextgetthreadaffinitymode) (const [OH_AI_ContextHandle](_mind_spore.md#oh_ai_contexthandle) context) | Obtains the affinity mode for binding runtime threads to CPU cores.| +| [OH_AI_ContextSetThreadAffinityCoreList](_mind_spore.md#oh_ai_contextsetthreadaffinitycorelist) ([OH_AI_ContextHandle](_mind_spore.md#oh_ai_contexthandle) context, const int32_t \*core_list, size_t core_num) | Sets the list of CPU cores bound to a runtime thread.| +| [OH_AI_ContextGetThreadAffinityCoreList](_mind_spore.md#oh_ai_contextgetthreadaffinitycorelist) (const [OH_AI_ContextHandle](_mind_spore.md#oh_ai_contexthandle) context, size_t \*core_num) | Obtains the list of bound CPU cores.| +| [OH_AI_ContextSetEnableParallel](_mind_spore.md#oh_ai_contextsetenableparallel) ([OH_AI_ContextHandle](_mind_spore.md#oh_ai_contexthandle) context, bool is_parallel) | Sets whether to enable parallelism between operators. The setting is ineffective because the feature of this API is not yet available.| +| [OH_AI_ContextGetEnableParallel](_mind_spore.md#oh_ai_contextgetenableparallel) (const [OH_AI_ContextHandle](_mind_spore.md#oh_ai_contexthandle) context) | Checks whether parallelism between operators is supported.| +| [OH_AI_ContextAddDeviceInfo](_mind_spore.md#oh_ai_contextadddeviceinfo) ([OH_AI_ContextHandle](_mind_spore.md#oh_ai_contexthandle) context, [OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info) | Attaches the custom device information to the inference context.| +| [OH_AI_DeviceInfoCreate](_mind_spore.md#oh_ai_deviceinfocreate) ([OH_AI_DeviceType](_mind_spore.md#oh_ai_devicetype) device_type) | Creates a device information object.| +| [OH_AI_DeviceInfoDestroy](_mind_spore.md#oh_ai_deviceinfodestroy) ([OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) \*device_info) | Destroys a device information object. Note: After the device information instance is added to the context, the caller does not need to destroy it manually.| +| [OH_AI_DeviceInfoSetProvider](_mind_spore.md#oh_ai_deviceinfosetprovider) ([OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info, const char \*provider) | Sets the provider name.| +| [OH_AI_DeviceInfoGetProvider](_mind_spore.md#oh_ai_deviceinfogetprovider) (const [OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info) | Obtains the provider name.| +| [OH_AI_DeviceInfoSetProviderDevice](_mind_spore.md#oh_ai_deviceinfosetproviderdevice) ([OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info, const char \*device) | Sets the name of a provider device.| +| [OH_AI_DeviceInfoGetProviderDevice](_mind_spore.md#oh_ai_deviceinfogetproviderdevice) (const [OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info) | Obtains the name of a provider device.| +| [OH_AI_DeviceInfoGetDeviceType](_mind_spore.md#oh_ai_deviceinfogetdevicetype) (const [OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info) | Obtains the device type.| +| [OH_AI_DeviceInfoSetEnableFP16](_mind_spore.md#oh_ai_deviceinfosetenablefp16) ([OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info, bool is_fp16) | Sets whether to enable float16 inference. This function is available only for CPU and GPU devices.| +| [OH_AI_DeviceInfoGetEnableFP16](_mind_spore.md#oh_ai_deviceinfogetenablefp16) (const [OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info) | Checks whether float16 inference is enabled. This function is available only for CPU and GPU devices.| +| [OH_AI_DeviceInfoSetFrequency](_mind_spore.md#oh_ai_deviceinfosetfrequency) ([OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info, int frequency) | Sets the NPU frequency type. This function is available only for NPU devices.| +| [OH_AI_DeviceInfoGetFrequency](_mind_spore.md#oh_ai_deviceinfogetfrequency) (const [OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info) | Obtains the NPU frequency type. This function is available only for NPU devices.| +| [OH_AI_GetAllNNRTDeviceDescs](_mind_spore.md#oh_ai_getallnnrtdevicedescs) (size_t \*num) | Obtains the descriptions of all NNRt devices in the system.| +| [OH_AI_DestroyAllNNRTDeviceDescs](_mind_spore.md#oh_ai_destroyallnnrtdevicedescs) ([NNRTDeviceDesc](_mind_spore.md#nnrtdevicedesc) \*\*desc) | Destroys the array of NNRT descriptions obtained by [OH_AI_GetAllNNRTDeviceDescs](_mind_spore.md#oh_ai_getallnnrtdevicedescs).| +| [OH_AI_GetDeviceIdFromNNRTDeviceDesc](_mind_spore.md#oh_ai_getdeviceidfromnnrtdevicedesc) (const [NNRTDeviceDesc](_mind_spore.md#nnrtdevicedesc) \*desc) | Obtains the NNRt device ID from the specified NNRt device description. Note that this ID is valid only for NNRt devices.| +| [OH_AI_GetNameFromNNRTDeviceDesc](_mind_spore.md#oh_ai_getnamefromnnrtdevicedesc) (const [NNRTDeviceDesc](_mind_spore.md#nnrtdevicedesc) \*desc) | Obtains the NNRt device name from the specified NNRt device description.| +| [OH_AI_GetTypeFromNNRTDeviceDesc](_mind_spore.md#oh_ai_gettypefromnnrtdevicedesc) (const [NNRTDeviceDesc](_mind_spore.md#nnrtdevicedesc) \*desc) | Obtains the NNRt device type from the specified NNRt device description.| +| [OH_AI_CreateNNRTDeviceInfoByName](_mind_spore.md#oh_ai_creatennrtdeviceinfobyname) (const char \*name) | Searches for the NNRt device with the specified name and creates the NNRt device information based on the information about the first found NNRt device.| +| [OH_AI_CreateNNRTDeviceInfoByType](_mind_spore.md#oh_ai_creatennrtdeviceinfobytype) ([OH_AI_NNRTDeviceType](_mind_spore.md#oh_ai_nnrtdevicetype) type) | Searches for the NNRt device with the specified type and creates the NNRt device information based on the information about the first found NNRt device.| +| [OH_AI_DeviceInfoSetDeviceId](_mind_spore.md#oh_ai_deviceinfosetdeviceid) ([OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info, size_t device_id) | Sets the ID of an NNRt device. This API is available only for NNRt devices.| +| [OH_AI_DeviceInfoGetDeviceId](_mind_spore.md#oh_ai_deviceinfogetdeviceid) (const [OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info) | Obtains the ID of an NNRt device. This API is available only for NNRt devices.| +| [OH_AI_DeviceInfoSetPerformanceMode](_mind_spore.md#oh_ai_deviceinfosetperformancemode) ([OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info, [OH_AI_PerformanceMode](_mind_spore.md#oh_ai_performancemode) mode) | Sets the performance mode of an NNRt device. This API is available only for NNRt devices.| +| [OH_AI_DeviceInfoGetPerformanceMode](_mind_spore.md#oh_ai_deviceinfogetperformancemode) (const [OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info) | Obtains the performance mode of an NNRt device. This API is available only for NNRt devices.| +| [OH_AI_DeviceInfoSetPriority](_mind_spore.md#oh_ai_deviceinfosetpriority) ([OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info, [OH_AI_Priority](_mind_spore.md#oh_ai_priority) priority) | Sets the priority of an NNRT task. This API is available only for NNRt devices.| +| [OH_AI_DeviceInfoGetPriority](_mind_spore.md#oh_ai_deviceinfogetpriority) (const [OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info) | Obtains the priority of an NNRT task. This API is available only for NNRt devices.| diff --git a/en/application-dev/reference/native-apis/oh__cursor_8h.md b/en/application-dev/reference/native-apis/oh__cursor_8h.md new file mode 100644 index 0000000000000000000000000000000000000000..d51368c059814c2f7e4f0daa34e7cc0e6484254b --- /dev/null +++ b/en/application-dev/reference/native-apis/oh__cursor_8h.md @@ -0,0 +1,40 @@ +# oh_cursor.h + + +## Overview + +Provides APIs to access the result set obtained by querying the RDB store. + +A result set is a set of results returned by **query()**. + +**Since** + +10 + +**Related Modules** + +[RDB](_r_d_b.md) + + +## Summary + + +### Structs + +| Name| Description| +| -------- | -------- | +| [OH_Cursor](_o_h___cursor.md) | Defines a result set.| + + +### Types + +| Name| Description| +| -------- | -------- | +| [OH_Cursor](_r_d_b.md#oh_cursor) | Indicates a result set.| + + +### Enums + +| Name| Description| +| -------- | -------- | +| [OH_ColumnType](_r_d_b.md#oh_columntype) {
TYPE_NULL = 0, TYPE_INT64, TYPE_REAL, TYPE_TEXT,
TYPE_BLOB
} | Enumerates the field types in an RDB store.| diff --git a/en/application-dev/reference/native-apis/oh__predicates_8h.md b/en/application-dev/reference/native-apis/oh__predicates_8h.md new file mode 100644 index 0000000000000000000000000000000000000000..7da0125f074e26e2a21e3d5d16a8e10dc15a48ec --- /dev/null +++ b/en/application-dev/reference/native-apis/oh__predicates_8h.md @@ -0,0 +1,38 @@ +# oh_predicates.h + + +## Overview + +Defines the predicates for RDB stores. + +**Since** + +10 + +**Related Modules** + +[RDB](_r_d_b.md) + + +## Summary + + +### Structs + +| Name| Description| +| -------- | -------- | +| [OH_Predicates](_o_h___predicates.md) | Defines a **predicates** object. | + + +### Types + +| Name| Description| +| -------- | -------- | +| [OH_Predicates](_r_d_b.md#oh_predicates) | Indicates a **predicates** object. | + + +### Enums + +| Name| Description| +| -------- | -------- | +| [OH_OrderType](_r_d_b.md#oh_ordertype) { ASC = 0, DESC = 1 } | Enumerates the sorting types.| diff --git a/en/application-dev/reference/native-apis/oh__value__object_8h.md b/en/application-dev/reference/native-apis/oh__value__object_8h.md new file mode 100644 index 0000000000000000000000000000000000000000..26e733a794d1b18de4b3787129763662da086468 --- /dev/null +++ b/en/application-dev/reference/native-apis/oh__value__object_8h.md @@ -0,0 +1,32 @@ +# oh_value_object.h + + +## Overview + +Provides type conversion methods. + +**Since** + +10 + +**Related Modules** + +[RDB](_r_d_b.md) + + +## Summary + + +### Structs + +| Name| Description| +| -------- | -------- | +| [OH_VObject](_o_h___v_object.md) | Defines the allowed data field types.| + + +### Types + +| Name| Description| +| -------- | -------- | +| [OH_VObject](_r_d_b.md#oh_vobject) | Indicates the allowed data field types. | + diff --git a/en/application-dev/reference/native-apis/oh__values__bucket_8h.md b/en/application-dev/reference/native-apis/oh__values__bucket_8h.md new file mode 100644 index 0000000000000000000000000000000000000000..e6b7fc7a03d69d5099aaf1e03c90779c0ac2d7a6 --- /dev/null +++ b/en/application-dev/reference/native-apis/oh__values__bucket_8h.md @@ -0,0 +1,32 @@ +# oh_values_bucket.h + + +## Overview + +Defines the types of the key and value in a key-value (KV) pair. + +**Since** + +10 + +**Related Modules** + +[RDB](_r_d_b.md) + + +## Summary + + +### Structs + +| Name| Description| +| -------- | -------- | +| [OH_VBucket](_o_h___v_bucket.md) | Defines the types of the key and value in a KV pair.| + + +### Types + +| Name| Description| +| -------- | -------- | +| [OH_VBucket](_r_d_b.md#oh_vbucket) | Indicates the types of the key and value in a KV pair. | + diff --git a/en/application-dev/reference/native-apis/relational__store_8h.md b/en/application-dev/reference/native-apis/relational__store_8h.md new file mode 100644 index 0000000000000000000000000000000000000000..6336866e5364f0294bd9c0a678d7cfe02e15d283 --- /dev/null +++ b/en/application-dev/reference/native-apis/relational__store_8h.md @@ -0,0 +1,57 @@ +# relation_store.h + + +## Overview + +Provides APIs to manage a relational database (RDB) store. + +**Since** + +10 + +**Related Modules** + +[RDB](_r_d_b.md) + + +## Summary + + +### Structs + +| Name| Description| +| -------- | -------- | +| [OH_Rdb_Config](_o_h___rdb___config.md) | Defines the RDB store configuration.| +| [OH_Rdb_Store](_o_h___rdb___store.md) | Defines the RDB store type.| + + +### Enums + +| Name| Description| +| -------- | -------- | +| [OH_Rdb_SecurityLevel](_r_d_b.md#oh_rdb_securitylevel) { S1 = 1, S2, S3, S4 } | Enumerates the RDB store security levels.| + + +### Functions + +| Name| Description| +| -------- | -------- | +| [OH_Rdb_CreateValueObject](_r_d_b.md#oh_rdb_createvalueobject) (void) | Creates an [OH_VObject](_o_h___v_object.md) instance.| +| [OH_Rdb_CreateValuesBucket](_r_d_b.md#oh_rdb_createvaluesbucket) (void) | Creates an [OH_VBucket](_o_h___v_bucket.md) instance.| +| [OH_Rdb_CreatePredicates](_r_d_b.md#oh_rdb_createpredicates) (const char \*table) | Creates an [OH_Predicates](_o_h___predicates.md) instance.| +| [OH_Rdb_GetOrOpen](_r_d_b.md#oh_rdb_getoropen) (const [OH_Rdb_Config](_o_h___rdb___config.md) \*config, int \*errCode) | Obtains an [OH_Rdb_Store](_o_h___rdb___store.md) instance for RDB store operations.| +| [OH_Rdb_CloseStore](_r_d_b.md#oh_rdb_closestore) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store) | Destroys an [OH_Rdb_Store](_o_h___rdb___store.md) object and reclaims the memory occupied by the object.| +| [OH_Rdb_DeleteStore](_r_d_b.md#oh_rdb_deletestore) (const char \*path) | Deletes an RDB store with the specified database file configuration.| +| [OH_Rdb_Insert](_r_d_b.md#oh_rdb_insert) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*table, [OH_VBucket](_o_h___v_bucket.md) \*valuesBucket) | Inserts a row of data into a table.| +| [OH_Rdb_Update](_r_d_b.md#oh_rdb_update) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_VBucket](_o_h___v_bucket.md) \*valuesBucket, [OH_Predicates](_o_h___predicates.md) \*predicates) | Updates data in an RDB store based on specified conditions.| +| [OH_Rdb_Delete](_r_d_b.md#oh_rdb_delete) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_Predicates](_o_h___predicates.md) \*predicates) | Deletes data from an RDB store based on specified conditions.| +| [OH_Rdb_Query](_r_d_b.md#oh_rdb_query) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_Predicates](_o_h___predicates.md) \*predicates, const char \*const \*columnNames, int length) | Queries data in an RDB store based on specified conditions.| +| [OH_Rdb_Execute](_r_d_b.md#oh_rdb_execute) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*sql) | Executes the SQL statement that returns no value.| +| [OH_Rdb_ExecuteQuery](_r_d_b.md#oh_rdb_executequery) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*sql) | Queries data in an RDB store based on the SQL statements executed.| +| [OH_Rdb_BeginTransaction](_r_d_b.md#oh_rdb_begintransaction) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store) | Starts the transaction before executing the SQL statements.| +| [OH_Rdb_RollBack](_r_d_b.md#oh_rdb_rollback) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store) | Rolls back the SQL statements executed. | +| [OH_Rdb_Commit](_r_d_b.md#oh_rdb_commit) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store) | Commits the executed SQL statements.| +| [OH_Rdb_Backup](_r_d_b.md#oh_rdb_backup) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*databasePath) | Backs up the RDB store in the specified path.| +| [OH_Rdb_Restore](_r_d_b.md#oh_rdb_restore) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*databasePath) | Restores an RDB store from the specified database backup file.| +| [OH_Rdb_GetVersion](_r_d_b.md#oh_rdb_getversion) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, int \*version) | Obtains the RDB store version.| +| [OH_Rdb_SetVersion](_r_d_b.md#oh_rdb_setversion) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, int version) | Sets the RDB store version.| diff --git a/en/application-dev/reference/native-apis/relational__store__error__code_8h.md b/en/application-dev/reference/native-apis/relational__store__error__code_8h.md new file mode 100644 index 0000000000000000000000000000000000000000..8b1cae8744922650a10d9632e107c16b7fb644d8 --- /dev/null +++ b/en/application-dev/reference/native-apis/relational__store__error__code_8h.md @@ -0,0 +1,24 @@ +# relation_error_code.h + + +## Overview + +Declares the error codes used for relational database (RDB) stores. + +**Since** + +10 + +**Related Modules** + +[RDB](_r_d_b.md) + + +## Summary + + +### Enums + +| Name| Description| +| -------- | -------- | +| [OH_Rdb_ErrCode](_r_d_b.md#oh_rdb_errcode) { RDB_ERR_INVALID_ARGS = -2, RDB_ERR = -1, RDB_ERR_OK = 0 } | Enumerates the RDB store error codes. | diff --git a/en/application-dev/reference/syscap-list.md b/en/application-dev/reference/syscap-list.md index f550259f41ac46bd6841083f87c412ba4e6c9a0f..bf294b95d9b536f5a71c41618896c26b893ab2fe 100644 --- a/en/application-dev/reference/syscap-list.md +++ b/en/application-dev/reference/syscap-list.md @@ -359,6 +359,14 @@ Power management display | ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | | Yes | No | Yes | Yes | No | Yes | No | No | +## SystemCapability.PowerManager.DisplayPowerManager.Lite + +Lite device capabilities of the system power management display + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | No | Yes | No | No | + ## SystemCapability.PowerManager.ThermalManager Temperature control diff --git a/en/application-dev/security/cryptoFramework-guidelines.md b/en/application-dev/security/cryptoFramework-guidelines.md index 5da4bc32d6ecb1951d067da0cd4369569e4d80d4..bea49347b31a43d966d671b0bbfd10973f51d19d 100644 --- a/en/application-dev/security/cryptoFramework-guidelines.md +++ b/en/application-dev/security/cryptoFramework-guidelines.md @@ -4,27 +4,30 @@ > > This guide applies to JS development using OpenHarmony API version 9 and SDK version 3.2.7 or later. -## Generating and Converting a Key +## Key Generation and Conversion -**When to Use** +### When to Use Typical key generation operations involve the following: -1. Randomly create a key instance for subsequent encryption and decryption. -2. Convert external or stored binary data into a key instance for subsequent encryption and decryption. -3. Obtain the binary data of a key for storage or transmission. -> **NOTE**
The key instance can be a symmetric key instance (**SymKey**) or an asymmetric key pair instance (**KeyPair**). The **KeyPair** instance consists a public key (**PubKey**) and a private key (**PriKey**). For details about the relationship between keys, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). +1. Randomly create a key object for subsequent encryption and decryption. +2. Create a key object based on the specified key parameters for subsequent encryption and decryption. +3. Convert external or internal binary data into a key object for subsequent encryption and decryption. +4. Obtain the binary data of a key object for storage or transmission. +5. Obtain the parameter properties of an asymmetric key object for storage or transmission. +> **NOTE** +> +> The key object can be a symmetric key object (**SymKey**) or an asymmetric key pair object (**KeyPair**). The **KeyPair** object consists a public key (**PubKey**) and a private key (**PriKey**). For details about the relationship between keys, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). -**Available APIs** - -For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). +### Available APIs -The table below describes the APIs used in this guide. +The following table describes the APIs used in typical key generation operations. For more information about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). |Instance|API|Description| |---|---|---| -|cryptoFramework|createAsyKeyGenerator(algName : string) : AsyKeyGenerator|Creates an **AsyKeyGenerator** instance.| +|cryptoFramework|createAsyKeyGenerator(algName : string) : AsyKeyGenerator|Creates an **AsyKeyGenerator** instance based on the asymmetric key pair specifications specified by **algName**.| +|cryptoFramework|createAsyKeyGeneratorBySpec(asyKeySpec: AsyKeySpec): AsyKeyGeneratorBySpec;|Creates an **AsyKeyGenerator** instance based on the asymmetric key specifications specified by the key parameter.| |cryptoFramework|createSymKeyGenerator(algName : string) : SymKeyGenerator|Creates a **SymKeyGenerator** instance.| |AsyKeyGenerator|generateKeyPair(callback : AsyncCallback\) : void|Generates an asymmetric key pair randomly. This API uses an asynchronous callback to return the result.| |AsyKeyGenerator|generateKeyPair() : Promise\|Generates an asymmetric key pair randomly. This API uses a promise to return the result.| @@ -36,17 +39,17 @@ The table below describes the APIs used in this guide. | SymKeyGenerator |convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\| Converts binary data into a symmetric key. This API uses a promise to return the result.| | Key | getEncoded() : DataBlob; | Obtains the binary data of a key. (The child class instances of **Key** include **SymKey**, **PubKey**, and **PriKey**.)| -**How to Develop** +### Randomly Generating an RSA Key Pair and Obtaining the Binary Data -Example 1: Randomly generate an asymmetric key pair and obtain its binary data. +Randomly generate an asymmetric key pair and obtain its binary data. 1. Create an **AsyKeyGenerator** instance. 2. Randomly generate an asymmetric key pair using **AsyKeyGenerator**. -3. Obtain binary data of the key pair generated. +3. Obtain the binary data of the key pair generated. -The following sample code demonstrates how to randomly generate an RSA key (1024 bits and two primes) using promise-based APIs. +Example: Randomly generate an RSA key (1024 bits and two primes) in promise mode. -```javascript +```js import cryptoFramework from '@ohos.security.cryptoFramework'; function generateAsyKey() { @@ -55,27 +58,28 @@ function generateAsyKey() { // Use the key generator to randomly generate an asymmetric key pair. let keyGenPromise = rsaGenerator.generateKeyPair(); keyGenPromise.then( keyPair => { - globalKeyPair = keyPair; - let pubKey = globalKeyPair.pubKey; - let priKey = globalKeyPair.priKey; + let pubKey = keyPair.pubKey; + let priKey = keyPair.priKey; // Obtain the binary data of the asymmetric key pair. - pkBlob = pubKey.getEncoded(); - skBlob = priKey.getEncoded(); + let pkBlob = pubKey.getEncoded(); + let skBlob = priKey.getEncoded(); AlertDialog.show({ message : "pk bin data" + pkBlob.data} ); AlertDialog.show({ message : "sk bin data" + skBlob.data} ); }) } ``` -Example 2: Randomly generate a symmetric key and obtain its binary data. +### Randomly Generating an AES Key and Obtaining the Binary Data + +Randomly generate a symmetric key and obtain its binary data. 1. Create a **SymKeyGenerator** instance. -2. Randomly generate a symmetric key using **SymKeyGenerator**. -3. Obtain binary data of the key generated. +2. Randomly generate a symmetric key using **SymKeyGenerator**. +3. Obtain the binary data of the key generated. -The following example demonstrates how to randomly generate a 256-bit AES key using promise-based APIs. +Example: Randomly generate an AES key (256 bits) in promise mode. -```javascript +```js import cryptoFramework from '@ohos.security.cryptoFramework'; // Output the byte streams in hexadecimal format. @@ -98,12 +102,14 @@ function testGenerateAesKey() { } ``` -Example 3: Generate an asymmetric key pair from the binary RSA key data. +### Converting Binary Data into an RSA Key Pair + +Generate an RSA asymmetric key pair from the binary data. 1. Obtain the binary data of the RSA public or private key. The public key must comply with the ASN.1 syntax, X.509 specifications, and DER encoding format. The private key must comply with the ASN.1 syntax, PKCS #8 specifications, and DER encoding format. -2. Create an **AsyKeyGenerator** instance and call **convertKey()** to convert the key binary data (data of the private or public key, or both) into a **KeyPair** instance. +2. Create an **AsyKeyGenerator** instance, and use **convertKey()** to convert the key binary data (data of the private or public key, or both) into a **KeyPair** instance. -```javascript +```js import cryptoFramework from '@ohos.security.cryptoFramework'; function convertAsyKey() { @@ -121,15 +127,17 @@ function convertAsyKey() { > **NOTE** > -> The public key material to be converted in **convertKey()** must be in the DER format complying with X.509 specifications, and the private key material must be in the DER format complying with PKCS #8 specifications. +> The public key binary data to be converted by **convertKey()** must be in the DER format complying with X.509 specifications, and the private key binary data must be in the DER format complying with PKCS #8 specifications. + +### Converting Binary Data into an ECC Key Pair -Example 4: Generate an asymmetric key pair from the binary ECC key data. +Generate an ECC asymmetric key pair from the binary data. 1. Obtain the ECC binary key data and encapsulate it into a **DataBlob** instance. -2. Call **convertKey()** to convert the key binary data (data of the private or public key, or both) into a **KeyPair** instance. +2. Use **convertKey()** to convert the binary data (data of the private or public key, or both) into a **KeyPair** instance. -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; function convertEccAsyKey() { let pubKeyArray = new Uint8Array([48,89,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,3,66,0,4,83,96,142,9,86,214,126,106,247,233,92,125,4,128,138,105,246,162,215,71,81,58,202,121,26,105,211,55,130,45,236,143,55,16,248,75,167,160,167,106,2,152,243,44,68,66,0,167,99,92,235,215,159,239,28,106,124,171,34,145,124,174,57,92]); @@ -146,15 +154,17 @@ function convertEccAsyKey() { } ``` -Example 5: Generate a symmetric key from binary data. +### Converting Binary Data into a 3DES Key + +Generate a symmetric key from the binary data. 1. Create a **SymKeyGenerator** instance. -2. Generate a symmetric key from the binary data passed in. -3. Obtain binary data of the key generated. +2. Convert the binary data into a **SymKey** instance. +3. Obtain the binary data of the key instance generated. -The following example demonstrates how to generate a 3DES key (192 bits only) using callback-based APIs. +Example: Generate a 3DES key (192 bits only) in callback mode. -```javascript +```js import cryptoFramework from '@ohos.security.cryptoFramework'; // Output the byte streams in hexadecimal format. @@ -189,48 +199,259 @@ function testConvertAesKey() { let encodedKey = key.getEncoded(); // Obtain the binary data of the symmetric key and output a 192-bit byte stream. console.info('key getEncoded hex: ' + uint8ArrayToShowStr(encodedKey.data)); }) - } catch (error) { // Throw an exception immediately in synchronous mode when an error is detected during the parameter check. + } catch (error) { // Throw an exception immediately after an error is detected during the parameter check. console.error(`convertKey failed, ${error.code}, ${error.message}`); return; } } ``` -## Encrypting and Decrypting Data +## Generating an Asymmetric Key Object and Obtaining Key Parameters + +### When to Use + +Typical key generation operations involve the following: +1. Create a key object based on the specified asymmetric key parameters for subsequent encryption and decryption. +2. Obtain the parameter properties of an asymmetric key object for storage or transmission. + +> **NOTE** +> +> - Key parameters can be used to generate asymmetric keys from API version 10. +> - Asymmetric systems use a public key (**PubKey**) to encrypt data and a related private key (**PriKey**) to decrypt it. The public key and private key form a key pair (**KeyPair**). For details about asymmetric key parameters, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). + +### Available APIs + +The following table describes the APIs used in typical key generation operations. For more information about the APIs, see [AsyKeyGeneratorBySpec](../reference/apis/js-apis-cryptoFramework.md#asykeygeneratorbyspec10). + +|Instance|API|Description| +|---|---|---| +|AsyKeyGeneratorBySpec|generateKeyPair(callback: AsyncCallback): void;|Generates a **KeyPair** instance based on the key parameters. This API uses an asynchronous callback to return the result.| +|AsyKeyGeneratorBySpec|generateKeyPair(): Promise;|Generates a **KeyPair** instance based on the key parameters. This API uses a promise to return the result.| +|AsyKeyGeneratorBySpec|generatePriKey(callback: AsyncCallback): void;|Generates a **PriKey** instance based on the key parameters. This API uses an asynchronous callback to return the result.| +|AsyKeyGeneratorBySpec|generatePriKey(): Promise;|Generates a **PriKey** instance based on the key parameters. This API uses a promise to return the result.| +|AsyKeyGeneratorBySpec|generatePubKey(callback: AsyncCallback): void;|Generates a **PubKey** instance based on the key parameters. This API uses an asynchronous callback to return the result.| +|AsyKeyGeneratorBySpec|generatePubKey(): Promise;|Generates a **PubKey** instance based on the key parameters. This API uses a promise to return the result.| +| PriKey | getAsyKeySpec(itemType: AsyKeySpecItem): bigint \| string \| number; | Obtains the key specifications of a **PriKey** instance.| +| PubKey | getAsyKeySpec(itemType: AsyKeySpecItem): bigint \| string \| number; | Obtains the key specifications of a **PubKey** instance.| + +### Generating an ECC Key Pair and Obtaining Key Specifications + +Generate an ECC key pair based on parameters and obtain the key specifications. + +1. Create an **AsyKeyGenerator** based on key parameters. +2. Use the **AsyKeyGenerator** to generate an asymmetric key pair based on the specified key parameters. +3. Obtain the key specifications of a key object. + +Example: Generate an ECC key based on key parameters in promise mode. + +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; + +// Print bigint information. +function showBigIntInfo(bnName, bnValue) { + console.warn(bnName + ":"); + console.warn(". Decimal: " + bnValue.toString()); + console.warn(". Hexadecimal: " + bnValue.toString(16)); + console.warn (". Length (bits): " + bnValue.toString(2).length); +} + +// Construct the EccCommonSpec struct based on the key specifications. The EccCommonSpec struct defines the common parameters of the ECC private key and public key. +function genEccCommonSpec() { + let fieldFp = { + fieldType : "Fp", + p : BigInt("0xffffffffffffffffffffffffffffffff000000000000000000000001") + } + + let G = { + x : BigInt("0xb70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21"), + y : BigInt("0xbd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34") + } + + let eccCommonSpec = { + algName : "ECC", + specType : cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC, + field : fieldFp, + a : BigInt("0xfffffffffffffffffffffffffffffffefffffffffffffffffffffffe"), + b : BigInt("0xb4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4"), + g : G, + n : BigInt("0xffffffffffffffffffffffffffff16a2e0b8f03e13dd29455c5c2a3d"), + h : 1 + } + return eccCommonSpec; +} + +// Print the ECC key specifications. +function showEccSpecDetailInfo(key, keyType) { + console.info("show detail of " + keyType + ":"); + try { + let p = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_FP_P_BN); + showBigIntInfo("--- p", p); //length is 224, hex : ffffffffffffffffffffffffffffffff000000000000000000000001 + + let a = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_A_BN); + showBigIntInfo("--- a", a); // length is 224, hex : fffffffffffffffffffffffffffffffefffffffffffffffffffffffe + + let b = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_B_BN); + showBigIntInfo("--- b", b); // length is 224, hex : b4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4 + + let gX = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_G_X_BN); + showBigIntInfo("--- gX", gX); // length is 224, hex : b70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21 + + let gY = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_G_Y_BN); + showBigIntInfo("--- gY", gY); // length is 224, hex : bd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34 + + let n = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_N_BN); + showBigIntInfo("--- n", n); // length is 224, hex : ffffffffffffffffffffffffffff16a2e0b8f03e13dd29455c5c2a3d + + let h = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_H_NUM); + console.warn("--- h: " + h); //key h: 1 + + let fieldType = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_FIELD_TYPE_STR); + console.warn("--- field type: " + fieldType); // key field type: Fp + + let fieldSize = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_FIELD_SIZE_NUM); + console.warn("--- field size: " + fieldSize); // key field size: 224 + + let curveName = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_CURVE_NAME_STR); + console.warn("--- curve name: " + curveName); // key curve name: NID_secp224r1 + + if (keyType == "priKey") { + let sk = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_SK_BN); + showBigIntInfo("--- sk", sk); + } else if (keyType == "pubKey") { + let pkX = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_PK_X_BN); + showBigIntInfo("--- pkX", pkX); + let pkY = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_PK_Y_BN); + showBigIntInfo("--- pkY", pkY); + } + } catch (error) { + console.error("getAsyKeySpec error"); + console.error("error code: " + error.code + ", message is: " + error.message); + } +} + +// Generate an ECC key pair based on the EccCommonSpec instance and obtain the key specifications. +function testEccUseCommKeySpecGet() +{ + try { + let commKeySpec = genEccCommonSpec(); // Construct the EccCommonSpec object. + let generatorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(commKeySpec); // Create an AsyKeyGenerator instance based on the EccCommonSpec object. + let keyPairPromise = generatorBySpec.generateKeyPair(); // Generate an ECC key pair. + keyPairPromise.then( keyPair => { + showEccSpecDetailInfo(keyPair.priKey, "priKey"); // Obtain the ECC specifications of the private key. + showEccSpecDetailInfo(keyPair.pubKey, "pubKey"); // Obtain the ECC specifications of the public key. + }).catch(error => { + console.error("generateComm error"); + console.error("error code: " + error.code + ", message is: " + error.message); + }) + } catch(error) { + console.error("testEccUseCommSpec error"); + console.error("error code: " + error.code + ", message is: " + error.message); + } +} +``` + +### Generating an RSA Public Key and Obtaining Key Specifications + +Generate an RSA public key based on parameters and obtain key specifications. + +1. Create an **AsyKeyGenerator** based on key parameters. +2. Use the **AsyKeyGenerator** to generate the public key of an asymmetric key pair. +3. Obtain the key specifications of the public key object. + +Example: Generate an RSA public key based on key parameters in callback mode. +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; + +// Generate RSA public key specifications. +function genRsaPubKeySpec(nIn : bigint, eIn : bigint) { + let rsaCommSpec = { n : nIn, algName : "RSA", specType : cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC }; + let rsaPubKeySpec = { params: rsaCommSpec, pk : eIn, algName : "RSA", specType : cryptoFramework.AsyKeySpecType.PUBLIC_KEY_SPEC }; + return rsaPubKeySpec; +} + +// Construct an RSA public key specifications object based on the key parameters. +function genRsa2048PubKeySpec() { + let nIn = BigInt("0x9260d0750ae117eee55c3f3deaba74917521a262ee76007cdf8a56755ad73a1598a1408410a01434c3f5bc54a88b57fa19fc4328daea0750a4c44e88cff3b2382621b80f670464433e4336e6d003e8cd65bff211da144b88291c2259a00a72b711c116ef7686e8fee34e4d933c868187bdc26f7be071493c86f7a5941c3510806ad67b0f94d88f5cf5c02a092821d8626e8932b65c5bd8c92049c210932b7afa7ac59c0e886ae5c1edb00d8ce2c57633db26bd6639bff73cee82be9275c402b4cf2a4388da8cf8c64eefe1c5a0f5ab8057c39fa5c0589c3e253f0960332300f94bea44877b588e1edbde97cf2360727a09b775262d7ee552b3319b9266f05a25"); + let eIn = BigInt("0x010001"); + return genRsaPubKeySpec(nIn, eIn); +} + +// Compare the RSA public key specifications with the expected values. +function compareRsaPubKeyBySpec(rsaKeySpec, n, e) { + if (rsaKeySpec.params.n != n) { + return false; + } + if (rsaKeySpec.pk != e) { + return false; + } + return true; +} + +// Generate an RSA public key based on the RSA public key specifications, obtain the key specifications, and compare the key specifications with the expected values. +function rsaUsePubKeySpecGetCallback() { + let rsaPubKeySpec = genRsa2048PubKeySpec(); + let rsaGeneratorSpec = cryptoFramework.createAsyKeyGeneratorBySpec(rsaPubKeySpec); + rsaGeneratorSpec.generatePubKey((error, key) => { + let pubKey = key; + let nBN = pubKey.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.RSA_N_BN); + let eBN = pubKey.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.RSA_PK_BN); + if (compareRsaPubKeyBySpec(rsaPubKeySpec, nBN, eBN) != true) { + AlertDialog.show({ message : "error pub key big number"} ); + } else { + console.info("n, e in the pubKey are same as the spec."); + } + if (error) { + console.error("generate pubKey error" + "error code: " + error.code + "error message" + error.message); + } + }); +} +``` + +## Encryption and Decryption -**When to Use** +### When to Use Important data needs to be encrypted in data storage or transmission for security purposes. Typical encryption and decryption operations involve the following: 1. Encrypt and decrypt data using a symmetric key. 2. Encrypt and decrypt data using an asymmetric key pair. +3. Obtain and set the **CipherSpecItem** parameter when the PKCS1_OAEP padding mode is used in RSA. + +> **NOTE** +> +> - From API version 10, [CipherSpecItem](../reference/apis/js-apis-cryptoFramework.md#cipherspecitem10) can be obtained and set when the PKCS1_OAEP padding mode is used in RSA. +> - From API version 10, the string parameter without the key length is supported in encryption and decryption. -**Available APIs** +### Available APIs + +The following table describes the APIs used in the typical encryption and decryption operations. For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). + +> **NOTE** +> +> Due to complexity of cryptographic algorithms, the implementation varies depending on the key specifications and parameters you use, and cannot be enumerated by sample code. Before you start, understand the APIs to ensure correct use of these APIs. -For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md).
Due to the complexity of cryptographic algorithms, the implementation varies depending on the specifications and parameters you use, and cannot be enumerated by sample code. Before you start, understand the APIs in the API reference to ensure correct use of these APIs. -The table below describes the APIs used in this guide. |Instance|API|Description| |---|---|---| -|cryptoFramework|createCipher(transformation : string) : Cipher|Creates a **Cipher** instance.| -|Cipher|init(opMode : CryptoMode, key : Key, params : ParamsSpec, callback : AsyncCallback\) : void|Sets a key and initializes the **Cipher** instance. This API uses an asynchronous callback to return the result.| -|Cipher|init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\|Sets a key and initializes the **Cipher** instance. This API uses a promise to return the result.| +|cryptoFramework|createCipher(transformation : string) : Cipher|Creates a **Cipher** instance based on the algorithm specified by **transformation**.| +|Cipher|init(opMode : CryptoMode, key : Key, params : ParamsSpec, callback : AsyncCallback\) : void|Initializes the **Cipher** instance. This API uses an asynchronous callback to return the result.| +|Cipher|init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\|Initializes the **Cipher** instance. This API uses a promise to return the result.| |Cipher|update(data : DataBlob, callback : AsyncCallback\) : void|Updates the data for encryption and decryption. This API uses an asynchronous callback to return the result.| |Cipher|update(data : DataBlob) : Promise\|Updates the data for encryption and decryption. This API uses a promise to return the result.| |Cipher|doFinal(data : DataBlob, callback : AsyncCallback\) : void|Finalizes the encryption or decryption. This API uses an asynchronous callback to return the result.| |Cipher|doFinal(data : DataBlob) : Promise\|Finalizes the encryption or decryption. This API uses a promise to return the result.| +|Cipher|getCipherSpec(itemType: CipherSpecItem): string \| Uint8Array|Obtains cipher specifications. Currently, only the RSA is supported.| +|Cipher|setCipherSpec(itemType: CipherSpecItem, itemValue: Uint8Array): void|Sets cipher specifications. Currently, only the RSA is supported.| -**How to Develop** +### Encrypting and Decrypting Data Using AES GCM (Promise) -Example 1: Encrypt and decrypt data using a symmetric key. +Encrypt and decrypt data using an AES symmetric key. 1. Create a **SymKeyGenerator** instance. -2. Use the key generator to generate a symmetric key. +2. Use the **SymKeyGenerator** to randomly generate a symmetric key. 3. Create a **Cipher** instance. 4. Encrypt or decrypt data. -The following example demonstrates how to use the AES-GCM to encrypt and decrypt data with promise-based APIs. - ```js import cryptoFramework from '@ohos.security.cryptoFramework'; @@ -251,7 +472,7 @@ function genGcmParamsSpec() { arr = [0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0]; // 16 bytes let dataTag = new Uint8Array(arr); let tagBlob = {data : dataTag}; // The authTag of GCM is obtained by doFinal() in encryption and passed in params of init() in decryption. - + let gcmParamsSpec = {iv : ivBlob, aad : aadBlob, authTag : tagBlob, algName : "GcmParamsSpec"}; return gcmParamsSpec; } @@ -281,17 +502,7 @@ function uint8ArrayToString(array) { return arrayString; } -function genKeyMaterialBlob() { - let arr = [ - 0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56, - 0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c, - 0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes) - let keyMaterial = new Uint8Array(arr); - return {data : keyMaterial}; -} - - -// Automatically generate a key in AES GCM mode and return the result in a promise. +// Automatically generate an AES GCM key in promise mode. function testAesGcm() { return new Promise((resolve, reject) => { setTimeout(() => { @@ -308,7 +519,7 @@ function testAesGcm() { console.info(`symKeyGenerator algName: ${symKeyGenerator.algName}`); // Use the key generator to randomly generate a 128-bit symmetric key. let promiseSymKey = symKeyGenerator.generateSymKey(); - // Constructor + // Generate GCM parameter specifications. globalGcmParams = genGcmParamsSpec(); // Create a Cipher instance. @@ -344,7 +555,7 @@ function testAesGcm() { globalGcmParams.authTag = authTag; return; }).then(() => { - // Initialize the cipher environment and start decryption. + // Initialize the Cipher instance and start decryption. let mode = cryptoFramework.CryptoMode.DECRYPT_MODE; let promiseInit = globalCipher.init(mode, globalKey, globalGcmParams); // init return promiseInit; @@ -365,7 +576,14 @@ function testAesGcm() { } ``` -The following example demonstrates how to use the the 3DES ECB to convert existing data into a key and encrypt and decrypt data using callback-based APIs. +### Encrypting and Decrypting Data Using a 3DES ECB Symmetric Key (Callback) + +Encrypt and decrypt data using a 3DES symmetric key. + +1. Create a **SymKeyGenerator** instance. +2. Generate a key based on the existing binary data. +3. Create a **Cipher** instance. +4. Encrypt or decrypt data using the **Cipher** instance. ```js import cryptoFramework from '@ohos.security.cryptoFramework'; @@ -409,7 +627,7 @@ function genKeyMaterialBlob() { return {data : keyMaterial}; } -// Use the 3DES ECB to Generate a key from the existing data and encrypt and decrypt data using callback-based APIs. +// Generate a 3DES ECB key from the existing data in callback mode. function test3DesEcb() { // Create a SymKeyGenerator instance. let symAlgName = '3DES192'; @@ -444,7 +662,7 @@ function test3DesEcb() { console.info('key getEncoded hex: ' + uint8ArrayToShowStr(encodedKey.data)); globalKey = key; - // Initialize the cipher environment and start encryption. + // Initialize the Cipher instance and start encryption. let mode = cryptoFramework.CryptoMode.ENCRYPT_MODE; // init globalCipher.init(mode, key, null, (err, ) => { @@ -465,7 +683,7 @@ function test3DesEcb() { globalCipherText = new Uint8Array(globalCipherText); globalCipherText = {data : globalCipherText}; } - // Initialize the cipher environment and start decryption. + // Initialize the Cipher instance and start decryption. let mode = cryptoFramework.CryptoMode.DECRYPT_MODE; // init globalCipher.init(mode, globalKey, null, (err, ) => { @@ -490,9 +708,19 @@ function test3DesEcb() { } } ``` -The following example demonstrates how to call **update()** multiple times to implement AES GCM encryption and decryption by using promise-based APIs. -```javascript +### Encrypting and Decrypting Data Using an AES GCM Symmetric Key by Segment (Promise) + +Use an AES symmetric key to encrypt and decrypt a large amount of data by segment using **update()**. + +1. Create a **SymKeyGenerator** instance. +2. Generate a key based on the existing binary data. +3. Create a **Cipher** instance. +4. Encrypt or decrypt data. + +Example: Encrypt and decrypt a large amount in AES GCM mode by calling **update()** multiple times in promise mode. + +```js import cryptoFramework from '@ohos.security.cryptoFramework'; var globalCipher; @@ -550,7 +778,7 @@ function testAesMultiUpdate() { console.info(`symKeyGenerator algName: ${symKeyGenerator.algName}`); // Use the key generator to randomly generate a 128-bit symmetric key. let promiseSymKey = symKeyGenerator.generateSymKey(); - // Constructor + // Construct key specifications. globalGcmParams = genGcmParamsSpec(); // Create a Cipher instance. @@ -578,7 +806,7 @@ function testAesMultiUpdate() { let messageArr = []; let updateLength = 20; // Pass in 20 bytes by update() each time. globalCipherText = []; - + for (let i = 0; i <= plainText.length; i++) { if ((i % updateLength == 0 || i == plainText.length) && messageArr.length != 0) { let message = new Uint8Array(messageArr); @@ -602,7 +830,7 @@ function testAesMultiUpdate() { globalGcmParams.authTag = authTag; return; }).then(() => { - // Initialize the cipher environment and start decryption. + // Initialize the Cipher instance and start decryption. let mode = cryptoFramework.CryptoMode.DECRYPT_MODE; let promiseInit = globalCipher.init(mode, globalKey, globalGcmParams); // init return promiseInit; @@ -632,76 +860,103 @@ function testAesMultiUpdate() { } ``` -Example 2: Encrypt and decrypt data using an asymmetric key pair. +### Encrypting and Decrypting Data Using RSA + +Encrypt and decrypt data using an RSA asymmetric key pair. 1. Generate an RSA key pair.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair. 2. Create a **Cipher** instance.
Call **createCipher()** to create a **Cipher** instance, and set the key and encryption/decryption mode. -3. Perform encryption and decryption operations.
Call **doFinal()** provided by the **Cipher** instance to encrypt data or decrypt data. +3. Encrypt and decrypt data.
Call **doFinal()** provided by the **Cipher** instance to encrypt data or decrypt data. -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" let plan = "This is cipher test."; +// Convert strings in plaintext into byte streams. function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { arr.push(str.charCodeAt(i)); } - var tmpArray = new Uint8Array(arr); - return tmpArray; + return new Uint8Array(arr); } -function encryptMessageProMise() { +// Encrypt the message in promise mode. +function encryptMessagePromise() { + // Create an AsyKeyGenerator instance. let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); + // Create a Cipher instance. let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); + // Generate an asymmetric key pair using the AsyKeyGenerator instance. let keyGenPromise = rsaGenerator.generateKeyPair(); keyGenPromise.then(rsaKeyPair => { let pubKey = rsaKeyPair.pubKey; + // Initialize the Cipher instance and use the public key to encrypt the data. return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null); }).then(() => { + // doFinal let input = { data : stringToUint8Array(plan) }; return cipher.doFinal(input); }).then(dataBlob => { + // Obtain the encrypted data. console.info("EncryptOutPut is " + dataBlob.data); }); } +// Encrypt the message in callback mode. function encryptMessageCallback() { + // Create an AsyKeyGenerator instance. let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); + // Create a Cipher instance. let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); + // Generate an asymmetric key pair using the AsyKeyGenerator instance. rsaGenerator.generateKeyPair(function (err, keyPair) { let pubKey = keyPair.pubKey; + // Initialize the Cipher instance and use the public key to encrypt the data. cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null, function (err, data) { let input = {data : stringToUint8Array(plan) }; + // doFinal cipher.doFinal(input, function (err, data) { + // Obtain the encrypted data. console.info("EncryptOutPut is " + data.data); }) }) }) } -function decryptMessageProMise() { +// Encrypt and decrypt the message in promise mode. +function decryptMessagePromise() { + // Create an AsyKeyGenerator instance. let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); + // Create a Cipher instance for encryption. let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); + // Create a Cipher instance for decryption. let decoder = cryptoFramework.createCipher("RSA1024|PKCS1"); + // Generate an asymmetric key pair using the AsyKeyGenerator instance. let keyGenPromise = rsaGenerator.generateKeyPair(); let keyPair; let cipherDataBlob; let input = { data : stringToUint8Array(plan) }; keyGenPromise.then(rsaKeyPair => { keyPair = rsaKeyPair; + // Initialize the Cipher instance and use the public key to encrypt the message. return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, null); }).then(() => { + // Call doFinal() to encrypt data. return cipher.doFinal(input); }).then(dataBlob => { + // Obtain the encrypted information and use it as the input parameter for decryption. console.info("EncryptOutPut is " + dataBlob.data); AlertDialog.show({message : "output" + dataBlob.data}); cipherDataBlob = dataBlob; + // Initialize the Cipher instance and use the private key to decrypt the message. return decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, keyPair.priKey, null); }).then(() => { + // Call doFinal() to decrypt the message. return decoder.doFinal(cipherDataBlob); }).then(decodeData => { + // Check whether the decrypted data is consistent with the original data. if (decodeData.data.toString() === input.data.toString()) { AlertDialog.show({message : "decrypt success"}); return; @@ -710,27 +965,38 @@ function decryptMessageProMise() { }); } +// Encrypt and decrypt the message in callback mode. function decryptMessageCallback() { + // Create an AsyKeyGenerator instance. let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); + // Create a Cipher instance for encryption. let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); + // Create a Cipher instance for decryption. let decoder = cryptoFramework.createCipher("RSA1024|PKCS1"); let plainText = "this is cipher text"; let input = {data : stringToUint8Array(plainText) }; let cipherData; let keyPair; + // Generate an asymmetric key pair using the AsyKeyGenerator instance. rsaGenerator.generateKeyPair(function (err, newKeyPair) { keyPair = newKeyPair; + // Initialize the Cipher instance and use the public key to encrypt the message. cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, null, function (err, data) { + // Call doFinal() to encrypt the message. cipher.doFinal(input, function (err, data) { + // Obtain the encrypted information and use it as the input parameter for decryption. AlertDialog.show({ message : "EncryptOutPut is " + data.data} ); cipherData = data; + // Initialize the Cipher instance and use the private key to decrypt the message. decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, keyPair.priKey, null, function (err, data) { + // Call doFinal() to decrypt the message. decoder.doFinal(cipherData, function (err, data) { + // Check whether the decrypted data is consistent with the original data. if (input.data.toString() === data.data.toString()) { - AlertDialog.show({ message : "decrype success"} ); + AlertDialog.show({ message : "decryption success"} ); return; } - AlertDialog.show({ message : "decrype fail"} ); + AlertDialog.show({ message : "decryption fail"} ); }); }); }); @@ -738,17 +1004,25 @@ function decryptMessageCallback() { }); } ``` -The following example demonstrates how to implement RSA asymmetric encryption and decryption (**doFinal()** is called multiple times). -```javascript + +### Encrypting and Decrypting Data Using RSA by Segment + +Use an RSA asymmetric key pair to encrypt and decrypt a large amount of data by segment. + +1. Generate an RSA key pair.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair. +2. Create a **Cipher** instance.
Call **createCipher()** to create a **Cipher** instance, and set the key and encryption/decryption mode. +3. Encrypt and decrypt data.
Call **doFinal()** provided by the **Cipher** instance multiple times to encrypt and decrypt data. + +```js import cryptoFramework from "@ohos.security.cryptoFramework" +// Convert strings in plaintext into byte streams. function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { arr.push(str.charCodeAt(i)); } - var tmpArray = new Uint8Array(arr); - return tmpArray; + return new Uint8Array(arr); } // Convert byte streams into strings in plaintext. @@ -784,9 +1058,9 @@ function encryptLongMessagePromise() { resolve("testRsaMultiDoFinal"); }, 10); }).then(() => { - return asyKeyGenerator.generateKeyPair(); // Generate an RSA key. + return asyKeyGenerator.generateKeyPair(); // Generate an RSA key pair. }).then(keyPair => { - globalKeyPair = keyPair; // Save the key to global variables. + globalKeyPair = keyPair; // Save the key pair as a global variable. return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, globalKeyPair.pubKey, null); }).then(async () => { globalCipherOutput = []; @@ -825,21 +1099,138 @@ function encryptLongMessagePromise() { > **NOTE** > -> - In RSA encryption and decryption, **init()** cannot be repeatedly called to initialize the **Cipher** instance. You must create a **Cipher** instance for each encryption and decryption. -> - The RSA encryption has a limit on the length of the plaintext to be encrypted. For details, see "Basic Concepts" in [Cryptographic Framework Overview](cryptoFramework-overview.md). +> - In RSA encryption and decryption, **init()** cannot be repeatedly called to initialize a **Cipher** instance. You must create a **Cipher** instance for each encryption and decryption. +> - The RSA encryption has a limit on the length of the plaintext to be encrypted. For details, see [Encryption and Decryption](cryptoFramework-overview.md#encryption-and-decryption). > - In RSA decryption, the length of the ciphertext to be decrypted each time is the number of bits of the RSA key divided by 8. -## Generating and Verifying a Signature +### Using PKCS1_OAEP in RSA Encryption and Decryption + +Use the PKCS1_OAEP padding mode in RSA encryption and decryption in promise mode. + +1. Generate an RSA key pair based on the key parameters.
Call **createAsyKeyGeneratorBySpec()** to create an **AsyKeyGeneratorBySpec** object and generate an RSA asymmetric key pair. (You can also use **createAsyKeyGenerator()** to randomly generate or convert an RSA key object.) +2. Create a **Cipher** instance.
Call **createCipher()** to create a cipher instance, initialize the cipher instance, set the key and encryption/decryption mode, use **setCipherSpec()** to set PKCS1_OAEP **pSource**, and use **update()** to pass in data. +3. Encrypt and decrypt data.
Call the **doFinal()** provided by the **Cipher** class to perform encryption or decryption. The **pSource** of the **Cipher** instance to be encrypted must be the same as that decrypted. + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +// Convert strings in plaintext into byte streams. +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} + +// Construct the key parameters of the RSA asymmetric key pair based on the key pair specifications. +function genRsaKeyPairSpec(nIn : bigint, eIn : bigint, dIn : bigint) { + let rsaCommSpec = { n : nIn, algName : "RSA", specType : cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC }; + let rsaKeyPairSpec = { params: rsaCommSpec, sk : dIn, pk : eIn, algName : "RSA", specType : cryptoFramework.AsyKeySpecType.KEY_PAIR_SPEC }; + return rsaKeyPairSpec; +} + +// Generate RSA2048 key pair parameters. +function genRsa2048KeyPairSpec() { + let nIn = BigInt("0x9260d0750ae117eee55c3f3deaba74917521a262ee76007cdf8a56755ad73a1598a1408410a01434c3f5bc54a88b57fa19fc4328daea0750a4c44e88cff3b2382621b80f670464433e4336e6d003e8cd65bff211da144b88291c2259a00a72b711c116ef7686e8fee34e4d933c868187bdc26f7be071493c86f7a5941c3510806ad67b0f94d88f5cf5c02a092821d8626e8932b65c5bd8c92049c210932b7afa7ac59c0e886ae5c1edb00d8ce2c57633db26bd6639bff73cee82be9275c402b4cf2a4388da8cf8c64eefe1c5a0f5ab8057c39fa5c0589c3e253f0960332300f94bea44877b588e1edbde97cf2360727a09b775262d7ee552b3319b9266f05a25"); + let eIn = BigInt("0x010001"); + let dIn = BigInt("0x6a7df2ca63ead4dda191d614b6b385e0d9056a3d6d5cfe07db1daabee022db08212d97613d3328e0267c9dd23d787abde2afcb306aeb7dfce69246cc73f5c87fdf06030179a2114b767db1f083ff841c025d7dc00cd82435b9a90f695369e94df23d2ce458bc3b3283ad8bba2b8fa1ba62e2dce9accff3799aae7c840016f3ba8e0048c0b6cc4339af7161003a5beb864a0164b2c1c9237b64bc87556994351b27506c33d4bcdfce0f9c491a7d6b0628c7c852be4f0a9c3132b2ed3a2c8881e9aab07e20e17deb074691be677776a78b5c502e05d9bdde72126b3738695e2dd1a0a98a14247c65d8a7ee79432a092cb0721a12df798e44f7cfce0c498147a9b1"); + return genRsaKeyPairSpec(nIn, eIn, dIn); +} + +function rsaUseSpecDecryptOAEPPromise() { + let plan = "This is cipher test."; + // Obtain the key parameter object of the RSA key pair. + let rsaKeyPairSpec = genRsa2048KeyPairSpec(); + // Generate an RSA key pair based on the RSA key parameters. + let rsaGeneratorSpec = cryptoFramework.createAsyKeyGeneratorBySpec(rsaKeyPairSpec); + let keyGenPromise = rsaGeneratorSpec.generateKeyPair(); + let cipher = cryptoFramework.createCipher("RSA|PKCS1_OAEP|SHA256|MGF1_SHA1"); + let decoder = cryptoFramework.createCipher("RSA|PKCS1_OAEP|SHA256|MGF1_SHA1"); + let keyPair; + let cipherDataBlob; + // Set the pSource, which defines the encoding input P filled by OAEP. + let pSource = new Uint8Array([1,2,3,4]); + let input = { data : stringToUint8Array(plan) }; + // Generate the key pair. + keyGenPromise.then(rsaKeyPair => { + keyPair = rsaKeyPair; + // Initialize the Cipher instance for encryption. + return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, null); + }).then(() => { + // Set and obtain the cipher specifications after the initialization. + cipher.setCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR, pSource); + let retP = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR); + // Check whether the obtained PSource is the same as the PSource set. + if (retP.toString() != pSource.toString()) { + AlertDialog.show({message : "error init pSource" + retP}); + } else { + console.info("pSource changed ==" + retP); + } + // Obtain other OAEP parameters. + let md = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MD_NAME_STR); + console.info("md == " + md); + let mgf = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF_NAME_STR); + console.info("mgf == " + mgf); + let mgf1Md = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_MD_STR); + console.info("mgf1Md == " + mgf1Md); + return cipher.doFinal(input); + }).then(dataBlob => { + console.info("EncryptOutPut is " + dataBlob.data); + cipherDataBlob = dataBlob; + // The get() and set() operations can be performed before the init() operation of the Cipher object and are equivalent to those after the init() operation. For example, set and get the decoder. + decoder.setCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR, pSource); + let retP = decoder.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR); + // Check whether the obtained PSource is the same as the PSource set. + if (retP.toString() != pSource.toString()) { + AlertDialog.show({message : "error init pSource" + retP}); + } else { + console.info("pSource changed ==" + retP); + } + // Obtain other OAEP parameters. + let md = decoder.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MD_NAME_STR); + console.info("md == " + md); + let mgf = decoder.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF_NAME_STR); + console.info("mgf == " + mgf); + let mgf1Md = decoder.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_MD_STR); + console.info("mgf1Md == " + mgf1Md); + // Initialize the decryption operation. + return decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, keyPair.priKey, null); + }).then(() => { + return decoder.doFinal(cipherDataBlob); + }).then(decodeData => { + // The decryption is successful. + if (decodeData.data.toString() === input.data.toString()) { + console.info("oaep decrypt success"); + AlertDialog.show({message : " oaep decrypt success"}); + } else { + AlertDialog.show({message : "oeap decrypt fail"}); + } + }); +} +``` -**When to Use** +## Signing and Signature Verification + +### When to Use A digital signature can be used to verify the authenticity of a message. Typical signing and signature verification operations involve the following: -- Use the RSA to generate and verify a signature. -- Use the ECC to generate and verify a signature. +1. Use RSA to generate a signature and verify the signature. +2. Use ECC to generate a signature and verify the signature. +3. Use RSA to generate a signature and verify the signature. Obtain and set **SignSpecItem** when the PSS padding mode is used. + +> **NOTE** +> +> - From API version 10, [SignSpecItem](../reference/apis/js-apis-cryptoFramework.md#signspecitem10) can be set and obtained when the PSS padding mode is used. +> - From API version 10, the string parameter without the key length is supported in signature verification. -**Available APIs** +### Available APIs -For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md).
Due to the complexity of cryptographic algorithms, the implementation varies depending on the specifications and parameters you use, and cannot be enumerated by sample code. Before you start, understand the APIs in the API reference to ensure correct use of these APIs. +The following table describes the APIs used in typical signing and signature verification operations. For more information about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). + +> **NOTE** +> +> Due to complexity of cryptographic algorithms, the implementation varies depending on the specifications and parameters you use, and cannot be enumerated by sample code. Before you start, understand the APIs to ensure correct use of these APIs. |Instance|API|Description| |---|---|---| @@ -850,32 +1241,38 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry |Sign|update(data : DataBlob) : Promise\|Updates the data for signing. This API uses a promise to return the result.| |Sign|sign(data : DataBlob, callback : AsyncCallback\) : void|Signs the data. This API uses an asynchronous callback to return the result.| |Sign|sign(data : DataBlob) : Promise\|Signs the data. This API uses a promise to return the result.| +|Sign|getSignSpec(itemType: SignSpecItem): string \| number|Obtains the signing specifications. Currently, only the RSA is supported.| +|Sign|setSignSpec(itemType: SignSpecItem, itemValue: number): void|Sets signing specifications. Currently, only the RSA is supported.| |cryptoFramework|function createVerify(algName : string) : Verify|Creates a **Verify** instance.| -|Verify|init(priKey : PriKey, callback : AsyncCallback\) : void|Sets a key and initializes the **Verify** instance. This API uses an asynchronous callback to return the result.| -|Verify|init(priKey : PriKey) : Promise\|Sets a key and initializes the **Verify** instance. This API uses a promise to return the result.| +|Verify|init(pubKey : PubKey, callback : AsyncCallback\) : void|Sets a key and initializes the **Verify** instance. This API uses an asynchronous callback to return the result.| +|Verify|init(pubKey : PubKey) : Promise\|Sets a key and initializes the **Verify** instance. This API uses a promise to return the result.| |Verify|update(data : DataBlob, callback : AsyncCallback\) : void|Updates the data for signature verification. This API uses an asynchronous callback to return the result.| |Verify|update(data : DataBlob) : Promise\|Updates the data for signature verification. This API uses a promise to return the result.| -|Verify|verify(data : DataBlob, signatureData : DataBlob, callback : AsyncCallback\) : void|Verifies the signature. This API uses an asynchronous callback to return the result.| -|Verify|verify(data : DataBlob, signatureData : DataBlob) : Promise\|Verifies the signature. This API uses a promise to return the result.| +|Verify|verify(data : DataBlob, signatureData : DataBlob, callback : AsyncCallback\) : void|Verifies a signature. This API uses an asynchronous callback to return the result.| +|Verify|verify(data : DataBlob, signatureData : DataBlob) : Promise\|Verifies a signature. This API uses a promise to return the result.| +|Verify|getVerifySpec(itemType: SignSpecItem): string \| number|Obtains signature verification specifications. Currently, only the RSA is supported.| +|Verify|setVerifySpec(itemType: SignSpecItem, itemValue: number): void|Sets signature verification specifications. Currently, only the RSA is supported.| -**How to Develop** +### Signing and Signature Verification Using RSA + +Use RSA to sign data and verify the signature. -Example 1: Use the RSA to generate and verify a signature. 1. Generate an RSA key pair.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair. 2. Create a **Sign** instance.
Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing. -3. Generate a signature.
Call **update()** provided by the **Sign** class to add the data for signing and call **sign()** to generate a signature. +3. Generate a signature.
Call **update()** provided by the **Sign** class to pass in the data for signing and call **sign()** to generate a signature. 4. Create a **Verify** instance.
Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification. -5. Verify the signature.
Call **update()** provided by the **Verify** class to add signature data and call **verify()** to verify the signature. -```javascript +5. Verify the signature.
Call **update()** provided by the **Verify** class to pass in the signature data and call **verify()** to verify the signature. + +```js import cryptoFramework from "@ohos.security.cryptoFramework" +// Convert strings in plaintext into byte streams. function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - var tmpArray = new Uint8Array(arr); - return tmpArray; + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); } let globalKeyPair; @@ -887,7 +1284,7 @@ let input2 = { data : stringToUint8Array(plan2) }; function signMessagePromise() { let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); - let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); + let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); // From API version 10, a Sign instance can be created by specifying a string parameter defining the key specifications. let keyGenPromise = rsaGenerator.generateKeyPair(); keyGenPromise.then( keyPair => { globalKeyPair = keyPair; @@ -917,7 +1314,7 @@ function verifyMessagePromise() { function signMessageCallback() { let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); - let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); + let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); // From API version 10, a Sign instance can be created by specifying a string parameter defining the key specifications. rsaGenerator.generateKeyPair(function (err, keyPair) { globalKeyPair = keyPair; let priKey = globalKeyPair.priKey; @@ -944,23 +1341,26 @@ function verifyMessageCallback() { } ``` -Example 2: Use the ECDSA to generate and verify a signature. +### Signing and Signature Verification Using ECDSA + +Use the ECDSA to sign data and verify the signature. + 1. Generate an ECC key.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair. 2. Create a **Sign** instance.
Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing. -3. Generate a signature.
Call **update()** provided by the **Sign** class to add the data for signing and call **doFinal()** to generate a signature. +3. Generate a signature.
Call **update()** provided by the **Sign** class to pass in the data for signing and call **doFinal()** to generate a signature. 4. Create a **Verify** instance.
Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification. -5. Verify the signature.
Call **update()** provided by the **Verify** class to add signature data and call **doFinal()** to verify the signature. +5. Verify the signature.
Call **update()** provided by the **Verify** class to pass in the signature data and call **doFinal()** to verify the signature. -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" +// Convert strings in plaintext into byte streams. function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - var tmpArray = new Uint8Array(arr); - return tmpArray; + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); } let globalKeyPair; @@ -1028,17 +1428,27 @@ function verifyMessageCallback() { }) } ``` -The following example demonstrates how to call **update()** multiple times to implement signing and signature verification. -```javascript + +### Signing and Signature Verification Using RSA by Segment + +Use RSA to sign data and verify the signature by segment. + +1. Generate an RSA key pair.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair. +2. Create a **Sign** instance.
Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing. +3. Generate a signature.
Call the **update()** provided by the **Sign** class multiple times to pass in data by segment and call **sign()** to generate a signature. +4. Create a **Verify** instance.
Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification. +5. Verify the signature.
Call the **update()** provided by the **Verify** class multiple times to pass in data by segment and call **verify()** to verify the signature. + +```js import cryptoFramework from "@ohos.security.cryptoFramework" +// Convert strings in plaintext into byte streams. function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { arr.push(str.charCodeAt(i)); } - var tmpArray = new Uint8Array(arr); - return tmpArray; + return new Uint8Array(arr); } function signLongMessagePromise() { @@ -1056,16 +1466,16 @@ function signLongMessagePromise() { let cipherAlgName = "RSA1024|PKCS1|SHA256"; let globalKeyPair; let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator(keyGenName); // Create an AsyKeyGenerator object. - let signer = cryptoFramework.createSign(cipherAlgName); //Create a cipher object for encryption. - let verifier = cryptoFramework.createVerify(cipherAlgName); // Create a Decoder object for decryption. + let signer = cryptoFramework.createSign(cipherAlgName); //Create a Sign object for signing. + let verifier = cryptoFramework.createVerify(cipherAlgName); // Create a Verify object for signature verification. return new Promise((resolve, reject) => { setTimeout(() => { resolve("testRsaMultiUpdate"); }, 10); }).then(() => { - return asyKeyGenerator.generateKeyPair(); // Generate an RSA key. + return asyKeyGenerator.generateKeyPair(); // Generate an RSA key pair. }).then(keyPair => { - globalKeyPair = keyPair; // Save the key to global variables. + globalKeyPair = keyPair; // Save the key pair as a global variable. return signer.init(globalKeyPair.priKey); }).then(async () => { // If the plaintext is too large, split the plaintext based on the specified length and cyclically call update() to pass in the plaintext. @@ -1095,26 +1505,183 @@ function signLongMessagePromise() { } ``` -## Generating a Digest +### Using PSS in RSA Signing and Signature Verification -**When to Use** +Use the PSS padding mode in RSA signing and signature verification in callback mode. -A message digest (MD) is a fixed size numeric representation of the content of a message, computed by a has function. It is sent with the message. The receiver can generate a digest for the message and compare it with the digest received. If the two digests are the same, the message integrity is verified. +1. Generate an RSA key pair based on the key parameters.
Call **createAsyKeyGeneratorBySpec** to create an **AsyKeyGeneratorBySpec** object and generate an RSA asymmetric key pair. +2. Create a **Sign** instance.
Call **createSign()** to create a **Sign** object, initialize the **Sign** object, set the private key for signing, and set and obtain PSS parameters. +3. Generate a signature.
Call **update()** provided by the **Sign** class to pass in the data for signing and call **sign()** to generate a signature. +4. Create a **Verify** instance.
Call **createVerify()** to create a **Verify** object, initialize the object, set the public key for signature verification, and set and obtain PSS parameters. The signature verification is successful if the salt length is the same. +5. Verify the signature.
Call **update()** provided by the **Verify** class to pass in the signature data and call **verify()** to verify the signature. -Typical MD operations involve the following: +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +// Convert strings in plaintext into byte streams. +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} + +// Construct the key parameters of the RSA asymmetric key pair based on the key pair specifications. +function genRsaKeyPairSpec(nIn : bigint, eIn : bigint, dIn : bigint) { + let rsaCommSpec = { n : nIn, algName : "RSA", specType : cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC }; + let rsaKeyPairSpec = { params: rsaCommSpec, sk : dIn, pk : eIn, algName : "RSA", specType : cryptoFramework.AsyKeySpecType.KEY_PAIR_SPEC }; + return rsaKeyPairSpec; +} + +// Generate RSA2048 key pair parameters. +function genRsa2048KeyPairSpec() { + let nIn = BigInt("0x9260d0750ae117eee55c3f3deaba74917521a262ee76007cdf8a56755ad73a1598a1408410a01434c3f5bc54a88b57fa19fc4328daea0750a4c44e88cff3b2382621b80f670464433e4336e6d003e8cd65bff211da144b88291c2259a00a72b711c116ef7686e8fee34e4d933c868187bdc26f7be071493c86f7a5941c3510806ad67b0f94d88f5cf5c02a092821d8626e8932b65c5bd8c92049c210932b7afa7ac59c0e886ae5c1edb00d8ce2c57633db26bd6639bff73cee82be9275c402b4cf2a4388da8cf8c64eefe1c5a0f5ab8057c39fa5c0589c3e253f0960332300f94bea44877b588e1edbde97cf2360727a09b775262d7ee552b3319b9266f05a25"); + let eIn = BigInt("0x010001"); + let dIn = BigInt("0x6a7df2ca63ead4dda191d614b6b385e0d9056a3d6d5cfe07db1daabee022db08212d97613d3328e0267c9dd23d787abde2afcb306aeb7dfce69246cc73f5c87fdf06030179a2114b767db1f083ff841c025d7dc00cd82435b9a90f695369e94df23d2ce458bc3b3283ad8bba2b8fa1ba62e2dce9accff3799aae7c840016f3ba8e0048c0b6cc4339af7161003a5beb864a0164b2c1c9237b64bc87556994351b27506c33d4bcdfce0f9c491a7d6b0628c7c852be4f0a9c3132b2ed3a2c8881e9aab07e20e17deb074691be677776a78b5c502e05d9bdde72126b3738695e2dd1a0a98a14247c65d8a7ee79432a092cb0721a12df798e44f7cfce0c498147a9b1"); + return genRsaKeyPairSpec(nIn, eIn, dIn); +} + +function verifyMessageCallbackPSS() { + let plan1 = "This is Sign test plan1"; + let plan2 = "This is Sign test plan1"; + let input1 = { data : stringToUint8Array(plan1) }; + let input2 = { data : stringToUint8Array(plan2) }; + let globalKeyPair; + let signMessageBlob; + // Obtain the key parameter object of the RSA key pair. + let rsaKeyPairSpec = genRsa2048KeyPairSpec(); + // Create an RSA key pair generator. + let rsaGeneratorSpec = cryptoFramework.createAsyKeyGeneratorBySpec(rsaKeyPairSpec); + // Both sign() and verify() support the RSA key with or without the length. + let signer = cryptoFramework.createSign("RSA|PSS|SHA256|MGF1_SHA256"); + let verifyer = cryptoFramework.createVerify("RSA2048|PSS|SHA256|MGF1_SHA256"); + rsaGeneratorSpec.generateKeyPair(function (err, keyPair) { + globalKeyPair = keyPair; + signer.init(globalKeyPair.priKey, function (err, data) { + // After the initialization, set and obtain the PSS parameters. + let setN = 32; + signer.setSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, setN); + let saltLen = signer.getSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM); + console.info("SaltLen == " + saltLen); + let tf = signer.getSignSpec(cryptoFramework.SignSpecItem.PSS_TRAILER_FIELD_NUM); + console.info("trailer field == " + tf); + let md = signer.getSignSpec(cryptoFramework.SignSpecItem.PSS_MD_NAME_STR); + console.info("md == " + md); + let mgf = signer.getSignSpec(cryptoFramework.SignSpecItem.PSS_MGF_NAME_STR); + console.info("mgf == " + mgf); + let mgf1Md = signer.getSignSpec(cryptoFramework.SignSpecItem.PSS_MGF1_MD_STR); + console.info("mgf1Md == " + mgf1Md); + signer.update(input1, function (err, data) { + signer.sign(input2, function (err, data) { + // Before signature verification initialization, set and obtain PSS parameters. The functions are the same as those after initialization. + signMessageBlob = data; + AlertDialog.show({message : "res" + signMessageBlob.data}); + let setN = 32; + verifyer.setVerifySpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, setN); + let saltLen = verifyer.getVerifySpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM); + console.info("SaltLen == " + saltLen); + let tf = verifyer.getVerifySpec(cryptoFramework.SignSpecItem.PSS_TRAILER_FIELD_NUM); + console.info("trailer field == " + tf); + let md = verifyer.getVerifySpec(cryptoFramework.SignSpecItem.PSS_MD_NAME_STR); + console.info("md == " + md); + let mgf = verifyer.getVerifySpec(cryptoFramework.SignSpecItem.PSS_MGF_NAME_STR); + console.info("mgf == " + mgf); + let mgf1Md = verifyer.getVerifySpec(cryptoFramework.SignSpecItem.PSS_MGF1_MD_STR); + console.info("mgf1Md == " + mgf1Md); + verifyer.init(globalKeyPair.pubKey, function (err, data) { + verifyer.update(input1, function(err, data) { + verifyer.verify(input2, signMessageBlob, function(err, data) { + AlertDialog.show({message : "res " + data}); + }) + }); + }); + }); + }); + }); + }); +} +``` + +## Key Agreement -1. Create an **Md** instance. -2. Add one or more segments of data for generating a digest. -3. Compute a digest. -4. Obtain the algorithm and length of a digest. +### When to Use -**Available APIs** +Key agreement allows two parties to establish a shared secret over an insecure channel. + +> **NOTE** +> +> From API version 10, the string parameter without the key length is supported in key agreement. + +### Available APIs For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). +|Instance|API|Description| +|---|---|---| +|cryptoFramework|createKeyAgreement(algName : string) : KeyAgreement|Creates a **KeyAgreement** instance.| +|KeyAgreement|generateSecret(priKey : PriKey, pubKey : PubKey, callback : AsyncCallback\) : void|Generates a shared secret. This API uses an asynchronous callback to return the result.| +|KeyAgreement|generateSecret(priKey : PriKey, pubKey : PubKey) : Promise\|Generates a shared secret. This API uses a promise to return the result.| + +### How to Develop + +1. Generate an ECC key.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair. +2. Generate a shared secret by using the private and public ECC keys. + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +let globalKeyPair; + +function ecdhPromise() { + let eccGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); + let eccKeyAgreement = cryptoFramework.createKeyAgreement("ECC256"); // ECC is supported for key agreement from API version 10. + let keyGenPromise = eccGenerator.generateKeyPair(); + keyGenPromise.then( keyPair => { + globalKeyPair = keyPair; + return eccKeyAgreement.generateSecret(keyPair.priKey, keyPair.pubKey); + }).then((secret) => { + console.info("ecdh output is " + secret.data); + }).catch((error) => { + console.error("ecdh error."); + }); +} + +function ecdhCallback() { + let eccGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); + let eccKeyAgreement = cryptoFramework.createKeyAgreement("ECC256"); + eccGenerator.generateKeyPair(function (err, keyPair) { + globalKeyPair = keyPair; + eccKeyAgreement.generateSecret(keyPair.priKey, keyPair.pubKey, function (err, secret) { + if (err) { + console.error("ecdh error."); + return; + } + console.info("ecdh output is " + secret.data); + }); + }); +} +``` + +## Message Digest + +### When to Use + +A message digest (MD) is a fixed size numeric representation of the content of a message, computed by a hash function. It is sent with the message. The receiver can generate a digest for the message and compare it with the digest received. If the two digests are the same, the message integrity is verified. + +Typical MD operations involve the following: + +1. Create an **Md** instance with the specified digest algorithm (such as SHA-256). +2. Pass in one or more messages for generating a digest, and generate a digest. +3. Obtain the digest algorithm and digest length (in bytes). + +### Available APIs + +For more information about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). + | Instance | API | Description | | --------------- | ------------------------------------------------------------ | -------------------------------------------------- | -| cryptoFramework | function createMd(algName : string) : Md; | Creates an **Md** instance. | +| cryptoFramework | function createMd(algName : string) : Md; | Creates an **Md** instance with the specified algorithm. | | Md | update(input : DataBlob, callback : AsyncCallback\) : void; | Updates the data for a digest. This API uses an asynchronous callback to return the result.| | Md | update(input : DataBlob) : Promise\; | Updates the data for a digest. This API uses a promise to return the result. | | Md | digest(callback : AsyncCallback\) : void; | Generates the digest. This API uses an asynchronous callback to return the result. | @@ -1122,226 +1689,155 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry | Md | getMdLength() : number; | Obtains the digest length based on the specified digest algorithm. | | Md | readonly algName : string; | Obtains the digest algorithm. | -**How to Develop** +### Generating a Digest -1. Call **createMd()** to create an **Md** instance. -2. Call **update()** to pass in the data for computing a digest. **update()** can be called multiple times to pass in the data by segment. -3. Call **digest()** to compute a digest. +1. Use **createMd()** to create an **Md** instance. +2. Use **update()** to pass in data. **update()** can be called multiple times. The algorithm library does not limit the data length of a single **update()**. +3. Use **digest()** to compute a digest. 4. Obtain the digest algorithm and length of the digest generated. -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" -// Convert string into uint8Arr. +// Convert strings in plaintext into byte streams. function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - var tmpUint8Array = new Uint8Array(arr); - return tmpUint8Array; -} - -// Generate a dataBlob of the given length. -function GenDataBlob(dataBlobLen) { - var dataBlob; - if (dataBlobLen == 12) { - dataBlob = {data: stringToUint8Array("my test data")}; - } else { - console.error("GenDataBlob: dataBlobLen is invalid"); - dataBlob = {data: stringToUint8Array("my test data")}; + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); } - return dataBlob; + return new Uint8Array(arr); } -// Compute an MD using promise-based APIs. -function doMdByPromise(algName) { - var md; +// Generate a digest in promise mode. +function doMdByPromise() { + let mdAlgName = "SHA256"; // Digest algorithm name. + let message = "mdTestMessgae"; // Data to be digested. + let md; + let mdOutput; try { - md = cryptoFramework.createMd(algName); + md = cryptoFramework.createMd(mdAlgName); } catch (error) { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); + return; } - console.error("[Promise]: Md algName is: " + md.algName); - // Initial update(). - var promiseMdUpdate = md.update(GenDataBlob(12)); + console.info("[Promise]: Md algName is: " + md.algName); + // If the data volume is small, you can use update() once to pass in all data. There is no limit on the length of the input parameter. + let promiseMdUpdate = md.update({ data: stringToUint8Array(message) }); promiseMdUpdate.then(() => { - // Call update() multiple times based on service requirements. - promiseMdUpdate = md.update(GenDataBlob(12)); - return promiseMdUpdate; - }).then(mdOutput => { - var PromiseMdDigest = md.digest(); + // Call digest() to return the result. + let PromiseMdDigest = md.digest(); return PromiseMdDigest; - }).then(mdOutput => { - console.error("[Promise]: MD result: " + mdOutput.data); - var mdLen = md.getMdLength(); - console.error("[Promise]: MD len: " + mdLen); + }).then(digestOutput => { + mdOutput = digestOutput; + console.info("[Promise]: MD result: " + mdOutput.data); + let mdLen = md.getMdLength(); + console.info("[Promise]: MD len: " + mdLen); }).catch(error => { console.error("[Promise]: error: " + error.message); }); } -// Compute an MD using callback-based APIs. -function doMdByCallback(algName) { - var md; +// Generate a digest in callback mode. +function doMdByCallback() { + let mdAlgName = "SHA256"; // Digest algorithm name. + let message = "mdTestMessgae"; // Data to be digested. + let md; + let mdOutput; try { - md = cryptoFramework.createMd(algName); + md = cryptoFramework.createMd(mdAlgName); } catch (error) { console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); } - console.error("[Callback]: Md algName is: " + md.algName); - // Initial update(). - md.update(GenDataBlob(12), (err,) => { + console.info("[Callback]: Md algName is: " + md.algName); + // If the data volume is small, you can use update() once to pass in all data. There is no limit on the length of the input parameter. + md.update({ data: stringToUint8Array(message) }, (err,) => { if (err) { console.error("[Callback]: err: " + err.code); } - // Call update() multiple times based on service requirements. - md.update(GenDataBlob(12), (err1,) => { + md.digest((err1, digestOutput) => { if (err1) { console.error("[Callback]: err: " + err1.code); + } else { + mdOutput = digestOutput; + console.info("[Callback]: MD result: " + mdOutput.data); + let mdLen = md.getMdLength(); + console.info("[Callback]: MD len: " + mdLen); } - md.digest((err2, mdOutput) => { - if (err2) { - console.error("[Callback]: err: " + err2.code); - } else { - console.error("[Callback]: MD result: " + mdOutput.data); - var mdLen = md.getMdLength(); - console.error("[Callback]: MD len: " + mdLen); - } - }); }); }); } ``` -The following example demonstrates how to call **update()** multiple times to update the MD. -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" -async function updateData(index, obj, data) { - console.error("update " + (index + 1) + " MB data..."); - return obj.update(data); -} +### Generating a Digest by Segment + +1. Use **createMd()** to create an **Md** instance. +2. Use **update()** multiple times to pass in by segment. +3. Use **digest()** to compute a digest. +4. Obtain the digest algorithm and length of the digest generated. +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +// Convert strings in plaintext into byte streams. function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { arr.push(str.charCodeAt(i)); } - var tmpUint8Array = new Uint8Array(arr); - return tmpUint8Array; -} - -function GenDataBlob(dataBlobLen) { - var dataBlob; - if (dataBlobLen == 12) { - dataBlob = {data: stringToUint8Array("my test data")}; - } else { - console.error("GenDataBlob: dataBlobLen is invalid"); - dataBlob = {data: stringToUint8Array("my test data")}; - } - return dataBlob; + return new Uint8Array(arr); } -function LoopMdPromise(algName, loopSize) { - var md; +// Generate a digest by segment in promise mode. +async function doLoopMdPromise() { + let mdAlgName = "SHA256"; // Digest algorithm name. + let md; + let mdOutput; try { - md = cryptoFramework.createMd(algName); + md = cryptoFramework.createMd(mdAlgName); } catch (error) { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); return; } - console.error("[Promise]: Md algName is: " + md.algName); - var promiseMdUpdate = md.update(GenDataBlob(12)); - promiseMdUpdate.then(() => { - var PromiseMdDigest = md.digest(); - return PromiseMdDigest; - }).then(async () => { - for (var i = 0; i < loopSize; i++) { - await updateData(i, md, GenDataBlob(12)); + console.info("[Promise]: Md algName is: " + md.algName); + let messageText = "aaaaa.....bbbbb.....ccccc.....ddddd.....eee"; // Assume that the message is of 43 bytes. + let messageArr = []; + let updateLength = 20; // For example, pass in 20 bytes in each update(). + + for (let i = 0; i <= messageText.length; i++) { + if ((i % updateLength == 0 || i == messageText.length) && messageArr.length != 0) { + let message = new Uint8Array(messageArr); + let messageBlob = { data : message }; + // Use await to process the update() in the for() loop. + try { + await md.update (messageBlob); // Call update() to process data by segment. + } catch (error) { + console.error("await update error code: " + error.code + ", message is: " + error.message); + return; + } + messageArr = []; } - var PromiseMdDigest = md.digest(); - return PromiseMdDigest; - }).then(mdOutput => { - console.error("[Promise]: MD result: " + mdOutput.data); - var mdLen = md.getMdLength(); - console.error("[Promise]: MD len: " + mdLen); + // Pad messageArr based on the segment length. + if (i < messageText.length) { + messageArr.push(messageText.charCodeAt(i)); + } + } + let PromiseMdDigest = md.digest(); + PromiseMdDigest.then(digestOutput => { + mdOutput = digestOutput; + console.info("[Promise]: MD result: " + mdOutput.data); + let mdLen = md.getMdLength(); + console.info("[Promise]: MD len: " + mdLen); }).catch(error => { console.error("[Promise]: error: " + error.message); }); } ``` -## Performing Key Agreement - -**When to Use** - -Key agreement allows two parties to establish a shared secret over an insecure channel. - -**Available APIs** - -For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). - -|Instance|API|Description| -|---|---|---| -|cryptoFramework|createKeyAgreement(algName : string) : KeyAgreement|Creates a **KeyAgreement** instance.| -|KeyAgreement|generateSecret(priKey : PriKey, pubKey : PubKey, callback : AsyncCallback\) : void|Generates a shared secret. This API uses an asynchronous callback to return the result.| -|KeyAgreement|generateSecret(priKey : PriKey, pubKey : PubKey) : Promise\|Generates a shared secret. This API uses a promise to return the result.| - -**How to Develop** +## HMAC -1. Use **createKeyAgreement()** to create a **KeyAgreement** object for subsequent key agreement operations. -2. Use **generateSecret()** provided by **KeyAgreement** to pass in the peer ECC public key object and the ECC private key object generated locally. +### When to Use -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" - -let globalSelfPriKey; -let globalPeerPubKey; - -function ecdhPromise() { - let peerPubKeyArray = new Uint8Array([48,89,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,3,66,0,4,83,96,142,9,86,214,126,106,247,233,92,125,4,128,138,105,246,162,215,71,81,58,202,121,26,105,211,55,130,45,236,143,55,16,248,75,167,160,167,106,2,152,243,44,68,66,0,167,99,92,235,215,159,239,28,106,124,171,34,145,124,174,57,92]); - let peerPubKeyBlob = { data: peerPubKeyArray }; - let eccGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); - let eccKeyAgreement = cryptoFramework.createKeyAgreement("ECC256"); - eccGenerator.convertKey(peerPubKeyBlob, null).then((peerKeyPair) => { - globalPeerPubKey = peerKeyPair.pubKey; - return eccGenerator.generateKeyPair(); - }).then((keyPair) => { - globalSelfPriKey = keyPair.priKey; - return eccKeyAgreement.generateSecret(globalSelfPriKey, globalPeerPubKey); - }).then((secret) => { - console.info("ecdh promise output is " + secret.data); - }).catch((error) => { - console.error("ecdh error."); - }); -} - -function ecdhCallback() { - let peerPubKeyArray = new Uint8Array([48,89,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,3,66,0,4,83,96,142,9,86,214,126,106,247,233,92,125,4,128,138,105,246,162,215,71,81,58,202,121,26,105,211,55,130,45,236,143,55,16,248,75,167,160,167,106,2,152,243,44,68,66,0,167,99,92,235,215,159,239,28,106,124,171,34,145,124,174,57,92]); - let peerPubKeyBlob = { data: peerPubKeyArray }; - let eccGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); - let eccKeyAgreement = cryptoFramework.createKeyAgreement("ECC256"); - eccGenerator.convertKey(peerPubKeyBlob, null, function (err, peerKeyPair) { - globalPeerPubKey = peerKeyPair.pubKey; - eccGenerator.generateKeyPair(function (err, keyPair) { - globalSelfPriKey = keyPair.priKey; - eccKeyAgreement.generateSecret(globalSelfPriKey, globalPeerPubKey, function (err, secret) { - if (err) { - console.error("ecdh error."); - return; - } - console.info("ecdh callback output is " + secret.data); - }); - }); - }) -} -``` - -## Generating a MAC - -**When to Use** - -A message authentication code (MAC) can be used to verify both the integrity and authenticity of a message using a shared secret. +A hash-based message authentication code (HMAC) can be used to verify both the integrity and authenticity of a message using a shared secret. Typical MAC operations involve the following: @@ -1349,104 +1845,100 @@ Typical MAC operations involve the following: 2. Initialize the **Mac** instance, add one or more segments of data for generating a MAC, and generate a MAC. 3. Obtain the algorithm and length of a MAC. -**Available APIs** +### Available APIs For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). | Instance | API | Description | | --------------- | ------------------------------------------------------------ | --------------------------------------------------- | | cryptoFramework | function createMac(algName : string) : Mac; | Creates a **Mac** instance. | -| Mac | init(key : SymKey, callback : AsyncCallback\) : void; | Initializes the MAC operation. This API uses an asynchronous callback to return the result.| -| Mac | init(key : SymKey) : Promise\; | Initializes the MAC operation. This API uses a promise to return the result. | +| Mac | init(key : SymKey, callback : AsyncCallback\) : void; | Initializes the **Mac** instance. This API uses an asynchronous callback to return the result. | +| Mac | init(key : SymKey) : Promise\; | Initializes the **Mac** instance. This API uses a promise to return the result. | | Mac | update(input : DataBlob, callback : AsyncCallback\) : void; | Updates the data for the MAC operation. This API uses an asynchronous callback to return the result. | | Mac | update(input : DataBlob) : Promise\; | Updates the data for the MAC operation. This API uses a promise to return the result. | -| Mac | doFinal(callback : AsyncCallback\) : void; | Finalizes the MAC operation to generate a MAC. This API uses an asynchronous callback to return the result. | +| Mac | doFinal(callback : AsyncCallback\) : void; | Finalizes the MAC operation to generate a MAC. This API uses an asynchronous callback to return the result. | | Mac | doFinal() : Promise\; | Finalizes the MAC operation to generate a MAC. This API uses a promise to return the result. | | Mac | getMacLength() : number; | Obtains the length of the MAC based on the specified algorithm. | | Mac | readonly algName : string; | Obtains the digest algorithm. | -**How to Develop** +### Generating an HMAC -1. Call **createMac()** to create a **Mac** instance. -2. Call **init()** to initialize the **Mac** instance with the symmetric key passed in. -3. Call **update()** one or more times to add the data for computing a MAC. -4. Call **doFinal()** to generate a MAC. -5. Obtain the algorithm and length of the MAC. +1. Use **createMac()** to create a **Mac** instance. +2. Use **init()** to initialize the **Mac** instance with the symmetric key passed in. +3. Use **update()** to pass in the data for computing an HMAC. +4. Use **doFinal()** to generate an HMAC. +5. Obtain the algorithm and length of the HMAC. -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" -// Convert string into uint8Arr. +// Convert strings in plaintext into byte streams. function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - var tmpUint8Array = new Uint8Array(arr); - return tmpUint8Array; -} - -// Generate a blob. -function GenDataBlob(dataBlobLen) { - var dataBlob; - if (dataBlobLen == 12) { - dataBlob = {data: stringToUint8Array("my test data")}; - } else { - console.error("GenDataBlob: dataBlobLen is invalid"); - dataBlob = {data: stringToUint8Array("my test data")}; + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); } - return dataBlob; + return new Uint8Array(arr); } -function doHmacByPromise(algName) { - var mac; +// Generate an HMAC in promise mode. +function doHmacByPromise() { + let macAlgName = "SHA256"; // Digest algorithm name. + let message = "hmacTestMessgae"; // Data used to generate an HMAC. + let macOutput; + let mac; try { - mac = cryptoFramework.createMac(algName); + mac = cryptoFramework.createMac(macAlgName); } catch (error) { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); } - console.error("[Promise]: Mac algName is: " + mac.algName); - var KeyBlob = { + console.info("[Promise]: Mac algName is: " + mac.algName); + let KeyBlob = { + // 128-bit key data : stringToUint8Array("12345678abcdefgh") } - var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); - var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); + let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); + // Convert the binary data into a key. + let promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); promiseConvertKey.then(symKey => { - var promiseMacInit = mac.init(symKey); + let promiseMacInit = mac.init(symKey); return promiseMacInit; }).then(() => { - // Initial update(). - var promiseMacUpdate = mac.update(GenDataBlob(12)); - return promiseMacUpdate; - }).then(() => { - // Call update() multiple times based on service requirements. - var promiseMacUpdate = mac.update(GenDataBlob(12)); + // If the data volume is small, you can use update() once to pass in all data. There is no limit on the length of the input parameter. + let promiseMacUpdate = mac.update({ data: stringToUint8Array(message) }); return promiseMacUpdate; }).then(() => { - var PromiseMacDoFinal = mac.doFinal(); + let PromiseMacDoFinal = mac.doFinal(); return PromiseMacDoFinal; - }).then(macOutput => { - console.error("[Promise]: HMAC result: " + macOutput.data); - var macLen = mac.getMacLength(); - console.error("[Promise]: MAC len: " + macLen); + }).then(output => { + macOutput = output; + console.info("[Promise]: HMAC result: " + macOutput.data); + let macLen = mac.getMacLength(); + console.info("[Promise]: MAC len: " + macLen); }).catch(error => { console.error("[Promise]: error: " + error.message); }); } -// Generate a MAC using callback-based APIs. -function doHmacByCallback(algName) { - var mac; +// Generate an HMAC in callback mode. +function doHmacByCallback() { + let macAlgName = "SHA256"; // Digest algorithm name. + let message = "hmacTestMessgae"; // Data used to generate an HMAC. + let macOutput; + let mac; try { - mac = cryptoFramework.createMac(algName); + mac = cryptoFramework.createMac(macAlgName); } catch (error) { AlertDialog.show({message: "[Callback]: error code: " + error.code + ", message is: " + error.message}); console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); } - var KeyBlob = { + console.info("[Promise]: Mac algName is: " + mac.algName); + let KeyBlob = { + // 128-bit key data : stringToUint8Array("12345678abcdefgh") } - var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); + let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); + // Convert the binary data into a key. symKeyGenerator.convertKey(KeyBlob, (err, symKey) => { if (err) { console.error("[Callback]: err: " + err.code); @@ -1455,127 +1947,138 @@ function doHmacByCallback(algName) { if (err1) { console.error("[Callback]: err: " + err1.code); } - // Initial update(). - mac.update(GenDataBlob(12), (err2, ) => { + // If the data volume is small, you can use update() once to pass in all data. There is no limit on the length of the input parameter. + mac.update({ data: stringToUint8Array(message) }, (err2, ) => { if (err2) { console.error("[Callback]: err: " + err2.code); } - // Call update() multiple times based on service requirements. - mac.update(GenDataBlob(12), (err3, ) => { + mac.doFinal((err3, output) => { if (err3) { console.error("[Callback]: err: " + err3.code); + } else { + macOutput = output; + console.error("[Callback]: HMAC result: " + macOutput.data); + let macLen = mac.getMacLength(); + console.error("[Callback]: MAC len: " + macLen); } - mac.doFinal((err4, macOutput) => { - if (err4) { - console.error("[Callback]: err: " + err4.code); - } else { - console.error("[Callback]: HMAC result: " + macOutput.data); - var macLen = mac.getMacLength(); - console.error("[Callback]: MAC len: " + macLen); - } - }); }); }); }); }); } ``` -The following example demonstrates how to call **update()** multiple times to update the MAC. -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" -async function updateData(index, obj, data) { - console.error("update " + (index + 1) + " MB data..."); - return obj.update(data); -} +### Generating an HMAC by Segment + +Generate an HMAC by segment. + +1. Use **createMac()** to create a **Mac** instance. +2. Use **init()** to initialize the **Mac** instance with the symmetric key passed in. +3. Call **update()** multiple times to pass in data by segment. +4. Use **doFinal()** to generate an HMAC. +5. Obtain the algorithm and length of the HMAC. + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { arr.push(str.charCodeAt(i)); } - var tmpUint8Array = new Uint8Array(arr); - return tmpUint8Array; -} - -function GenDataBlob(dataBlobLen) { - var dataBlob; - if (dataBlobLen == 12) { - dataBlob = {data: stringToUint8Array("my test data")}; - } else { - console.error("GenDataBlob: dataBlobLen is invalid"); - dataBlob = {data: stringToUint8Array("my test data")}; - } - return dataBlob; + return new Uint8Array(arr); } -function LoopHmacPromise(algName, loopSize) { - var mac; +function doLoopHmacPromise() { + let macAlgName = "SHA256"; // Digest algorithm name. + let macOutput; + let mac; try { - mac = cryptoFramework.createMac(algName); + mac = cryptoFramework.createMac(macAlgName); } catch (error) { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); return; } - console.error("[Promise]: Mac algName is: " + mac.algName); - var KeyBlob = { + console.info("[Promise]: Mac algName is: " + mac.algName); + let KeyBlob = { + // 128-bit key data : stringToUint8Array("12345678abcdefgh") } - var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); - var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); + let messageText = "aaaaa.....bbbbb.....ccccc.....ddddd.....eee"; // Assume that the message is of 43 bytes. + let updateLength = 20; // For example, pass in 20 bytes in each update(). + let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); + // Convert the binary data into a key. + let promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); promiseConvertKey.then(symKey => { - var promiseMacInit = mac.init(symKey); + let promiseMacInit = mac.init(symKey); return promiseMacInit; }).then(async () => { - for (var i = 0; i < loopSize; i++) { - await updateData(i, mac, GenDataBlob(12)); + let promiseMacUpdate; + let messageArr = []; + for (let i = 0; i <= messageText.length; i++) { + if ((i % updateLength == 0 || i == messageText.length) && messageArr.length != 0) { + let message = new Uint8Array(messageArr); + let messageBlob = { data : message }; + // Use await to process the update() in the for() loop. + try { + promiseMacUpdate = await mac.update(messageBlob); // Invoke update() multiple times. + } catch (error) { + console.error("await update error code: " + error.code + ", message is: " + error.message); + return; + } + messageArr = []; + } + // Pad messageArr based on the segment length. + if (i < messageText.length) { + messageArr.push(messageText.charCodeAt(i)); + } } - var promiseMacUpdate = mac.update(GenDataBlob(12)); return promiseMacUpdate; }).then(() => { - var PromiseMacDoFinal = mac.doFinal(); + let PromiseMacDoFinal = mac.doFinal(); return PromiseMacDoFinal; - }).then(macOutput => { - console.error("[Promise]: HMAC result: " + macOutput.data); - var macLen = mac.getMacLength(); - console.error("[Promise]: MAC len: " + macLen); + }).then(output => { + macOutput = output; + console.log("[Promise]: HMAC result: " + macOutput.data); + let macLen = mac.getMacLength(); + console.log("[Promise]: MAC len: " + macLen); }).catch(error => { console.error("[Promise]: error: " + error.message); }); } ``` +## Random Number -## Generating a Random Number - -**When to Use** +### When to Use Typical random number operations involve the following: -- Generate a random number. -- Set a seed based on the random number generated. +1. Create a **Random** instance and specify the length (in bytes) of the random number to generate a secure random number of the specified length (ranging from **1** to **INT_MAX**). +2. Set a seed based on the random number generated. -**Available APIs** +### Available APIs -For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). +For more information about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). -| Instance | API | Description | -| --------------- | ------------------------------------------------------------ | ---------------------------------------------- | -| cryptoFramework | function createRandom() : Random; | Creates a **Random** instance. | -| Random | generateRandom(len : number, callback: AsyncCallback\) : void; | Generates a random number. This API uses an asynchronous callback to return the result. | -| Random | generateRandom(len : number) : Promise\; | Generates a random number. This API uses a promise to return the result. | -| Random | setSeed(seed : DataBlob) : void; | Sets a seed. | +| Instance | API | Description | +| --------------- | ------------------------------------------------------------ | ------------------------------------------ | +| cryptoFramework | function createRandom() : Random; | Creates a **Random** instance. | +| Random | generateRandom(len : number, callback: AsyncCallback\) : void; | Generates a random number. This API uses an asynchronous callback to return the result.| +| Random | generateRandom(len : number) : Promise\; | Generates a random number. This API uses a promise to return the result. | +| Random | generateRandomSync(len: number): DataBlob; | Generates a random number of the specified length synchronously. | +| Random | setSeed(seed : DataBlob) : void; | Sets a seed. | -**How to Develop** +### How to Develop -1. Call **createRandom()** to create a **Random** instance. -2. Call **generateRandom()** to generate a random number of the given length. -3. Call **setSeed()** to set a seed. +1. Use **createRandom()** to create a **Random** instance. +2. Use **generateRandom()** to generate a random number of the given length. +3. Use **setSeed()** to set a seed. -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" -// Generate a random number and set a seed using promise-based APIs. +// Generate a random number in promise mode. function doRandByPromise(len) { var rand; try { @@ -1596,7 +2099,7 @@ function doRandByPromise(len) { }); } -// Generate a random number and set a seed using callback-based APIs. +// Generate a random number in callback mode. function doRandByCallback(len) { var rand; try { @@ -1617,4 +2120,25 @@ function doRandByCallback(len) { } }); } + +// Generate a random number synchronously. +function doRandBySync(len) { + var rand; + try { + rand = cryptoFramework.createRandom(); + } catch (error) { + console.error("[Sync]: error code: " + error.code + ", message is: " + error.message); + } + + try { + let randData = rand.generateRandomSync(len); + if (randData != null) { + console.info("[Sync]: rand result: " + randData.data); + } else { + console.error("[Sync]: get rand result fail!"); + } + } catch (error) { + console.error("[Sync]: error: " + error.message); + } +} ``` diff --git a/en/application-dev/security/cryptoFramework-overview.md b/en/application-dev/security/cryptoFramework-overview.md index 72bbb1148908d177498d54cfc9585c12b3b1d73f..dc44626d8429376093bd476e7e43d7364a8677bf 100644 --- a/en/application-dev/security/cryptoFramework-overview.md +++ b/en/application-dev/security/cryptoFramework-overview.md @@ -1,175 +1,244 @@ # Crypto Framework Overview -The cryptographic (crypto for shot) framework shields the implementation differences of third-party cryptographic algorithm libraries and implements encryption and decryption, signing and signature verification, and operations of the message authentication code (MAC), hashes, and secure random numbers. You can use the APIs provided by this framework to implement cipher development quickly. +The Cryptographic (Crypto for shot) Framework shields the implementation differences of third-party cryptographic algorithm libraries and implements encryption and decryption, digital signature and signature verification, message authentication code (MAC) generation, hashes, and generation of secure random numbers. You can use the APIs provided by this framework to implement cipher development quickly. > **NOTE** > -> The crypto framework provides cryptographic operations on keys, but not key management. It is used when the application keeps the key securely (for example, temporary session keys are used only in the memory or the application implements secure key storage). If the system is required to provide key management (such as key storage), use the [HUKS](huks-overview.md). +> The Crypto Framework provides cryptographic operations, but not key management. It can be used when temporary session keys are used only in the memory or the applications implement secure key storage. If the system is required to provide key management (such as key storage), use the [HUKS](huks-overview.md). ## Working Principles -The crypto framework provides components in the following layers: -- Interface layer: provides unified JS interface externally. +The Crypto Framework provides components in the following layers: + +- Interface layer: provides unified JavaScript interfaces externally. - Plug-in layer: implements third-party algorithm libraries. -- Framework layer: loads plug-ins at the plug-in layer to adapt to third-party algorithm libraries and shield implementation differences between these libraries. +- Framework layer: flexibly loads plug-ins at the plug-in layer to adapt to third-party algorithm libraries and shield differences between these libraries. ## Basic Concepts -**Symmetric Key** + +### Symmetric Key A symmetric key is a key used both to encrypt and decrypt data. In symmetric encryption, the sender converts information in plaintext into ciphertext using a key and certain algorithm for security purposes. The receiver converts the ciphertext into plaintext using the same key and algorithm. -- AES +- **AES key** - Advanced Encryption Standard (AES) is the most common symmetric encryption algorithm. AES is a block cipher. A block cipher divides plaintext into fixed-length groups of bits, called blocks. A block is encrypted each time until the entire plaintext is encrypted. The block size in AES is 128 bits. That is, each block contains 16 bytes (8 bits/byte). The key length can be 128 bits, 192 bits, or 256 bits. -- 3DES - - Triple Data Encryption Standard (3DES), also called 3DESede or Triple DES, applies the DES cipher three times to each data block. It uses three 64-bit keys to encrypt a data block three times. Compared with DES, 3DES provides higher security due to longer key length, but its processing speed is lower. The AES is faster and more secure than 3DES. + Advanced Encryption Standard (AES) is the most common symmetric encryption algorithm. AES is a block cipher, which divides plaintext into fixed-length groups of bits, called blocks. A block is encrypted each time until the entire plaintext is encrypted. The block size in AES is 128 bits. That is, each block contains 16 bytes (8 bits/byte). The AES key length can be 128 bits, 192 bits, or 256 bits. -**Asymmetric Key** +- **3DES key** -In the asymmetric cryptography, a private and public key pair is required. The private key is used to encrypt the plaintext, and the public key is used to decrypt the ciphertext. The public key is public and open to anyone in the system, while the private key is private. For signing and signature verification, the private key is used to sign the plaintext, and the public key is used to verify the signature data. + Triple Data Encryption Standard (3DES), also called 3DESede or Triple DES, applies the DES cipher three times to each data block. It uses three 64-bit keys to encrypt a data block three times. Compared with DES, 3DES provides higher security due to longer key length, but lower processing speed. AES is faster and more secure than 3DES. -- RSA key +### Asymmetric Key - The security of RSA relies on the factoring problem, that is, the difficulty of factoring the product of two large prime numbers. The keys for the RSA algorithm are generated as follows: +In the asymmetric cryptography, a private and public key pair is required. The private key is used to encrypt the plaintext, and the public key is used to decrypt the ciphertext. The public key is public and open to anyone in the system, while the private key is private. For digital signature and signature verification, the private key is used to sign the plaintext, and the public key is used to verify the signature data. - 1. Generate two large prime numbers **p** and **q**. - - 2. Compute **n** = **p** x **q**. - - **n** is used as the modulus for both the public and private keys, and is released as part of the public key. - - 3. Choose an integer **e** such that 1 < **e** < (**p** - 1) x (**q** - 1), that is, **e** and (**p** - 1) x (**q** - 1) are coprime. - - 4. Compute **d**. **e** x **d** - 1 is a multiple of (**p** - 1) and (**q** - 1). - - The public key consists of the modulus **n** and the public exponent **e**. The private key consists of **n** and the private exponent **d**. - - In addition to the default RSA key generation from two primes, the crypto framework provides key generation from multiple primes. You can set the **primes** parameter (PRIMES_2, PRIMES_3, PRIMES_4, PRIMES_5) to specify the number of primes during key generation. The keys generated from multiple primes help reduce the computation workload in decryption and signing (Chinese remainder theorem). However, such keys are weak. The algorithm library defines specifications based on the rules for using OpenSSL prime numbers. For details, see [**Constraints**](#constraints). - -- ECC key - - Elliptic-Curve Cryptography (ECC) is a public-key encryption based on the algebraic structure of elliptic curve over finite fields. The crypto framework provides a variety of ECC key generation capabilities. +- **RSA key** + + Rivest-Shamir-Adleman (RSA) is an asymmetric encryption algorithm widely used for secure data transmission. The security of RSA depends on the practical difficulty of factoring the product of two large prime numbers. + + The RSA key parameters include the following integers: + + **n**: modulus, which is a public parameter of the private key and public key. + + **sk**: private exponent, which is often written as **d** in the formula. + + **pk**: public exponent, which is often written as **e** in the formula. + +- **ECC key** + + Elliptic-curve cryptography (ECC) is a public-key encryption algorithm based on elliptic curve mathematics. It security is based on the assumption that it is infeasible to find the discrete logarithm of a random elliptic curve element with respect to a publicly known base point. The Crypto Framework provides capabilities for generating a variety of ECC keys. + + The ECC algorithm can be regarded as an operation of numbers defined in a special set. Currently, the Crypto Framework supports elliptic curves in **Fp** fields, where **p** is prime. The **Fp** fields are also called the prime fields. + + The ECC key parameters in the **Fp** fields include the following: + + **p**: prime number used to determine **Fp**. + + **a**, **b**: determine the elliptic curve equation. -**Encryption and Decryption** + **g**: base point of the elliptic curve, which can be represented as **gx** or **gy**. -- Symmetric AES encryption and decryption + **n**: order of the base point **g**. + + **h**: cofactor. + + **sk**: private key, which is a random integer less than **n**. + + **pk**: public key, which is a point on the elliptic curve. **pk** = **sk** x **g**. + +- **DSA key** + + Digital Signature Algorithm (DSA) is a public-key algorithm based on the modular exponentiation and discrete logarithm problem. It is used for digital signatures and signature verification, but not for encryption and decryption. The Crypto Framework provides the capability of generating DSA keys of different lengths. + + The DSA key parameters include the following: + + **p**: a prime modulus, whose length is an integer multiple of 64. + + **q**: prime factor of p – 1. The length varies depending on the length of **p**. + + **g**: g = (h ^ ((p - 1) / q)) mod p, where **h** is any integer that meets 1 < h < p -1. + + **sk**: private key, which is a randomly generated integer and complies with 0 < sk < q. + + **pk**: public key. pk = (g ^ sk) mod p + +### Encryption and Decryption + +- **Symmetric AES encryption and decryption** The algorithm library provides the following cipher modes of operation for AES: ECB, CBC, OFB, CFB, CTR, GCM, and CCM. AES is a block cipher, with a fixed block size of 128 bits. In actual applications, the last block of plaintext may be less than 128 bits and needs to be padded. The padding options are as follows: - - **NoPadding**: no padding. - - **PKCS5**: pads a block cipher with a block size of 8 bytes - - **PKCS7**: The PKCS #7 padding scheme is the same as that of PKCS #5 padding except that PKCS #5 padding is defined for 8-byte block sizes, while PKCS #5 padding works for any block size from 1 to 255 bytes. + - **NoPadding**: no padding. + - **PKCS5**: pads a block cipher with a block size of 8 bytes. + - **PKCS7**: pads any block size from 1 to 255 bytes. The PKCS #7 padding scheme is the same as that of PKCS #5. - > **NOTE**
In ECB and CBC, the plaintext must be padded if its length is not an integer multiple of 128 bits. Since the plaintext is padded to the block size, the PKCS #5 and PKCS #7 used in the algorithm library use the block size as the padding length. That is, data is padded to 16 bytes in AES encryption. - -- **Symmetric 3DES Encryption and Decryption** + > **NOTE** + > + > In ECB and CBC modes, the plaintext must be padded if its length is not an integer multiple of 128 bits.
+ > Since the plaintext is padded to the block size, the PKCS #5 and PKCS #7 used in the algorithm library use the block size as the padding length. That is, data is padded to 16 bytes in AES encryption. + +- **Symmetric 3DES encryption and decryption** 3DES encryption and decryption apply the DES cipher three times to each data block to obtain the ciphertext or plaintext. The algorithm library provides the following cipher modes of operation for 3DES encryption and decryption: ECB, CBC, OFB, and CFB. DES is a block cipher, with a fixed block size of 64 bits. In actual applications, the last block of plaintext may be less than 64 bits and needs to be padded. The padding options are as follows: - - **NoPadding**: no padding. - - **PKCS5**: pads a block cipher with a block size of 8 bytes - - **PKCS7**: The PKCS #7 padding scheme is the same as that of PKCS #5 padding except that PKCS #5 padding is defined for 8-byte block sizes, while PKCS #5 padding works for any block size from 1 to 255 bytes. - - > **NOTE**
In ECB and CBC, the plaintext must be padded if its length is not an integer multiple of 64 bits.
Since the plaintext is padded to the block size, the PKCS #5 and PKCS #7 used in the algorithm library use the block size as the padding length. That is, data is padded to 8 bytes in 3DES encryption. - -- **Asymmetric RSA Encryption and Decryption** - - After the RSA public key (n, e) and private key (n, d) are held, the RSA encryption process is as follows: - - Ciphertext = Plaintext ^ **e** mod **n** - - The decryption process is as follows: - - Plaintext = Ciphertext ^ **d** mod **n** - - The algorithm library provides the following modes of operation for RSA encryption and decryption: **PKCS1**, **PKCS1_ OAEP**, and **NoPadding**. RSA is a block cipher, with fixed-length blocks. In actual applications, diverse padding modes are used. The padding options are as follows: - - - **NoPadding**: No padding is required. The length of the input or output data must be the same as that of the RSA key modulus. - - **PKCS1**: PKCS #1 v1.5 is the default padding mode for RSA encryption and decryption. The length of the input data must be less than or equal to the RSA key modulus minus 11, and the length of the output data must be the same as that of the RSA key modulus. - - **PKCS1_OAEP**: The RSA_PKCS1_OAEP_PADDING is a new padding mode provided by PKCS #1. In this mode, two digests (**md** and **mgf1_md**) must be set. The length of the input data must be less than RSA key modulus length minus the **md** length, **mgf1_md** length, and two. The length of the output data must be the same as that of the RSA key modulus. - - > **NOTE** - > - > Length of the RSA key modulus = (Number of RSA bits + 7)/8 - -**Signing and Signature Verification** - -- RSA signing and signature verification - - After the RSA public key (n, e) and private key (n, d) are held, the RSA signature is generated as follows: + - **NoPadding**: no padding. + - **PKCS5**: pads a block cipher with a block size of 8 bytes. + - **PKCS7**: pads any block size from 1 to 255 bytes. The PKCS #7 padding scheme is the same as that of PKCS #5. + + > **NOTE** + > + > In ECB and CBC modes, the plaintext must be padded if its length is not an integer multiple of 64 bits. + > Since the plaintext is padded to the block size, the PKCS #5 and PKCS #7 used in the algorithm library use the block size as the padding length. That is, data is padded to 8 bytes in 3DES encryption. + +- **Asymmetric RSA encryption and decryption** + + RSA is a block cipher, with fixed-length blocks. In actual applications, diverse padding modes are used. Currently, the Crypto Framework provides the following padding modes: + - **NoPadding**: no padding. The length of the input or output data must be the same as that of the RSA key modulus. - Signature = Message ^ **d** mod **n** + - **PKCS1**: RSAES-PKCS1-V1_5 mode in RFC3447 (corresponding to RSA_PKCS1_PADDING in OpenSSL). The RSA converts the source data D into an encryption block (EB). In encryption, the length of the input data must be less than or equal to the RSA key modulus minus 11. The length of the output data is the same as that of the RSA key modulus. - The signature verification process is as follows: + - **PKCS1_OAEP**: RSAES-OAEP mode in RFC 3447 (corresponding to RSA_PKCS1_OAEP_PADDING in OpenSSL). It is a new padding mode developed by PKCS#1. In this mode, two digests (**md** and **mgf1_md**) need to be set. During encryption, the length of the input data must meet the following requirements: - Message = Signature ^ **d** mod **n** + Input data length < RSA key modulus – **md** length (bytes) – **mgf1_md** length (bytes) – 2 - The sender sends the message and the signature signed by the private key. The receiver decrypts the signature using the public key to verify the signature. Generally, the message sent is longer than the RSA key modulus. Therefore, the crypto framework provides two padding modes to extract the hash value of the message digest before signing the message. The crypto framework provides the following padding modes for signing and signature verification: + The length of the output data is the same as that of the RSA key modulus. In this mode, you can also set the **pSource** byte stream to define the encoding input **P** filled by OAEP and obtain the parameters related to PKCS1_OAEP. - - **PKCS1**: PKCS #1 v1.5 is the default padding mode for RSA encryption and decryption. When this mode is used, the digest (**md**) must be set. - - **PSS**: The PSS mode is a padding algorithm based on the RSA algorithm. When it is used, the digest (**md**) and mask function (**mgf1_md**) are required. + The **PKCS1_OAEP** parameters include the following: + **md**: message digest algorithm.
+ **mgf**: mask generation algorithm. Currently, only MGF1 is supported.
+ **mgf1_md**: mgf1 digest algorithm.
+ **pSource**: byte stream, which is the source for encoding input P in OAEP padding. -- ECDSA + > **NOTE** + > + > RSA key modulus = (RSA bits + 7)/8 - The Elliptic Curve Digital Signature Algorithm (ECDSA) is a Digital Signature Algorithm (DSA) that uses the ECC. Compared with the ordinary Discrete Logarithm Problem (DLP) and Integer Factorization Problem (IFP), the ECC provides a higher unit bit strength than other public-key cryptographic systems. The crypto framework provides the ECDSA that combines multiple elliptic curve and digest algorithms. +### Signing and Signature Verification -**Key Agreement** +- **RSA signing and signature verification** -- **ECDH** + The Crypto Framework provides the following padding modes for RSA signing and signature verification: + - **PKCS1**: RSASSA-PKCS1-V1_5 mode in RFC3447 (corresponding to RSA_PKCS1_PADDING in OpenSSL). When this mode is used for signing and signature verification, the digest (**md**) must be set, the digest algorithm output length (bytes) must be less than the RSA key modulus. + - **PSS**: RSASSA-PSS mode in RFC 3447 (corresponding to RSA_PKCS1_PSS_PADDING in OpenSSL). In this mode, two digests (**md** and **mgf1_md**) must be set, and the total length (bytes) of **md** and **mgf1_md** must be less than the RSA key modulus. In this mode, the salt length (**saltLen**, in bytes) can also be set, and PSS-related parameters can be obtained.
+ The PSS parameters include the following:
+ **md**: message digest algorithm.
+ **mgf**: mask generation algorithm. Currently, only MGF1 is supported.
+ **mgf1_md**: digest algorithm used in the MGF1 algorithm.
+ **saltLen**: salt length, in bytes.
+ **trailer_field**: integer used for encoding. The value must be **1**. - Elliptic Curve Diffie-Hellman (ECDH) allows two parties to establish a shared secret over an insecure channel. The crypto framework provides a variety of ECDH capabilities based on the open-source algorithm library. + > **NOTE** + > + > RSA key modulus = (RSA bits + 7)/8 -**Digest** +- **ECDSA** + + The Elliptic Curve Digital Signature Algorithm (ECDSA) is a digital signature algorithm that uses the ECC. Compared with the ordinary Discrete Logarithm Problem (DLP) and Integer Factorization Problem (IFP), the ECC provides a higher unit bit strength than other public-key cryptographic systems. The Crypto Framework provides the ECDSA that combines multiple elliptic curves and digest algorithms. + +- **DSA** + + The DSA security is based on the difficulty of the DLP in integer finite field. The DSA features high compatibility and applicability. + +### Key Agreement + +**ECDH** + +Elliptic Curve Diffie-Hellman (ECDH) allows two parties to establish a shared secret over an insecure channel. The Crypto Framework provides a variety of ECDH capabilities based on the open-source algorithm library. + +### Message Digest + +The message digest (MD) algorithm allows a fixed-length digest to be generated from data of arbitrary size by using the hash algorithm. It is used for sensitive information encryption because it is infeasible to invert or reverse the computation. The MD algorithm is also referred to as a hash algorithm or a one-way hash algorithm. -The message digest algorithm allows a fixed-length digest to be generated from data of arbitrary size by using the hash algorithm. It is used for sensitive information encryption because it is infeasible to invert or reverse the computation. The MD algorithm is also referred to as a hash algorithm or a one-way hash algorithm. When the same digest algorithm is used, the generated digest (hash value) has the following features: - The same message always results in the same hash value. - The digest generated is of the fixed length no matter the length of messages. (The digest length is determined by the algorithm used). - It is almost impossible to find two different messages with the same hash value. (The probability still exists, depending on the length of the digest.) -There are three types of message digest algorithms: MD, SHA, and MAC. For details, see **HMAC**. +There are three types of message digest algorithms: MD, SHA, and MAC. For details, see section "HMAC". + MD algorithms include MD2, MD4, and MD5. + Major SHA algorithms include SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512. -**HMAC** +### HMAC -Hash-based Message Authentication Code (HMAC) is a key-based message authentication code algorithm. HMAC provides authentication using a shared secret instead of using a digital signature. The MAC generated can be used to verify the integrity and authenticity of the message. The length of the MAC generated by HMAC is fixed. Compared with MAC, HMAC introduces the shared secret, which ensures data correctness. +Hash-based Message Authentication Code (HMAC) is a key-based message authentication code algorithm. It provides authentication using a shared secret instead of using a digital signature. The MAC generated can be used to verify the integrity and authenticity of the message. The length of the MAC generated by HMAC is fixed. Compared with MAC, HMAC introduces the shared secret, which ensures data correctness. -**Random Number** +### Random Number Random numbers are mainly used to generate temporary session keys or keys in asymmetric encryption. They are generated by a hardware random number generator or software-based pseudo-random number generator. In encryption and decryption, a secure random number generator must feature randomness, unrepeatability, and unpredictability. The random numbers generated by the Cryptography Secure Random Number Generator (CSPRNG) meet the requirements of cryptography security pseudo-randomness. - Internal state
A value in the random number generator memory. The same internal state produces the same sequence of the random number. - Seed
A number used to initialize the internal state of a pseudorandom number generator. The random number generator generates a series of random sequences based on the seeds. - ## Constraints -- The crypto framework does not support concurrent operations of multiple threads. +- The Crypto Framework does not support concurrent operations of multiple threads. - Currently, the algorithm library supports only OpenSSL. +- For a key generated based on key parameters, the bigint type must be a positive number in big-endian format. +- The Crypto Framework algorithm library provides common algorithms. Some algorithms and specifications, such as MD5, are not applicable to security scenarios. You need to select the proper algorithms as required. -### Key Generation Specifications +## Key Generation Specifications -**Symmetric Key Generation Specifications** +A key can be generated based on either of the following specifications: +- String parameter: provides the specifications of the key to be generated in the form of a string. +- Key parameters: constructs a key object using the specific cryptography information. -- The following parameters are supported: +### AES Key Generation Specifications - |Symmetric Key Algorithm|Key Length (Bit)|String Parameter| - |---|---|---| - |3DES|192|3DES192| - |AES|128|AES128| - |AES|192|AES192| - |AES|256|AES256| +The AES key can be generated based on a string parameter. + +|Symmetric Key Algorithm|Key Length (Bit)|String Parameter| +|---|---|---| +|AES|128|AES128| +|AES|192|AES192| +|AES|256|AES256| + +> **NOTE** +> +> As a combination of the symmetric key algorithm and the key length, the string parameter specifies the key specifications when a symmetric key generator is created. - > **NOTE**
**String Parameter** is a combination of **Symmetric Key Algorithm** and **Key Length**. It specifies the key specifications when a symmetric key generator is created. +### 3DES Key Generation Specifications -**Asymmetric Key Generation Specifications** -- **RSA key generation** +The 3DES key can be generated based on a string parameter. - The following parameters are supported: +|Symmetric Key Algorithm|Key Length (Bit)|String Parameter| +|---|---|---| +|3DES|192|3DES192| - |Asymmetric Key Type|Number of Primes|String Parameter| +> **NOTE** +> +> As a combination of the symmetric key algorithm and the key length, the string parameter specifies the key specifications when a symmetric key generator is created. + +### RSA Key Generation Specifications + + > **NOTE** + > + > The RSA keys can be generated based on key parameters from API version 10. + +- The RSA key can be generated based on a string parameter. + + |RSA Key Type|Number of Primes|String Parameter| |---|---|---| |RSA512|2|RSA512\|PRIMES_2| |RSA768|2|RSA768\|PRIMES_2| @@ -187,48 +256,154 @@ Random numbers are mainly used to generate temporary session keys or keys in asy |RSA8192|4|RSA8192\|PRIMES_4| |RSA8192|5|RSA8192\|PRIMES_5| - > **NOTE**
When an RSA asymmetric key is generated, the default prime number is 2, and **PRIMES_2** is optional. + > **NOTE** + > + > As a combination of the RSA key type and the number of primes, the string parameter specifies the key specifications when an asymmetric key generator is created. + > + > The default number of primes for generating the RSA asymmetric key is 2, and **PRIMES_2** can be omitted. -- **ECC key generation** +- The RSA key can also be generated based on key parameters. The following table lists the types of key parameters and cryptography specifications of each key parameter. - The following parameters are supported: + | |Common Parameter|Public Key Parameter|Private Key Parameter|Public/Private Key Pair Parameter| + |---|---------|---|---|---| + |n |× |√ |× |√ | + |pk| |√ | |√ | + |sk| | |× |√ | - |Asymmetric Key Algorithm|Key Length| - |---|---| - |ECC|ECC224| - |ECC|ECC256| - |ECC|ECC384| - |ECC|ECC521| + > **NOTE** + > + > The key parameters are used to specify the key specifications when an asymmetric key generator is created. + > + The preceding table describes the public and private key parameters supported by the Crypto Framework algorithm library for generating RSA keys.
**√** indicates that properties needs to be specified to construct the key parameter.
x indicates that the Crypto Framework currently does not support key generation based on this parameter. + + > **CAUTION** + > + > - RSA does not support random key generation by specifying the public parameter (**n**). + > + > - RSA does not support generation of the private key by specifying private key parameters (**n**, **sk**). + +### ECC Key Generation Specifications + + > **NOTE** + > + > The ECC key can be generated based on key parameters from API version 10. + +- The ECC key can be generated based on a string parameter. + + |Asymmetric Key Algorithm|Key Length (Bit)|Curve Name|String Parameter| + |---|---|---|---| + |ECC|224|NID_secp224r1|ECC224| + |ECC|256|NID_X9_62_prime256v1|ECC256| + |ECC|384|NID_secp384r1|ECC384| + |ECC|521|NID_secp521r1|ECC521| + + > **NOTE** + > + > As a combination of the asymmetric key algorithm and the key Length, the string parameter specifies the key specifications when an asymmetric key generator is created. + > + > Currently, only ECC Fp curves are supported. + +- The ECC key can also be generated based on key parameters. The following table lists the types of key parameters and cryptography specifications of each key parameter. + | |Common Parameter|Public Key Parameter|Private Key Parameter|Public/Private Key Pair Parameter| + |---|---|---|---|---| + |fieldType| √| √| √| √| + |p | √| √| √| √| + |a | √| √| √| √| + |b | √| √| √| √| + |g | √| √| √| √| + |n | √| √| √| √| + |h | √| √| √| √| + |pk | | √| | √| + |sk | | | √| √| + + > **NOTE** + > + > The key parameters specify the key specifications when an asymmetric key generator is created. + > + > The preceding table describes the public and private key parameters supported by the Crypto Framework algorithm library for generating ECC keys. √ indicates that properties need to be specified to construct the key parameter. -### Encryption and Decryption Specifications + > **CAUTION** + > + > - Currently, the ECC supports only the **Fp** fields. Therefore, **fieldType** has a fixed value of **Fp**. **fieldType** and **p** constitute the property **field**, which currently supports only [ECFieldFp](../reference/apis/js-apis-cryptoFramework.md#ecfieldfp10). + > - **g** and **pk** are points on the ECC curve and belong to the [Point](../reference/apis/js-apis-cryptoFramework.md#point10) type. You need to specify the X and Y coordinates. -**Symmetric Encryption and Decryption** +### DSA Key Generation Specifications -- The following symmetric encryption algorithms are supported: + > **NOTE** + > + > From API version 10, the DSA algorithm is supported for key generation, signing, and signature verification. + +- The DSA key can be generated based on a string parameter. - |Algorithm|Block Cipher Mode| String Parameter | + |Asymmetric Key Algorithm|Key Length (Bit)|String Parameter| |---|---|---| - |3DES|ECB|3DES192\|ECB\|[NoPadding\|PKCS5\|PKCS7]| - |3DES|CBC|3DES192\|CBC\|[NoPadding\|PKCS5\|PKCS7]| - |3DES|OFB|3DES192\|OFB\|[NoPadding\|PKCS5\|PKCS7]| - |3DES|CFB|3DES192\|CFB\|[NoPadding\|PKCS5\|PKCS7]| - |AES|ECB|AES[128\|192\|256]\|ECB\|[NoPadding\|PKCS5\|PKCS7]| - |AES|CBC|AES[128\|192\|256]\|CBC\|[NoPadding\|PKCS5\|PKCS7]| - |AES|CTR|AES[128\|192\|256]\|CTR\|[NoPadding\|PKCS5\|PKCS7]| - |AES|OFB|AES[128\|192\|256]\|OFB\|[NoPadding\|PKCS5\|PKCS7]| - |AES|CFB|AES[128\|192\|256]\|CFB\|[NoPadding\|PKCS5\|PKCS7]| - |AES|GCM|AES[128\|192\|256]\|GCM\|[NoPadding\|PKCS5\|PKCS7]| - |AES|CCM|AES[128\|192\|256]\|CCM\|[NoPadding\|PKCS5\|PKCS7]| + |DSA|1024|DSA1024| + |DSA|2048|DSA2048| + |DSA|3072|DSA3072| + + > **NOTE** + > + > As a combination of the asymmetric key algorithm and the key length, the string parameter specifies the key specifications when an asymmetric key generator is created. + +- The DSA key can also be generated based on key parameters. The following table lists the types of key parameters and cryptography specifications of each key parameter. + + | |Common Parameter|Public Key Parameter|Private Key Parameter|Public/Private Key Pair Parameter| + |---|---------|---|---|---| + |p |√ |√ |× |√ | + |q |√ |√ |× |√ | + |g |√ |√ |× |√ | + |pk | |√ | |√ | + |sk | | |× |√ | + + > **NOTE** + > + > The key parameters specify the key specifications when an asymmetric key generator is created. + > + > The preceding table describes the public and private key parameters supported by the Crypto Framework algorithm library for generating DSA keys. + > + > **√** indicates that properties needs to be specified to construct the key parameter.
x indicates that the Crypto Framework currently does not support key generation based on this parameter. + + > **CAUTION** + > + > - DSA does not support generation of the private key by specifying the private key parameters (**p**, **q**, **g**, **sk**). + > - When common parameters (**p**, **q**, **g**) are specified to generate a DSA key pair, the DSA key length must be at least 1024 bits. + +## Encryption and Decryption Specifications + +### Symmetric Encryption and Decryption + + > **NOTE** + > + > The APIs support specifications without the key length for symmetric encryption and decryption from API version 10. + +The following symmetric encryption algorithms are supported. +|Symmetric Encryption and Decryption Algorithm|Block Cipher Mode|String Parameter | +|---|---|---| +|3DES|ECB|3DES192\|ECB\|[NoPadding\|PKCS5\|PKCS7]| +|3DES|CBC|3DES192\|CBC\|[NoPadding\|PKCS5\|PKCS7]| +|3DES|OFB|3DES192\|OFB\|[NoPadding\|PKCS5\|PKCS7]| +|3DES|CFB|3DES192\|CFB\|[NoPadding\|PKCS5\|PKCS7]| +|AES|ECB|AES[128\|192\|256]\|ECB\|[NoPadding\|PKCS5\|PKCS7]| +|AES|CBC|AES[128\|192\|256]\|CBC\|[NoPadding\|PKCS5\|PKCS7]| +|AES|CTR|AES[128\|192\|256]\|CTR\|[NoPadding\|PKCS5\|PKCS7]| +|AES|OFB|AES[128\|192\|256]\|OFB\|[NoPadding\|PKCS5\|PKCS7]| +|AES|CFB|AES[128\|192\|256]\|CFB\|[NoPadding\|PKCS5\|PKCS7]| +|AES|GCM|AES[128\|192\|256]\|GCM\|[NoPadding\|PKCS5\|PKCS7]| +|AES|CCM|AES[128\|192\|256]\|CCM\|[NoPadding\|PKCS5\|PKCS7]| > **NOTE** -> +> > - The options included in the square brackets ([]) are mutually exclusive. -> - **String Parameter** is a combination of **Algorithm** (including the key length), **Block Cipher Mode**, and padding mode. It specifies the symmetric encryption/decryption algorithm specifications when a symmetric encryption/decryption instance is created. +> - As a combination of the algorithm (including the key length), block cipher mode, and padding mode, the string parameter specifies the symmetric encryption/decryption algorithm specifications when a symmetric encryption/decryption instance is created. -**Asymmetric RSA Encryption and Decryption** +### Asymmetric RSA Encryption and Decryption -The crypto framework provides three padding modes for RSA encryption/decryption: **NoPadding**, **PKCS1**, and **PKCS1_OAEP**. -- Parameters for **NoPadding** + > **NOTE** + > + > The APIs support specifications without the key length for asymmetric RSA encryption and decryption from API version 10. + +The Crypto Framework provides three padding modes for RSA encryption/decryption: **NoPadding**, **PKCS1**, and **PKCS1_OAEP**. +- If **NoPadding** is used, the following parameters can be specified. |Asymmetric Key Type| Padding Mode| String Parameter| |---|---|---| @@ -239,8 +414,14 @@ The crypto framework provides three padding modes for RSA encryption/decryption: |RSA3072|NoPadding|RSA3072\|NoPadding| |RSA4096|NoPadding|RSA4096\|NoPadding| |RSA8192|NoPadding|RSA8192\|NoPadding| + |RSA|NoPadding|RSA\|NoPadding| -- Parameters for **PKCS1** + > **NOTE** + > + > - As a combination of the asymmetric key type and the padding mode, the string parameter specifies the asymmetric encryption/decryption algorithm specifications when an asymmetric encryption/decryption instance is created. + > - The RSA key type in the last row of the preceding table does not contain the key length to ensure compatibility with the key generated based on the key parameters. The encryption/decryption operation varies depending on the actual key length. + +- If **PKCS1** is used, the following parameters can be specified. |Asymmetric Key Type| Padding Mode| String Parameter| |---|---|---| @@ -251,174 +432,277 @@ The crypto framework provides three padding modes for RSA encryption/decryption: |RSA3072|PKCS1|RSA3072\|PKCS1| |RSA4096|PKCS1|RSA4096\|PKCS1| |RSA8192|PKCS1|RSA8192\|PKCS1| + |RSA|PKCS1|RSA\|PKCS1| -- Parameters for **PKCS1_OAEP** > **NOTE** - > + > + > - As a combination of the asymmetric key type and the padding mode, the string parameter specifies the asymmetric encryption/decryption algorithm specifications when an asymmetric encryption/decryption instance is created. + > - The RSA key type in the last row of the preceding table does not contain the key length to ensure compatibility with the key generated based on the key parameters. The encryption/decryption operation varies depending on the actual key length. + +- If **PKCS1_OAEP** is used, the following parameters can be specified. + + | Asymmetric Key Type| Padding Mode| Digest| Mask Digest| + |---|---|---|---| + |RSA512|PKCS1_OAEP|MD5| [MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| + |RSA512|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| + |RSA512|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| + |RSA512|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224] + |RSA768|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA768|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA768|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA768|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384]| + |RSA768|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| + |RSA768|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]| + |RSA1024|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA1024|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA1024|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA1024|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA1024|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA1024|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384]| + |RSA2048|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA2048|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA2048|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA2048|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA2048|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA2048|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA3072|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA3072|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA3072|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA3072|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA3072|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA3072|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA4096|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA4096|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA4096|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA4096|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA4096|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA4096|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA8192|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA8192|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA8192|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA8192|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA8192|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA8192|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA|PKCS1_OAEP|Digest algorithm that meets the requirements for length|MGF1_ digest algorithm that meets the requirements for length| + + > **NOTE** + > > - The options included in the square brackets ([]) are mutually exclusive. The options outside the square brackets are fixed values. - > - Combine the asymmetric key type, padding mode, digest, and mask digest, with a vertical bar (|) in between. For example, **RSA2048|PKCS1_OAEP|SHA256|MGF1_SHA256**. + > - As a combination of the asymmetric key type, padding mode, digest, and mask digest with a vertical bar (|) in between, the string parameter specifies the asymmetric encryption/decryption algorithm specifications when an asymmetric encryption/decryption instance is created. For example, **RSA2048|PKCS1_OAEP|SHA256|MGF1_SHA256**. + > - The RSA key type in the last row of the preceding table does not contain the key length to ensure compatibility with the key generated based on the key parameters. The encryption/decryption operation varies depending on the actual key length. + > - The input data must meet the following requirement:
Input data length < RSA key modulus - **md** length - **mgf1_md** length - 2
For example, if the RSA key is 512 bits, SHA-512 is not supported. For details about the definition of the RSA key modulus and digest length, see "Asymmetric RSA encryption and decryption" in [Encryption and Decryption](#encryption-and-decryption). -| Asymmetric Key Type| Padding Mode| Digest| Mask Digest| -|---|---|---|---| -|RSA512|PKCS1_OAEP|MD5| [MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| -|RSA512|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| -|RSA512|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| -|RSA512|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]| -|RSA768|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA768|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA768|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA768|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384]| -|RSA768|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| -|RSA768|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]| -|RSA1024|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384]| -|RSA2048|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512 ]| -|RSA8192|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - - -### Signing and Signature Verification Specifications - -**RSA Signing and Signature Verification** - -The crypto framework provides two padding modes for RSA signing and signature verification: **PKCS1** and **PSS**. -- Parameters for **PKCS1** +- If **PKCS1_OAEP** is used, you can obtain the [OAEP cipher parameter](../reference/apis/js-apis-cryptoFramework.md#cipherspecitem10) and set the encoding input P for OAEP padding. + + | OAEP Parameter|Enum Value| Get()| Set()| + |---|---|---|---| + |md|OAEP_MD_NAME_STR |√| + |mgf|OAEP_MGF_NAME_STR|√| + |mgf1_md|OAEP_MGF1_MD_STR |√| + |pSource|OAEP_MGF1_PSRC_UINT8ARR|√|√| + + > **NOTE** + > + > The preceding table presents the **Get()** and **Set()** capabilities for OAEP parameters supported by the Crypto Framework. **√** indicates that the parameter can be obtained or set. + +## Signing and Signature Verification Specifications + +### RSA Signing and Signature Verification + + > **NOTE** + > + > The APIs support specifications without the key length for RSA signing and signature verification from API version 10. + +The Crypto Framework provides two padding modes for RSA signing and signature verification: **PKCS1** and **PSS**. + +- If **PKCS1** is used, the following parameters can be specified. | Asymmetric Key Type| Padding Mode| Digest| String Parameter| |---|---|---|---| - |RSA512|PKCS1|[MD5\|SHA1\|SHA224\|SHA256\|SHA384]|RSA512\|PKCS1\| [MD5\|SHA1\|SHA224\|SHA256\|SHA384]| + |RSA512|PKCS1|[MD5\|SHA1\|SHA224\|SHA256\|SHA384]|RSA512\|PKCS1\|[MD5\|SHA1\|SHA224\|SHA256\|SHA384]| |RSA768|PKCS1|[MD5\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|RSA768\|PKCS1\|[MD5\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| |RSA1024|PKCS1|[MD5\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|RSA1024\|PKCS1\|[MD5\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| |RSA2048|PKCS1|[MD5\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|RSA2048\|PKCS1\|[MD5\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| |RSA3072|PKCS1|[MD5\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|RSA3072\|PKCS1\|[MD5\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| |RSA4096|PKCS1|[MD5\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|RSA4096\|PKCS1\|[MD5\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| |RSA8192|PKCS1|[MD5\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|RSA8192\|PKCS1\|[MD5\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| + |RSA|PKCS1|Digest algorithm that meets the requirements for length|RSA\|PKCS1\|Digest algorithm that meets the requirements for length| -- Parameters for **PSS** > **NOTE** - > + > > - The options included in the square brackets ([]) are mutually exclusive. The options outside the square brackets are fixed values. - > - Combine the asymmetric key type, padding mode, digest, and mask digest, with a vertical bar (|) in between. For example, **RSA2048|PSS|SHA256|MGF1_SHA256**. + > - The RSA key type in the last row of the preceding table does not contain the key length to ensure compatibility with the key generated based on the key parameters. The signing or signature verification operation varies depending on the actual key length. + > - During RSA signature verification, the output length of the digest algorithm must be less than the RSA key modulus. For example, if the RSA key is 512 bits, SHA-512 is not supported. For details, see "RSA signing and signature verification" in [Signing and Signature Verification](#signing-and-signature-verification). + +- If **PSS** is used, the following parameters can be specified. + + | Asymmetric Key Type| Padding Mode| Digest| Mask Digest| + |---|---|---|---| + |RSA512|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| + |RSA512|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| + |RSA512|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| + |RSA512|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]|RSA512\|PSS\|SHA256\|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]| + |RSA768|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA768|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA768|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA768|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384]| + |RSA768|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| + |RSA768|PSS|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]| + |RSA1024|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA1024|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA1024|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA1024|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA1024|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA1024|PSS|SHA512| [MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384]| + |RSA2048|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA2048|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA2048|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA2048|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA2048|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA2048|PSS|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA3072|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA3072|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA3072|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA3072|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA3072|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA3072|PSS|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA4096|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA4096|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA4096|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA4096|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA4096|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA4096|PSS|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA8192|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA8192|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA8192|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA8192|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA8192|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA8192|PSS|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA|PSS|Digest algorithm that meets the requirements for length|MGF1_ digest algorithm that meets the requirements for length| + + > **NOTE** + > + > - The options included in the square brackets ([]) are mutually exclusive. The options outside the square brackets are fixed values. + > - As a combination of the asymmetric key type, padding mode, digest, and mask digest with a vertical bar (|) in between, the string parameter specifies the asymmetric signing or signature verification algorithm specifications when an asymmetric signing or signature verification instance is created. For example, **RSA2048|PSS|SHA256|MGF1_SHA256**. + > - The RSA key type in the last row of the preceding table does not contain the key length to ensure compatibility with the key generated based on the key parameters. The signing or signature verification operation varies depending on the actual key length. + > - If the PSS padding mode is used in RSA signing or signature verification, the total length (in bytes) of **md** and **mgf1_md** must be less than the RSA key modulus. For example, if the RSA key is 512 bits, **md** and **mgf1_md** cannot be SHA256 at the same time. For details about the definition of the RSA key modulus and digest length, see "RSA signing and signature verification" in [Signing and Signature Verification](#signing-and-signature-verification). -| Asymmetric Key Type| Padding Mode| Digest| Mask Digest| -|---|---|---|---| -|RSA512|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| -|RSA512|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| -|RSA512|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| -|RSA512|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]|RSA512\|PSS\|SHA256\|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]| -|RSA768|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA768|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA768|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA768|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384]| -|RSA768|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| -|RSA768|PSS|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]| -|RSA1024|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PSS|SHA512| [MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384]| -|RSA2048|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PSS|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PSS|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PSS|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PSS|SHA512| [MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - -**ECDSA Signing and Signature Verification** - -- The following ECDSA parameters are supported: - - |Asymmetric Key Algorithm|Supported Type| - |---|---| - |ECC|ECC224| - |ECC|ECC256| - |ECC|ECC384| - |ECC|ECC521| +- If the PSS mode is used, you can obtain the PSS [parameter](../reference/apis/js-apis-cryptoFramework.md#signspecitem10) for signing or signature verification, and set the salt length (**saltLen**, in bytes) for the PSS. - |Digest Algorithm|Supported Type| - |---|---| - |HASH|SHA1| - |HASH|SHA224| - |HASH|SHA256| - |HASH|SHA384| - |HASH|SHA512| + | PSS Parameter|Enum Value| Get()| Set()| + |---|---|---|---| + |md|PSS_MD_NAME_STR |√| + |mgf|PSS_MGF_NAME_STR|√| + |mgf1_md|PSS_MGF1_MD_STR |√| + |saltLen|PSS_SALT_LEN_NUM|√|√| + |trailer_field|PSS_TRAILER_FIELD_NUM|√| -### Key Agreement Specifications + > **NOTE** + > + > The preceding table presents the **Get()** and **Set()** capabilities for PSS parameters supported by the Crypto Framework. **√** indicates that the parameter can be obtained or set. -**ECDH** +### ECDSA Signing and Signature Verification + + > **NOTE** + > The APIs support specifications without the key length for ECDSA signing and signature verification from API version 10. +- The following ECDSA parameters are supported. + + |Asymmetric Key Type|Digest|String Parameter| + |---|---|---| + |ECC224|[SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|ECC224\|[SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| + |ECC256|[SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|ECC256\|[SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| + |ECC384|[SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|ECC384\|[SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| + |ECC521|[SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|ECC521\|[SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| + |ECC|[SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|ECC\|[SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| + + > **NOTE** + > + > - The options included in the square brackets ([]) are mutually exclusive. The options outside the square brackets are fixed values. + > - As a combination of the asymmetric key type and digest with a vertical bar (|) in between, the string parameter specifies the asymmetric signing or signature verification algorithm specifications when an asymmetric signing or signature verification instance is created. For example, **ECC224|SHA256**. + > - The ECC key type in the last row of the preceding table does not contain the key length to ensure compatibility with the key generated based on the key parameters. The ECDSA signing or signature verification operation varies depending on the actual key length. + +### DSA Signing and Signature Verification + + > **NOTE** + > + > DSA signing and signature verification specifications are supported from API version 10. + +- The following DSA parameters are supported. + + |Asymmetric Key Type|Digest|String Parameter| + |---|---|---| + |DSA1024|[NoHash\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|DSA1024\|[NoHash\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| + |DSA2048|[NoHash\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|DSA2048\|[NoHash\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| + |DSA3072|[NoHash\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|DSA3072\|[NoHash\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| + |DSA|[NoHash\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|DSA\|[NoHash\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| + + > **NOTE** + > + > - The options included in the square brackets ([]) are mutually exclusive. The options outside the square brackets are fixed values. + > - As a combination of the asymmetric key type and digest with a vertical bar (|) in between, the string parameter specifies the asymmetric signing or signature verification algorithm specifications when an asymmetric signing or signature verification instance is created. For example, **DSA1024|SHA256**. + > - The DSA key type in the last row of the preceding table does not contain the key length to ensure compatibility with the key generated based on the key parameters. The signing or signature verification operation varies depending on the actual key length. -- The following ECDH parameters are supported: +## Key Agreement Specifications - |Asymmetric Key Algorithm|Supported Type| +### ECDH + + > **NOTE** + > + > The APIs support specifications without the key length for ECDH from API version 10. + +- The following ECDH parameters are supported. + + |Asymmetric Key Algorithm|String Parameter| |---|---| |ECC|ECC224| |ECC|ECC256| |ECC|ECC384| |ECC|ECC521| + |ECC|ECC| -### MD Algorithm Specifications -- The crypto framework supports the following MD algorithm parameters: + > **NOTE** + > + > - The string parameter specifies the key agreement algorithm specifications when a key agreement instance is created. + > - The ECC key type in the last row of the preceding table does not contain the key length to ensure compatibility with the key generated based on the key parameters. The ECDH key agreement operation varies depending on the actual key length. - |Digest Algorithm|Supported Type| - |---|---| - |HASH|SHA1| - |HASH|SHA224| - |HASH|SHA256| - |HASH|SHA384| - |HASH|SHA512| - |HASH|MD5| -### HMAC Algorithm Specifications -- The crypto framework supports the following HMAC algorithm parameters: +## MD Algorithm Specifications - |Digest Algorithm|Supported Type| - |---|---| - |HASH|SHA1| - |HASH|SHA224| - |HASH|SHA256| - |HASH|SHA384| - |HASH|SHA512| +The Crypto Framework supports the following MD algorithm parameters. + +|Digest algorithm|Supported Type| +|---|---| +|HASH|SHA1| +|HASH|SHA224| +|HASH|SHA256| +|HASH|SHA384| +|HASH|SHA512| +|HASH|MD5| + +> **NOTE** +> +> **Supported Type** specifies the MD algorithm specifications when an MD instance is created. + +## HMAC Algorithm Specifications + +The Crypto Framework supports the following HMAC algorithm parameters. + +|Digest algorithm|Supported Type| +|---|---| +|HASH|SHA1| +|HASH|SHA224| +|HASH|SHA256| +|HASH|SHA384| +|HASH|SHA512| + +> **NOTE** +> +> **Supported Type** specifies the HMAC algorithm specifications when an HMAC instance is created. + +## Random Number +Currently, the Crypto Framework supports only the CTR_DRBG algorithm. + +> **NOTE** +> +> - Currently, only secure random numbers with length of 1 to **INT_MAX** bytes are supported. +> - The random number generation algorithm uses the **RAND_priv_bytes** interface of OpenSSL to generate secure random numbers. \ No newline at end of file diff --git a/en/application-dev/task-management/background-task-overview.md b/en/application-dev/task-management/background-task-overview.md index c17f1b3827430f5b0aa2408fb4289276c63942a9..3132796740f148f69af750ff7982af4b9fe54133 100644 --- a/en/application-dev/task-management/background-task-overview.md +++ b/en/application-dev/task-management/background-task-overview.md @@ -46,9 +46,11 @@ Adhere to the following constraints and rules when using transient tasks: - **Quota mechanism**: To prevent abuse of the keepalive, each application has a certain quota every day (dynamically adjusted based on user habits). The default quota for a single day is 10 minutes, and the maximum quota for each request is 3 minutes. After using up the quota, an application cannot request transient tasks. Therefore, applications should cancel their request immediately after the transient tasks are complete, to avoid quota consumption. (Note: The quota refers to the requested duration and does not include the time when the application runs in the background.) ## Continuous Tasks + Continuous tasks provide background running lifecycle support for services that can be directly perceived by users and need to run in the background. For example, if a service needs to play audio or continue with navigation and positioning in the background, which can be perceived by users, it can execute a continuous task in the respective background mode. ### Background Mode Classification + OpenHarmony provides 9 background modes for services that require continuous task execution. **Table 1** Background modes for continuous tasks @@ -66,6 +68,7 @@ OpenHarmony provides 9 background modes for services that require continuous tas | taskKeeping | Computing task | A computing task is running | Effective only for specific devices | ### Restrictions on Using Continuous Tasks + - If a user triggers a perceivable task, such as broadcasting and navigation, the corresponding background mode is triggered. When the task is started, the system forcibly displays a notification to the user. - If the task is complete, the application should exit the background mode. If the system detects that an application is not using the resources in the corresponding background mode when the application is running in the background, the application is suspended. - Ensure that the requested continuous task background mode matches the application type. If the background mode does not match the application type, the system will suspend the task once it detects the issue. @@ -73,6 +76,7 @@ OpenHarmony provides 9 background modes for services that require continuous tas - An ability can request only one continuous task at a time. If an application has multiple abilities, you can request a continuous task for each ability. ## Work Scheduler Tasks + The Work Scheduler provides a mechanism for an application to execute a non-real-time task, for example, data learning, when the system is idle. The system places the Work Scheduler tasks requested by applications in a queue and determines the optimal scheduling time of each task based on the storage space, power consumption, temperature, and more. Persistence is supported. This means that a requested Work Scheduler task can be triggered when the application exits or the device restarts. ### Restrictions on Using Work Scheduler Tasks @@ -103,6 +107,7 @@ The use of the Work Scheduler must comply with the following restrictions and ru - The carried parameters can be of the number, string, or boolean type. ## Efficiency Resources + Efficiency resources are classified into software (WORK_SCHEDULER, COMMON_EVENT, and TIMER) and hardware resources (CPU, GPS, BLUETOOTH, and AUDIO). An application can perform different operations based on the requested efficiency resources. @@ -126,6 +131,7 @@ An application can perform different operations based on the requested efficienc | AUDIO | 64 | AUDIO resources, which prevent audio resources from being proxied when the application is suspended. | ### Restrictions on Using Efficiency Resources + - Applications or processes are responsible for requesting and releasing efficiency resources. A process can release the resources requested by itself, whereas an application can release the resources requested by both itself and its processes. For example, an application requests CPU resources, and its process requests CPU and WORK_SCHEDULER resources. If the application initiates CPU resource release, the CPU resources requested by the process are also released. However, the WORK_SCHEDULER resources are not released. If the process initiates CPU resource release, the CPU resources requested by the application are retained until being released by the application. - If persistent resources and non-persistent resources of the same type are requested, the persistent resources overwrite the non-persistent resources and they will not be released upon a timeout. For example, if an application first requests 10-second CPU resources and then requests persistent CPU resources at the 5th second, the CPU resources become persistent and will not be released at the tenth second. If the application releases the CPU resources at the 8th second, both types of CPU resources are released. - The WORK_SCHEDULER resources can be requested and released by applications, but not by processes. diff --git a/en/application-dev/tools/packing-tool.md b/en/application-dev/tools/packing-tool.md index db0f232d6c53cdb7bf47c540010c2aea3f83d06c..dd219250333636f96f715530b3ef8c86f0810223 100644 --- a/en/application-dev/tools/packing-tool.md +++ b/en/application-dev/tools/packing-tool.md @@ -1,7 +1,7 @@ -# Packing and Unpacking Tools +# Packing Tool ## Overview -The packing tool packs compiled files for installation and release. The packing tool supports the generation of application packages (HAP), application sets (APP) to launch to the application market, quick fix packages (HQF), quick fix packages (APPQF) to launch to the application market, static shared libraries (HAR), and dynamic shared libraries (HSP). The unpacking tool is used to unpack the HAP, APP, HQF, APPQF, HAR, and HSP files and parse the HAP, HSP, APP, and APPQF files. Generally, the packing process is automatically carried out in DevEco Studio. However, you can also use the JAR package of the packing tool to pack files. The JAR package is stored in the **toolchains** directory in the SDK path. +The packing tool packs compiled files for installation and release. The packing tool supports the generation of HAP (an application package), APP (application set to launch to the application market), HQF (quick fix package), APPQF (quick fix package to launch to the application market ), HAR (static shared library), and HSP (dynamic shared library) files. The unpacking tool is used to unpack the HAP, APP, HQF, APPQF, HAR, and HSP files and parse the HAP, HSP, APP, and APPQF files. Generally, the packing process is automatically carried out in DevEco Studio. However, you can also use the JAR package of the packing tool to pack files. The JAR package is stored in the **toolchains** directory in the SDK path. ## Packing Commands @@ -15,7 +15,7 @@ You can use the JAR package of the packing tool to generate an HAP file by impor ``` - java -jar app_packing_tool.jar --mode hap --json-path