diff --git a/en/application-dev/Readme-EN.md b/en/application-dev/Readme-EN.md index a4d1f95a92f50783825b392d55aa089d121c84c4..c964b95235cde910b76cde78f114772237973af4 100644 --- a/en/application-dev/Readme-EN.md +++ b/en/application-dev/Readme-EN.md @@ -20,24 +20,23 @@ - Development - [Ability Development](ability/Readme-EN.md) - [UI Development](ui/Readme-EN.md) - - Basic Feature Development - - [Common Event and Notification](notification/Readme-EN.md) - - [Window Manager](windowmanager/Readme-EN.md) - - [WebGL](webgl/Readme-EN.md) - - [Media](media/Readme-EN.md) - - [Security](security/Readme-EN.md) - - [Connectivity](connectivity/Readme-EN.md) - - [Data Management](database/Readme-EN.md) - - [Telephony](telephony/Readme-EN.md) - - [Agent-Powered Scheduled Reminders](background-agent-scheduled-reminder/Readme-EN.md) - - [Background Task Management](background-task-management/Readme-EN.md) - - [Work Scheduler](work-scheduler/Readme-EN.md) - - [Device Management](device/Readme-EN.md) - - [Device Usage Statistics](device-usage-statistics/Readme-EN.md) - - [DFX](dfx/Readme-EN.md) - - [Internationalization](internationalization/Readme-EN.md) - - [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md) - - [Using Native APIs in Application Projects](napi/Readme-EN.md) + - [Common Event and Notification](notification/Readme-EN.md) + - [Window Manager](windowmanager/Readme-EN.md) + - [WebGL](webgl/Readme-EN.md) + - [Media](media/Readme-EN.md) + - [Security](security/Readme-EN.md) + - [Connectivity](connectivity/Readme-EN.md) + - [Data Management](database/Readme-EN.md) + - [Telephony](telephony/Readme-EN.md) + - [Agent-Powered Scheduled Reminders](background-agent-scheduled-reminder/Readme-EN.md) + - [Background Task Management](background-task-management/Readme-EN.md) + - [Work Scheduler](work-scheduler/Readme-EN.md) + - [Device Management](device/Readme-EN.md) + - [Device Usage Statistics](device-usage-statistics/Readme-EN.md) + - [DFX](dfx/Readme-EN.md) + - [Internationalization](internationalization/Readme-EN.md) + - [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md) + - [Using Native APIs in Application Projects](napi/Readme-EN.md) - Tools - [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md) - Hands-On Tutorials diff --git a/en/application-dev/ability/ability-delegator.md b/en/application-dev/ability/ability-delegator.md index 4e27041093bc2b9d1e3a2966f7a5f20b0f51b94c..86b8bdf7f2389763dfd65e3d124e04e7ec863939 100644 --- a/en/application-dev/ability/ability-delegator.md +++ b/en/application-dev/ability/ability-delegator.md @@ -12,8 +12,8 @@ The APIs provided by the test framework can be used only in the test HAP. They t The test framework can be started in either of the following ways: -- Method 1: Run the aa test command. -- Method 2: Use the IDE. +- Method 1: Run the `aa test` command. +- Method 2: Use DevEco Studio. ### Running aa test @@ -37,16 +37,16 @@ aa test -b BundleName -m com.example.myapplicationfaets -s unittest OpenHarmonyT | -s unittest | Yes | Name of the **TestRunner** to be used. The TestRunner name must be the same as the file name. | | -w | No | Timeout interval of a test case, in seconds. If this parameter is not specified or is set to a value less than or equal to **0**, the test framework exits only after **finishTest** is invoked.| | -s \\ | No | **-s** can be followed by any key-value pair obtained through **AbilityDelegatorArgs.parameters**. For example, in **-s classname myTest**, **-s classname** is the key and **myTest** is the value.| -| -D | No | Debug mode for starting the tested application. | -| -h | No | Help information. | +| -D | No | Debug mode for starting the tested application.| +| -h | No | Help information.| -### Using the IDE +### Using DevEco Studio -For details about how to use the IDE to start the test framework, see [IDE Guide](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-openharmony-test-framework-0000001263160453#section1034420367508). +For details about how to use DevEco Studio to start the test framework, see [OpenHarmony Test Framework](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-openharmony-test-framework-0000001263160453#section1034420367508). ## Introduction to TestRunner -**TestRunner** is the entry class of the test framework test process. When the test process is started, the system calls related APIs in **TestRunner**. You need to inherit this class and override the **onPrepare** and **onRun** APIs. When creating an application template, the IDE initializes the default **TestRunner** and starts the default **TestAbility** in the **onRun** API. You can modify the test code of **TestAbility** or override **onPrepare** and **onRun** in **TestRunner** to implement your own test code. For details, see [TestRunner](../reference/apis/js-apis-testRunner.md). +**TestRunner** is the entry class of the test framework test process. When the test process is started, the system calls related APIs in **TestRunner**. You need to inherit this class and overwrite the **onPrepare** and **onRun** APIs. When creating an application template, DevEco Studio initializes the default **TestRunner** and starts the default **TestAbility** in the **onRun** API. You can modify the test code of **TestAbility** or override **onPrepare** and **onRun** in **TestRunner** to implement your own test code. For details, see [TestRunner](../reference/apis/js-apis-testRunner.md). ## Introduction to AbilityDelegatorRegistry @@ -136,6 +136,7 @@ abilityDelegator.startAbility(want, (err, data) => { ### Running a Shell Command **AbilityDelegator** provides APIs to run shell commands in the test environment. + **Example** ```javascript @@ -150,6 +151,7 @@ abilityDelegator.executeShellCommand(cmd, (err, data) => { ### Printing Log Information **AbilityDelegator** provides APIs for printing log information. You can call any API in the test code to print process logs to the unit test console. + **Example** ```javascript @@ -165,6 +167,7 @@ abilityDelegator.print(msg, (err) => { ### Finishing the Test and Printing Log Information **AbilityDelegator** provides the APIs for actively finishing the test. You can call any API in test code to finish the test and print logs to the unit test console. + **Example** ```javascript diff --git a/en/application-dev/ability/fa-formability.md b/en/application-dev/ability/fa-formability.md index 8b447ba835d915e3d6ff1b7ed491342932048673..dac8d5ee66e4441021a91f1967815d364227228c 100644 --- a/en/application-dev/ability/fa-formability.md +++ b/en/application-dev/ability/fa-formability.md @@ -3,20 +3,12 @@ ## Widget Overview A widget is a set of UI components used to display important information or operations for an application. It provides users with direct access to a desired application service, without requiring them to open the application. -A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive features such as opening a UI page or sending a message. The widget host is responsible for displaying the widget. +A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive functions such as opening a UI page or sending a message. Basic concepts: -- Widget provider - - The widget provider is an atomic service that provides the content to be displayed. It controls the display content, component layout, and component click events of a widget. - -- Widget host - - The widget host is an application that displays the widget content and controls the position where the widget is displayed in the host application. - -- Widget Manager - - The Widget Manager is a resident agent that manages widgets added to the system and provides functions such as periodic widget update. +- Widget provider: an atomic service that controls what and how content is displayed in a widget and interacts with users. +- Widget host: an application that displays the widget content and controls the position where the widget is displayed in the host application. +- Widget Manager: a resident agent that manages widgets added to the system and provides functions such as periodic widget update. > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The widget host and provider do not keep running all the time. The Widget Manager starts the widget provider to obtain widget information when a widget is added, deleted, or updated. @@ -30,7 +22,7 @@ The widget provider controls the widget content to display, component layout, an Form ability development refers to the development conducted by the widget provider based on the [Feature Ability (FA) model](fa-brief.md). As a widget provider, you need to carry out the following operations: - Develop the lifecycle callbacks in **LifecycleForm**. -- Create a **FormBindingData** object. +- Create a **FormBindingData** instance. - Update a widget through **FormProvider**. - Develop the widget UI page. @@ -46,9 +38,9 @@ The table below describes the lifecycle callbacks provided **LifecycleForm**. | onCastToNormal(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.| | onUpdate(formId: string): void | Called to notify the widget provider that a widget has been updated. | | onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change of widget visibility. | -| onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process the widget event. | +| onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process a widget event. | | onDestroy(formId: string): void | Called to notify the widget provider that a **Form** instance (widget) has been destroyed. | -| onAcquireFormState?(want: Want): formInfo.FormState | Called when the widget provider receives the status query result of a specified widget. | +| onAcquireFormState?(want: Want): formInfo.FormState | Called when the widget provider receives the status query result of a widget. | For details about the **FormProvider** APIs, see [FormProvider](../reference/apis/js-apis-formprovider.md). @@ -81,7 +73,7 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li export default { onCreate(want) { console.log('FormAbility onCreate'); - // Persistently store widget information for subsequent use, such as widget instance retrieval and update. + // Persistently store widget information for subsequent use, such as during widget instance retrieval or update. let obj = { "title": "titleOnCreate", "detail": "detailOnCreate" @@ -94,7 +86,7 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li console.log('FormAbility onCastToNormal'); }, onUpdate(formId) { - // To support scheduled update, periodic update, or update requested by the widget host for a widget, override this method for data update. + // To support scheduled update, periodic update, or update requested by the widget host, override this method for widget data update. console.log('FormAbility onUpdate'); let obj = { "title": "titleOnUpdate", @@ -124,11 +116,11 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li } ``` -### Configuring config.json for the Form Ability +### Configuring the Widget Configuration File -Configure the **config.json** file for the **Form** ability. +Configure the **config.json** file for the widget. -- The **js** module in the **config.json** file provides the JavaScript resources of the **Form** ability. The internal field structure is described as follows: +- The **js** module in the **config.json** file provides the JavaScript resources of the widget. The internal field structure is described as follows: | Field| Description | Data Type| Default | | -------- | ------------------------------------------------------------ | -------- | ------------------------ | @@ -161,12 +153,12 @@ Configure the **config.json** file for the **Form** ability. | isDefault | Whether the widget is a default one. Each ability has only one default widget.
**true**: The widget is the default one.
**false**: The widget is not the default one.| Boolean | No | | type | Type of the widget. Available values are as follows:
**JS**: indicates a JavaScript-programmed widget. | String | No | | colorMode | Color mode of the widget. Available values are as follows:
**auto**: The widget adopts the auto-adaptive color mode.
**dark**: The widget adopts the dark color mode.
**light**: The widget adopts the light color mode.| String | Yes (initial value: **auto**)| - | supportDimensions | Grid styles supported by the widget. Available values are as follows:
1 * 2: indicates a grid with one row and two columns.
2 * 2: indicates a grid with two rows and two columns.
2 * 4: indicates a grid with two rows and four columns.
4 * 4: indicates a grid with four rows and four columns.| String array| No | + | supportDimensions | Grid styles supported by the widget. Available values are as follows:
**1 * 2**: indicates a grid with one row and two columns.
**2 * 2**: indicates a grid with two rows and two columns.
**2 * 4**: indicates a grid with two rows and four columns.
**4 * 4**: indicates a grid with four rows and four columns.| String array| No | | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No | | updateEnabled | Whether the widget can be updated periodically. Available values are as follows:
**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.
**false**: The widget cannot be updated periodically.| Boolean | No | | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes (initial value: **0:0**) | | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.| Number | Yes (initial value: **0**) | - | formConfigAbility | Indicates the link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) | + | formConfigAbility | Link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) | | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | | jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. | String | No | | metaData | Metadata of the widget. This field contains the array of the **customizeData** field. | Object | Yes (initial value: left empty) | @@ -203,7 +195,7 @@ Configure the **config.json** file for the **Form** ability. ``` -### Widget Data Persistence +### Persistently Store Widget Data Mostly, the widget provider is started only when it needs to obtain information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting a widget. @@ -215,6 +207,7 @@ Mostly, the widget provider is started only when it needs to obtain information let formName = want.parameters["ohos.extra.param.key.form_name"]; let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"]; // Persistently store widget information for subsequent use, such as widget instance retrieval and update. + // The storeFormInfo API is not implemented here. For details about the implementation, see "FA Model Widget" provided in "Samples". storeFormInfo(formId, formName, tempFlag, want); let obj = { @@ -230,26 +223,28 @@ You should override **onDestroy** to delete widget data. ```javascript onDestroy(formId) { - // Delete widget data. - deleteFormInfo(formId); console.log('FormAbility onDestroy'); + + // You need to implement the code for deleting the persistent widget instance. + // The deleteFormInfo API is not implemented here. For details, see "Widget Host" provided in "Samples". + deleteFormInfo(formId); } ``` For details about the persistence method, see [Lightweight Data Store Development](../database/database-preference-guidelines.md). Note that the **Want** passed by the widget host to the widget provider contains a temporary flag, indicating whether the requested widget is a temporary one. + +- Normal widget: a widget that will be persistently used by the widget host -Normal widget: a widget that will be persistently used by the widget host - -Temporary widget: a widget that is temporarily used by the widget host +- Temporary widget: a widget that is temporarily used by the widget host Data of a temporary widget is not persistently stored. If the widget framework is killed and restarted, data of a temporary widget will be deleted. However, the widget provider is not notified of which widget is deleted, and still keeps the data. Therefore, the widget provider should implement data clearing. In addition, the widget host may convert a temporary widget into a normal one. If the conversion is successful, the widget provider should process the widget ID and store the data persistently. This prevents the widget provider from deleting persistent data when clearing temporary widgets. ### Developing the Widget UI Page You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> Currently, only the JavaScript-based web-like development paradigm can be used to develop the widget UI. - HML: @@ -331,10 +326,8 @@ Now you've got a widget shown below. ![fa-form-example](figures/fa-form-example.png) -## Development Example - -The following sample is provided to help you better understand how to develop a widget on the FA model: - -[FormAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/FormAbility) +## Samples -This sample provides a widget. Users can create, update, and delete widgets on the home screen of their devices or by using their own widget host. This sample also implements widget information persistence by using lightweight data storage. +The following samples are provided to help you better understand how to develop a widget on the FA model: +- [`FormAbility`: FA Model Widget (JS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormAbility) +- [`FormLauncher`: Widget Host (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormLauncher) diff --git a/en/application-dev/ability/stage-call.md b/en/application-dev/ability/stage-call.md index 36efd3076702ef26c37cd304794ea2caf36e053d..663cce30ee51874682e7de03f16151ba193ab86d 100644 --- a/en/application-dev/ability/stage-call.md +++ b/en/application-dev/ability/stage-call.md @@ -83,7 +83,7 @@ export default class MySequenceable { ``` 4. Implement **Callee.on** and **Callee.off**. - The time to register a listener for the callee depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **CalleeSortMethod** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code snippet is as follows: + The time to register a listener for the callee depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code snippet is as follows: ```ts const TAG: string = '[CalleeAbility]' const MSG_SEND_METHOD: string = 'CallSendMsg' @@ -148,7 +148,7 @@ async onButtonGetCaller() { console.error(TAG + 'get caller failed with ' + error) }) ``` -In the cross-device scenario, you need to specify the ID of the peer device. The sample code snippet is as follows: + In the cross-device scenario, you need to specify the ID of the peer device. The sample code snippet is as follows: ```ts let TAG = '[MainAbility] ' var caller = undefined @@ -172,7 +172,7 @@ context.startAbilityByCall({ console.error(TAG + 'get remote caller failed with ' + error) }) ``` -Obtain the ID of the peer device from **DeviceManager**. Note that the **getTrustedDeviceListSync** API is open only to system applications. The sample code snippet is as follows: + Obtain the ID of the peer device from **DeviceManager**. Note that the **getTrustedDeviceListSync** API is open only to system applications. The sample code snippet is as follows: ```ts import deviceManager from '@ohos.distributedHardware.deviceManager'; var dmClass; @@ -190,7 +190,7 @@ function getRemoteDeviceId() { } } ``` -In the cross-device scenario, the application must also apply for the data synchronization permission from end users. The sample code snippet is as follows: + In the cross-device scenario, the application must also apply for the data synchronization permission from end users. The sample code snippet is as follows: ```ts let context = this.context let permissions: Array = ['ohos.permission.DISTRIBUTED_DATASYNC'] @@ -215,7 +215,7 @@ async onButtonCall() { } ``` -In the following, **CallWithResult** is used to send data **originMsg** to the callee and assign the data processed by the **CallSendMsg** method to **backMsg**. The sample code snippet is as follows: + In the following, **CallWithResult** is used to send data **originMsg** to the callee and assign the data processed by the **CallSendMsg** method to **backMsg**. The sample code snippet is as follows: ```ts const MSG_SEND_METHOD: string = 'CallSendMsg' originMsg: string = '' diff --git a/en/application-dev/ability/stage-formextension.md b/en/application-dev/ability/stage-formextension.md index 24d704fbc193e9743cbb59792c48b18cd3e601ca..e1d3604c566b217a7b4f9f2c880faf5d4c71cf47 100644 --- a/en/application-dev/ability/stage-formextension.md +++ b/en/application-dev/ability/stage-formextension.md @@ -4,18 +4,15 @@ A widget is a set of UI components used to display important information or operations for an application. It provides users with direct access to a desired application service, without requiring them to open the application. -A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive features such as opening a UI page or sending a message. The widget host is responsible for displaying the service widget. +A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive functions such as opening a UI page or sending a message. Basic concepts: -- Widget provider
- The widget provider is an atomic service that provides the content to be displayed. It controls the display content, component layout, and component click events of a widget. -- Widget host
- The widget host is an application that displays the widget content and controls the position where the widget is displayed in the host application. -- Widget Manager
- The Widget Manager is a resident agent that manages widgets added to the system and provides functions such as periodic widget update. +- Widget provider: an atomic service that controls what and how content is displayed in a widget and interacts with users. +- Widget host: an application that displays the widget content and controls the position where the widget is displayed in the host application. +- Widget Manager: a resident agent that manages widgets added to the system and provides functions such as periodic widget update. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > The widget host and provider do not keep running all the time. The Widget Manager starts the widget provider to obtain widget information when a widget is added, deleted, or updated. You only need to develop widget content as the widget provider. The system automatically handles the work done by the widget host and Widget Manager. @@ -24,16 +21,16 @@ The widget provider controls the widget content to display, component layout, an ## When to Use -Stage ability development refers to the development conducted by the widget provider based on the [stage model](stage-brief.md). As a widget provider, you need to carry out the following operations: +Stage widget development refers to the development conducted by the widget provider based on the [stage model](stage-brief.md). As a widget provider, you need to carry out the following operations: -- Develop the lifecycle callback functions in **FormExtension**. -- Create a **FormBindingData** object. +- Develop the lifecycle callbacks in **FormExtension**. +- Create a **FormBindingData** instance. - Update a widget through **FormProvider**. - Develop the widget UI page. ## Available APIs -The **FormExtension** class has the **context** attribute. For details on the APIs provided by the **FormExtension** class, see [FormExtension](../reference/apis/js-apis-formextension.md). +The **FormExtension** class has the following APIs. For details, see [FormExtension](../reference/apis/js-apis-formextension.md). **Table 1** FormExtension APIs @@ -42,19 +39,19 @@ The **FormExtension** class has the **context** attribute. For details on the AP | onCreate(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a **Form** instance (widget) has been created. | | onCastToNormal(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.| | onUpdate(formId: string): void | Called to notify the widget provider that a widget has been updated. | -| onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change of widget visibility. | -| onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process the widget event. | +| onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change in widget visibility. | +| onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process a widget event. | | onDestroy(formId: string): void | Called to notify the widget provider that a **Form** instance (widget) has been destroyed. | -| onConfigurationUpdated(config: Configuration): void; | Called when the configuration of the environment where the ability is running is updated. | +| onConfigurationUpdated(config: Configuration): void; | Called when the configuration of the environment where the widget is running is updated. | -The **context** attribute of the **FormExtension** class inherits from the **FormExtensionContext** class. For details about the APIs provided by the **FormExtensionContext** class, see [FormExtensionContext](../reference/apis/js-apis-formextensioncontext.md). +The **FormExtension** class also has a member context, that is, the **FormExtensionContext** class. For details, see [FormExtensionContext](../reference/apis/js-apis-formextensioncontext.md). **Table 2** FormExtensionContext APIs | API | Description | | :----------------------------------------------------------- | :------------------------ | -| updateForm(formId: string, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback\): void | Updates a widget. This method uses a callback to return the result. | -| updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Promise\ | Updates a widget. This method uses a promise to return the result.| +| updateForm(formId: string, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback\): void | Updates a widget. This API uses an asynchronous callback to return the result. | +| updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Promise\ | Updates a widget. This API uses a promise to return the result.| For details about the **FormProvider** APIs, see [FormProvider](../reference/apis/js-apis-formprovider.md). @@ -69,9 +66,9 @@ For details about the **FormProvider** APIs, see [FormProvider](../reference/api ## How to Develop -### Creating a Form Extension +### Creating a FormExtension Instance -To create a widget in the stage model, you need to implement the lifecycle callback functions of **FormExtension**. The sample code is as follows: +To create a widget in the stage model, implement the lifecycle callbacks of **FormExtension**. The sample code is as follows: 1. Import the required modules. @@ -82,13 +79,13 @@ To create a widget in the stage model, you need to implement the lifecycle callb import formProvider from '@ohos.application.formProvider' ``` -2. Implement the lifecycle callback functions of **FormExtension**. +2. Implement the lifecycle callbacks of **FormExtension**. ```javascript export default class FormAbility extends FormExtension { onCreate(want) { console.log('FormAbility onCreate'); - // Persistently store widget information for subsequent use, such as widget instance retrieval and update. + // Persistently store widget information for subsequent use, such as during widget instance retrieval or update. let obj = { "title": "titleOnCreate", "detail": "detailOnCreate" @@ -101,7 +98,7 @@ To create a widget in the stage model, you need to implement the lifecycle callb console.log('FormAbility onCastToNormal'); } onUpdate(formId) { - // To support scheduled update, periodic update, or update requested by the widget host for a widget, override this method for data update. + // To support scheduled update, periodic update, or update requested by the widget host, override this method for widget data update. console.log('FormAbility onUpdate'); let obj = { "title": "titleOnUpdate", @@ -130,24 +127,22 @@ To create a widget in the stage model, you need to implement the lifecycle callb } ``` -### Configuring config.json for the Form Ability +### Configuring the Widget Configuration File -Configure the **module.json** file for the **Form** ability. - -- The internal field structure of the **extensionAbility** module is described as follows: +- Configure Extension ability information under **extensionAbilities** in the **module.json5** file. The internal field structure is described as follows: | Field | Description | Data Type | Default | | ----------- | ------------------------------------------------------------ | ---------- | -------------------- | - | name | Name of an extension ability. | String | No | - | srcEntrance | JS code path of the extension ability. | String | No | - | description | Description of the extension ability. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty)| - | icon | Index of the extension ability icon file. | String | Yes (initial value: left empty)| - | label | Descriptive information about the extension ability presented externally. The value can be a string or a resource index to the description.| String | Yes (initial value: left empty)| - | type | Type of the extension ability. The value can be **form** or **service**. | String | No | + | name | Name of the Extension ability. This field must be specified. | String | No | + | srcEntrance | Path of the Extension ability lifecycle code. This field must be specified.| String | No | + | description | Description of the Extension ability. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty)| + | icon | Index of the Extension ability icon file. | String | Yes (initial value: left empty)| + | label | Descriptive information about the Extension ability presented externally. The value can be a string or a resource index to the description.| String | Yes (initial value: left empty)| + | type | Type of the Extension ability. In the current development scenario, set this field to **form**.| String | No | | permissions | Permissions required for abilities of another application to call the current ability. | String array| Yes (initial value: left empty)| - | metadata | Metadata of the extension ability. It describes the configuration information of the extension ability.| Object | Yes (initial value: left empty) | + | metadata | Metadata (configuration information) of the Extension ability.| Object | Yes (initial value: left empty) | - For a Form Extension ability, set **type** to **form** and **metadata** to the widget details. + For a Form Extension ability, you must specify **metadata**. Specifically, set **name** to **ohos.extension.form** (fixed), and set **resource** to the index of the widget configuration information. A configuration example is as follows: @@ -165,25 +160,25 @@ Configure the **module.json** file for the **Form** ability. }] ``` -- Configure the widget profile module. In the metadata of the Form Extension ability, the resource file path specified by **ohos.extension.form** must be used. For example, **$profile:form_config** means that **form_config.json** in the **resources/base/profile/** directory of the development view is used as the widget profile. +- Configure the widget configuration information. **resource** in **metadata** specifies the index of the widget configuration information. For example, **$profile:form_config** means that **form_config.json** in the **resources/base/profile/** directory of the development view is used as the widget profile configuration file. The internal field structure is described as follows: | Field | Description | Data Type | Default | | ------------------- | ------------------------------------------------------------ | ---------- | ------------------------ | - | name | Class name of the widget. The value is a string with a maximum of 127 bytes. | String | No | + | name | Class name of a widget. The value is a string with a maximum of 127 bytes. | String | No | | description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | | src | Full path of the UI code corresponding to the widget. | String | No | | window | Window-related configurations. | Object | Yes | | isDefault | Whether the widget is a default one. Each ability has only one default widget.
**true**: The widget is the default one.
**false**: The widget is not the default one.| Boolean | No | | colorMode | Color mode of the widget. Available values are as follows:
**auto**: The widget adopts the auto-adaptive color mode.
**dark**: The widget adopts the dark color mode.
**light**: The widget adopts the light color mode.| String | Yes (initial value: **auto**)| - | supportDimensions | Grid styles supported by the widget. Available values are as follows:
1 * 2: indicates a grid with one row and two columns.
2 * 2: indicates a grid with two rows and two columns.
2 * 4: indicates a grid with two rows and four columns.
4 * 4: indicates a grid with four rows and four columns.| String array| No | + | supportDimensions | Grid styles supported by the widget. Available values are as follows:
**1 * 2**: indicates a grid with one row and two columns.
**2 * 2**: indicates a grid with two rows and two columns.
**2 * 4**: indicates a grid with two rows and four columns.
**4 * 4**: indicates a grid with four rows and four columns.| String array| No | | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No | - | updateEnabled | Whether the widget can be updated periodically. Available values are as follows:
**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.
**false**: The widget cannot be updated periodically.| Boolean | No | + | updateEnabled | Whether the widget can be updated periodically. Available values are as follows:
**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is recommended.
**false**: The widget cannot be updated periodically.| Boolean | No | | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes (initial value: **0:0**) | | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.| Number | Yes (initial value: **0**) | | formConfigAbility | Link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) | - | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | + | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | | metaData | Metadata of the widget. This field contains the array of the **customizeData** field. | Object | Yes (initial value: left empty) | A configuration example is as follows: @@ -211,9 +206,9 @@ Configure the **module.json** file for the **Form** ability. ``` -### Widget Data Persistence +### Persistently Storing Widget Data -Mostly, the widget provider is started only when it needs to obtain information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting a widget. +Mostly, the widget provider is started only when it needs to obtain information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting the widget. ```javascript onCreate(want) { @@ -222,7 +217,8 @@ Mostly, the widget provider is started only when it needs to obtain information let formId = want.parameters["ohos.extra.param.key.form_identity"]; let formName = want.parameters["ohos.extra.param.key.form_name"]; let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"]; - // Persistently store widget information for subsequent use, such as widget instance retrieval and update. + // Persistently store widget data for subsequent use, such as widget instance retrieval and update. + // The storeFormInfo API is not implemented here. For details about the implementation, see "Samples" below. storeFormInfo(formId, formName, tempFlag, want); let obj = { @@ -238,9 +234,11 @@ You should override **onDestroy** to delete widget data. ```javascript onDestroy(formId) { - // Delete widget data. - deleteFormInfo(formId); console.log('FormAbility onDestroy'); + + // You need to implement the code for deleting the persistent widget data. + // The deleteFormInfo API is not implemented here. For details about the implementation, see "Samples" below. + deleteFormInfo(formId); } ``` @@ -248,16 +246,16 @@ For details about the persistence method, see [Lightweight Data Store Developmen Note that the **Want** passed by the widget host to the widget provider contains a temporary flag, indicating whether the requested widget is a temporary one. -Normal widget: a widget that will be persistently used by the widget host +- Normal widget: a widget that will be persistently used by the widget host -Temporary widget: a widget that is temporarily used by the widget host +- Temporary widget: a widget that is temporarily used by the widget host -Data of a temporary widget is not persistently stored. If the widget framework is killed and restarted, data of a temporary widget will be deleted. However, the widget provider is not notified of which widget is deleted, and still keeps the data. Therefore, the widget provider should implement data clearing. In addition, the widget host may convert a temporary widget into a normal one. If the conversion is successful, the widget provider should process the widget ID and store the data persistently. This prevents the widget provider from deleting persistent data when clearing temporary widgets. +Data of a temporary widget is not persistently stored. If it is deleted from the Widget Manager due to exceptions, such as crash of the widget framework, the widget provider will not be notified of which widget is deleted, and still keeps the data. In light of this, the widget provider should implement data clearing. If the widget host successfully converts a temporary widget into a normal one, the widget provider should also process the widget ID and store the data persistently. This prevents the widget provider from deleting the widget data when clearing temporary widgets. ### Developing the Widget UI Page You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > Currently, only the JavaScript-based web-like development paradigm can be used to develop the widget UI. - hml: @@ -339,10 +337,7 @@ Now you've got a widget shown below. ![fa-form-example](figures/fa-form-example.png) -## Development Example +## Samples The following sample is provided to help you better understand how to develop a widget on the stage model: - -[FormExtAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/FormExtAbility) - -Users can create, update, and delete widgets on the home screen of their devices or by using their own widget host. This sample also implements widget information persistence by using lightweight data storage. \ No newline at end of file +- [`FormExtAbility`: Stage Model Widget (eTS, JS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormExtAbility) diff --git a/en/application-dev/database/database-distributedobject-guidelines.md b/en/application-dev/database/database-distributedobject-guidelines.md index 516ed427b9b8d613b832b430cc63e7d3fa4cd30f..86392551501483b40e69ce3fdcad0e3c5f71e92c 100644 --- a/en/application-dev/database/database-distributedobject-guidelines.md +++ b/en/application-dev/database/database-distributedobject-guidelines.md @@ -165,14 +165,4 @@ The following example shows how to implement a distributed data object synchroni ```js local_object.setSessionId(""); - ``` - -## Samples - -The following example is provided for you to better understand the development of distributed data objects: - -- [Distributed Notepad](https://gitee.com/openharmony/distributeddatamgr_objectstore/tree/master/samples/distributedNotepad) - - -When an event of the Notepad app occurs on a device, such as a note is added, the tile or content of a note is changed, or the event list is cleared, the change will be synchronized to other devices in the trusted network. - + ``` \ No newline at end of file diff --git a/en/application-dev/database/database-mdds-guidelines.md b/en/application-dev/database/database-mdds-guidelines.md index fb45be2adf83aa7c3a1dac6cc875926c3c22a705..309d2a38e4cbcab79a102b809bb9444cf9a8e1ee 100644 --- a/en/application-dev/database/database-mdds-guidelines.md +++ b/en/application-dev/database/database-mdds-guidelines.md @@ -178,7 +178,3 @@ The following uses a single KV store as an example to describe the development p } }); ``` -## Samples -The following samples are provided to help you better understand the distributed data development: -- [`KvStore`: Distributed Data Management (eTS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/data/Kvstore) -- [Distributed Data Service](https://gitee.com/openharmony/codelabs/tree/master/Data/JsDistributedData) diff --git a/en/application-dev/database/database-relational-guidelines.md b/en/application-dev/database/database-relational-guidelines.md index d43b11ff62e73d65de6d77623641b7748a82c824..cdcbf0b033288458f2d0ae4192476d86bc9f38b5 100644 --- a/en/application-dev/database/database-relational-guidelines.md +++ b/en/application-dev/database/database-relational-guidelines.md @@ -15,10 +15,10 @@ The following table describes the APIs available for creating and deleting an RD | API| Description| | -------- | -------- | -|getRdbStore(config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void | Obtains an RDB store. This method uses a callback to return the result. You can set parameters for the RDB store based on service requirements, and then call APIs to perform data operations.
- **config**: configuration of the RDB store.
- **version**: RDB version.
- **callback**: callback invoked to return the RDB store obtained.| -|getRdbStore(config: StoreConfig, version: number): Promise<RdbStore> | Obtains an RDB store. This method uses a promise to return the result. You can set parameters for the RDB store based on service requirements, and then call APIs to perform data operations.
- **config**: configuration of the RDB store.
- **version**: RDB version.| -|deleteRdbStore(name: string, callback: AsyncCallback<void>): void | Deletes an RDB store. This method uses a callback to return the result.
- **name**: RDB store to delete.
- **callback**: callback invoked to return the result.| -| deleteRdbStore(name: string): Promise<void> | Deletes an RDB store. This method uses a promise to return the result.
- **name**: RDB store to delete.| +|getRdbStore(config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void | Obtains an RDB store. This method uses a callback to return the result. You can set parameters for the RDB store based on service requirements, and then call APIs to perform data operations.
- **config**: configuration of the RDB store.
- **version**: RDB version.
- **callback**: callback invoked to return the RDB store obtained.| +|getRdbStore(config: StoreConfig, version: number): Promise<RdbStore> | Obtains an RDB store. This method uses a promise to return the result. You can set parameters for the RDB store based on service requirements, and then call APIs to perform data operations.
- **config**: configuration of the RDB store.
- **version**: RDB version.| +|deleteRdbStore(name: string, callback: AsyncCallback<void>): void | Deletes an RDB store. This method uses a callback to return the result.
- **name**: RDB store to delete.
- **callback**: callback invoked to return the result.| +| deleteRdbStore(name: string): Promise<void> | Deletes an RDB store. This method uses a promise to return the result.
- **name**: RDB store to delete.| ### Managing Data in an RDB Store @@ -32,8 +32,8 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th | Class| API| Description| | -------- | -------- | -------- | - | RdbStore | insert(name: string, values: ValuesBucket, callback: AsyncCallback<number>):void | Inserts a row of data into a table. This method uses a callback to return the result.
- **name**: name of the target table.
- **values**: data to be inserted into the table.
- **callback**: callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| - | RdbStore | insert(name: string, values: ValuesBucket): Promise<number> | Inserts a row of data into a table. This method uses a promise to return the result.
- **name**: name of the target table.
- **values**: data to be inserted into the table.| + | RdbStore | insert(name: string, values: ValuesBucket, callback: AsyncCallback<number>):void | Inserts a row of data into a table. This method uses a callback to return the result.
- **name**: name of the target table.
- **values**: data to be inserted into the table.
- **callback**: callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| + | RdbStore | insert(name: string, values: ValuesBucket): Promise<number> | Inserts a row of data into a table. This method uses a promise to return the result.
- **name**: name of the target table.
- **values**: data to be inserted into the table.| - **Updating data** @@ -43,8 +43,8 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th | Class| API| Description| | -------- | -------- | -------- | - | RdbStore | update(values: ValuesBucket, rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void | Updates data in the RDB store based on the specified **RdbPredicates** object. This method uses a callback to return the result.
- **values**: data to update, which is stored in a **ValuesBucket**.
- **rdbPredicates**: conditions for updating data.
- **callback**: callback invoked to return the number of rows updated.| - | RdbStore | update(values: ValuesBucket, rdbPredicates: RdbPredicates): Promise | Updates data in the RDB store based on the specified **RdbPredicates** object. This method uses a promise to return the result.
- **values**: data to update, which is stored in a **ValuesBucket**.
- **rdbPredicates**: conditions for updating data.| + | RdbStore | update(values: ValuesBucket, rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void | Updates data in the RDB store based on the specified **RdbPredicates** object. This method uses a callback to return the result.
- **values**: data to update, which is stored in a **ValuesBucket**.
- **rdbPredicates**: conditions for updating data.
- **callback**: callback invoked to return the number of rows updated.| + | RdbStore | update(values: ValuesBucket, rdbPredicates: RdbPredicates): Promise\ | Updates data in the RDB store based on the specified **RdbPredicates** object. This method uses a promise to return the result.
- **values**: data to update, which is stored in a **ValuesBucket**.
- **rdbPredicates**: conditions for updating data.| - **Deleting data** @@ -54,8 +54,8 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th | Class| API| Description| | -------- | -------- | -------- | - | RdbStore | delete(rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void | Deletes data from the RDB store based on the specified **RdbPredicates** object. This method uses a callback to return the result.
- **rdbPredicates**: conditions for deleting data.
- **callback**: callback invoked to return the number of rows deleted.| - | RdbStore | delete(rdbPredicates: RdbPredicates): Promise | Deletes data from the RDB store based on the specified **RdbPredicates** object. This method uses a promise to return the result.
- **rdbPredicates**: conditions for deleting data.| + | RdbStore | delete(rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void | Deletes data from the RDB store based on the specified **RdbPredicates** object. This method uses a callback to return the result.
- **rdbPredicates**: conditions for deleting data.
- **callback**: callback invoked to return the number of rows deleted.| + | RdbStore | delete(rdbPredicates: RdbPredicates): Promise\ | Deletes data from the RDB store based on the specified **RdbPredicates** object. This method uses a promise to return the result.
- **rdbPredicates**: conditions for deleting data.| - **Querying data** @@ -68,10 +68,10 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th | Class| API| Description| | -------- | -------- | -------- | - | RdbStore | query(rdbPredicates: RdbPredicates, columns: Array, callback: AsyncCallback<ResultSet>): void | Queries data in the RDB store based on the specified **RdbPredicates** object. This method uses a callback to return the result.
- **rdbPredicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.
- **callback**: callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| - | RdbStore | query(rdbPredicates: RdbPredicates, columns: Array): Promise<ResultSet> | Queries data in the RDB store based on the specified **RdbPredicates** object. This method uses a promise to return the result.
- **rdbPredicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| - | RdbStore | querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void | Queries data in the RDB store using the specified SQL statement. This method uses a callback to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.
- **callback**: callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| - | RdbStore | querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> | Queries data in the RDB store using the specified SQL statement. This method uses a promise to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.| + | RdbStore | query(rdbPredicates: RdbPredicates, columns: Array, callback: AsyncCallback<ResultSet>): void | Queries data in the RDB store based on the specified **RdbPredicates** object. This method uses a callback to return the result.
- **rdbPredicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.
- **callback**: callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + | RdbStore | query(rdbPredicates: RdbPredicates, columns: Array): Promise<ResultSet> | Queries data in the RDB store based on the specified **RdbPredicates** object. This method uses a promise to return the result.
- **rdbPredicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| + | RdbStore | querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void | Queries data in the RDB store using the specified SQL statement. This method uses a callback to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.
- **callback**: callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + | RdbStore | querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> | Queries data in the RDB store using the specified SQL statement. This method uses a promise to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.| ### Using Predicates @@ -81,74 +81,76 @@ The RDB provides **RdbPredicates** for you to set database operation conditions. | Class| API| Description| | -------- | -------- | -------- | -| RdbPredicates |inDevices(devices: Array): RdbPredicates | Specifies remote devices on the network with RDB stores to be synchronized.
- **devices**: IDs of the remote devices on the network.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates |inAllDevices(): RdbPredicates | Connects to all remote devices on the network with RDB stores to be synchronized.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | equalTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | notEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | beginWrap(): RdbPredicates | Adds a left parenthesis to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with a left parenthesis.| -| RdbPredicates | endWrap(): RdbPredicates | Adds a right parenthesis to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with a right parenthesis.| -| RdbPredicates | or(): RdbPredicates | Adds the OR condition to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with the OR condition.| -| RdbPredicates | and(): RdbPredicates | Adds the AND condition to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with the AND condition.| -| RdbPredicates | contains(field: string, value: string): RdbPredicats | Sets the **RdbPredicates** to match a string containing the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified string.| -| RdbPredicates | beginsWith(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that starts with the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | endsWith(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that ends with the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | isNull(field: string): RdbPredicates | Sets the **RdbPredicates** to match the field whose value is null.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | isNotNull(field: string): RdbPredicates | Sets the **RdbPredicates** to match the field whose value is not null.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | like(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that is similar to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | glob(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match the specified string.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | between(field: string, low: ValueType, high: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value within the specified range.
- **field**: column name in the database table.
- **low**: minimum value that matches the **RdbPredicates**.
- **high**: maximum value that matches the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range.
- **field**: column name in the database table.
- **low**: minimum value that matches the **RdbPredicates**.
- **high**: maximum value that matches the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | greaterThan(field: string, value: ValueType): RdbPredicatesgr | Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | lessThan(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | orderByAsc(field: string): RdbPredicates | Sets the **RdbPredicates** to match the column with values sorted in ascending order.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | orderByDesc(field: string): RdbPredicates | Sets the **RdbPredicates** to match the column with values sorted in descending order.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | distinct(): RdbPredicates | Sets the **RdbPredicates** to filter out duplicate records.
- **RdbPredicates**: returns a **RdbPredicates** object that can filter out duplicate records.| -| RdbPredicates | limitAs(value: number): RdbPredicates | Sets the **RdbPredicates** to specify the maximum number of records.
- **value**: maximum number of records.
- **RdbPredicates**: returns a **RdbPredicates** object that can be used to set the maximum number of records.| -| RdbPredicates | offsetAs(rowOffset: number): RdbPredicates | Sets the **RdbPredicates** to specify the start position of the returned result.
- **rowOffset**: start position of the returned result. The value is a positive integer.
- **RdbPredicates**: returns a **RdbPredicates** object that specifies the start position of the returned result.| -| RdbPredicates | groupBy(fields: Array<string>): RdbPredicates | Sets the **RdbPredicates** to group rows that have the same value into summary rows.
- **fields**: names of the columns grouped for querying data.
- **RdbPredicates**: returns a **RdbPredicates** object that groups rows with the same value.| -| RdbPredicates | indexedBy(indexName: string): RdbPredicates | Sets the **RdbPredicates** to specify the index column.
- **indexName**: name of the index column.
- **RdbPredicates**: returns a **RdbPredicates** object that specifies the index column.| -| RdbPredicates | in(field: string, value: Array<ValueType>): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **Array<ValueType>** and value within the specified range.
- **field**: column name in the database table.
- **value**: array of **ValueType** to match.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | notIn(field: string, value: Array<ValueType>): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **Array<ValueType>** and value out of the specified range.
- **field**: column name in the database table.
- **value**: array of **ValueType** to match.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates |inDevices(devices: Array\): RdbPredicates | Specifies remote devices on the network with RDB stores to be synchronized.
- **devices**: IDs of the remote devices on the network.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates |inAllDevices(): RdbPredicates | Connects to all remote devices on the network with RDB stores to be synchronized.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | equalTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | notEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | beginWrap(): RdbPredicates | Adds a left parenthesis to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with a left parenthesis.| +| RdbPredicates | endWrap(): RdbPredicates | Adds a right parenthesis to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with a right parenthesis.| +| RdbPredicates | or(): RdbPredicates | Adds the OR condition to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with the OR condition.| +| RdbPredicates | and(): RdbPredicates | Adds the AND condition to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with the AND condition.| +| RdbPredicates | contains(field: string, value: string): RdbPredicats | Sets the **RdbPredicates** to match a string containing the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified string.| +| RdbPredicates | beginsWith(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that starts with the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | endsWith(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that ends with the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | isNull(field: string): RdbPredicates | Sets the **RdbPredicates** to match the field whose value is null.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | isNotNull(field: string): RdbPredicates | Sets the **RdbPredicates** to match the field whose value is not null.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | like(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that is similar to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | glob(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match the specified string.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | between(field: string, low: ValueType, high: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value within the specified range.
- **field**: column name in the database table.
- **low**: minimum value that matches the **RdbPredicates**.
- **high**: maximum value that matches the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range.
- **field**: column name in the database table.
- **low**: minimum value that matches the **RdbPredicates**.
- **high**: maximum value that matches the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | greaterThan(field: string, value: ValueType): RdbPredicatesgr | Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | lessThan(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | orderByAsc(field: string): RdbPredicates | Sets the **RdbPredicates** to match the column with values sorted in ascending order.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | orderByDesc(field: string): RdbPredicates | Sets the **RdbPredicates** to match the column with values sorted in descending order.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | distinct(): RdbPredicates | Sets the **RdbPredicates** to filter out duplicate records.
- **RdbPredicates**: returns a **RdbPredicates** object that can filter out duplicate records.| +| RdbPredicates | limitAs(value: number): RdbPredicates | Sets the **RdbPredicates** to specify the maximum number of records.
- **value**: maximum number of records.
- **RdbPredicates**: returns a **RdbPredicates** object that can be used to set the maximum number of records.| +| RdbPredicates | offsetAs(rowOffset: number): RdbPredicates | Sets the **RdbPredicates** to specify the start position of the returned result.
- **rowOffset**: start position of the returned result. The value is a positive integer.
- **RdbPredicates**: returns a **RdbPredicates** object that specifies the start position of the returned result.| +| RdbPredicates | groupBy(fields: Array<string>): RdbPredicates | Sets the **RdbPredicates** to group rows that have the same value into summary rows.
- **fields**: names of the columns grouped for querying data.
- **RdbPredicates**: returns a **RdbPredicates** object that groups rows with the same value.| +| RdbPredicates | indexedBy(indexName: string): RdbPredicates | Sets the **RdbPredicates** to specify the index column.
- **indexName**: name of the index column.
- **RdbPredicates**: returns a **RdbPredicates** object that specifies the index column.| +| RdbPredicates | in(field: string, value: Array<ValueType>): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **Array<ValueType>** and value within the specified range.
- **field**: column name in the database table.
- **value**: array of **ValueType** to match.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | notIn(field: string, value: Array<ValueType>): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **Array<ValueType>** and value out of the specified range.
- **field**: column name in the database table.
- **value**: array of **ValueType** to match.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| ### Using the Result Set A result set can be regarded as a row of data in the queried results. It allows you to traverse and access the data you have queried. The following table describes the external APIs of **ResultSet**. -> ![icon-notice.gif](public_sys-resources/icon-notice.gif) **NOTICE**
+> **NOTICE**
> After a result set is used, you must call the **close()** method to close it explicitly. **Table 7** APIs for using the result set | Class| API| Description| | -------- | -------- | -------- | -| ResultSet | goTo(offset:number): boolean | Moves the result set forwards or backwards by the specified offset relative to its current position.| -| ResultSet | goToRow(position: number): boolean | Moves the result set to the specified row.| -| ResultSet | goToNextRow(): boolean | Moves the result set to the next row.| -| ResultSet | goToPreviousRow(): boolean | Moves the result set to the previous row.| -| ResultSet | getColumnIndex(columnName: string): number | Obtains the column index based on the specified column name.| -| ResultSet | getColumnName(columnIndex: number): string | Obtains the column name based on the specified column index.| -| ResultSet | goToFirstRow(): boolean | Checks whether the result set is located in the first row.| -| ResultSet | goToLastRow(): boolean | Checks whether the result set is located in the last row.| -| ResultSet | getString(columnIndex: number): string | Obtains the value in the specified column of the current row, in a string.| -| ResultSet | getBlob(columnIndex: number): Uint8Array | Obtains the values in the specified column of the current row, in a byte array.| -| ResultSet | getDouble(columnIndex: number): number | Obtains the values in the specified column of the current row, in double.| -| ResultSet | isColumnNull(columnIndex: number): boolean | Checks whether the value in the specified column of the current row is null.| -| ResultSet | close(): void | Closes the result set.| +| ResultSet | goTo(offset:number): boolean | Moves the result set forwards or backwards by the specified offset relative to its current position.| +| ResultSet | goToRow(position: number): boolean | Moves the result set to the specified row.| +| ResultSet | goToNextRow(): boolean | Moves the result set to the next row.| +| ResultSet | goToPreviousRow(): boolean | Moves the result set to the previous row.| +| ResultSet | getColumnIndex(columnName: string): number | Obtains the column index based on the specified column name.| +| ResultSet | getColumnName(columnIndex: number): string | Obtains the column name based on the specified column index.| +| ResultSet | goToFirstRow(): boolean | Checks whether the result set is located in the first row.| +| ResultSet | goToLastRow(): boolean | Checks whether the result set is located in the last row.| +| ResultSet | getString(columnIndex: number): string | Obtains the value in the specified column of the current row, in a string.| +| ResultSet | getBlob(columnIndex: number): Uint8Array | Obtains the values in the specified column of the current row, in a byte array.| +| ResultSet | getDouble(columnIndex: number): number | Obtains the values in the specified column of the current row, in double.| +| ResultSet | isColumnNull(columnIndex: number): boolean | Checks whether the value in the specified column of the current row is null.| +| ResultSet | close(): void | Closes the result set.| ### Setting Distributed Tables +>**CAUTION**
ohos.permission.DISTRIBUTED_DATASYNC is requied for using the **setDistributedTables**, **obtainDistributedTableName**, **sync**, **on**, and **off** APIs of **RdbStore**. + **Setting Distributed Tables** **Table 8** APIs for setting distributed tables | Class| API| Description| | -------- | -------- | -------- | -| RdbStore | setDistributedTables(tables: Array, callback: AsyncCallback): void;| Sets a list of distributed tables. This method uses a callback to return the result.
-  **tables**: names of the distributed tables to set.
- **callback**: callback invoked to return the result.| -| RdbStore | setDistributedTables(tables: Array): Promise; | Sets a list of distributed tables. This method uses a promise to return the result.
-  **tables**: names of the distributed tables to set.| +| RdbStore | setDistributedTables(tables: Array\, callback: AsyncCallback\): void | Sets a list of distributed tables. This method uses a callback to return the result.
- **tables**: names of the distributed tables to set.
- **callback**: callback invoked to return the result.| +| RdbStore | setDistributedTables(tables: Array\): Promise\ | Sets a list of distributed tables. This method uses a promise to return the result.
- **tables**: names of the distributed tables to set.| **Obtaining the Distributed Table Name for a Remote Device** @@ -158,8 +160,8 @@ You can obtain the distributed table name for a remote device based on the local | Class| API| Description| | -------- | -------- | -------- | -| RdbStore | obtainDistributedTableName(device: string, table: string, callback: AsyncCallback): void; | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is used to query the RDB store of the remote device. This method uses a callback to return the result.
- **device**: remote device.
-  **table**: local table name.
-  **callback**: callback used to return the result. If the operation is successful, the distributed table name of the remote device will be returned. | -| RdbStore | obtainDistributedTableName(device: string, table: string): Promise; | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is used to query the RDB store of the remote device. This method uses a promise to return the result.
- **device**: remote device.
-  **table**: local table name.| +| RdbStore | obtainDistributedTableName(device: string, table: string, callback: AsyncCallback\): void | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is used to query the RDB store of the remote device. This method uses a callback to return the result.
- **device**: remote device.
- **table**: local table name.
- **callback**: callback used to return the result. If the operation is successful, the distributed table name of the remote device will be returned. | +| RdbStore | obtainDistributedTableName(device: string, table: string): Promise\ | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is used to query the RDB store of the remote device. This method uses a promise to return the result.
- **device**: remote device.
- **table**: local table name.| **Synchronizing Data Between Devices** @@ -167,8 +169,8 @@ You can obtain the distributed table name for a remote device based on the local | Class| API| Description| | -------- | -------- | -------- | -| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback>): void;| Synchronizes data between devices. This method uses a callback to return the result.
- **mode**: data synchronization mode. **SYNC\_MODE\_PUSH** means to push data from the local device to a remote device. **SYNC\_MODE\_PULL** means to pull data from a remote device to the local device.
- **predicates**: data and devices to be synchronized.
- **callback**: callback invoked to return the result. In the result, **string** indicates the device ID, and **number** indicates the synchronization status of each device. The value **0** indicates a success, and other values indicate a failure.| -| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise>;| Synchronizes data between devices. This method uses a promise to return the result.
- **mode**: data synchronization mode. **SYNC\_MODE\_PUSH** means to push data from the local device to a remote device. **SYNC\_MODE\_PULL** means to pull data from a remote device to the local device.
- **predicates**: data and devices to be synchronized. | +| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback\>): void | Synchronizes data between devices. This method uses a callback to return the result.
- **mode**: data synchronization mode. **SYNC\_MODE\_PUSH** means to push data from the local device to a remote device. **SYNC\_MODE\_PULL** means to pull data from a remote device to the local device.
- **predicates**: data and devices to be synchronized.
- **callback**: callback invoked to return the result. In the result, **string** indicates the device ID, and **number** indicates the synchronization status of each device. The value **0** indicates a success, and other values indicate a failure.| +| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\> | Synchronizes data between devices. This method uses a promise to return the result.
- **mode**: data synchronization mode. **SYNC\_MODE\_PUSH** means to push data from the local device to a remote device. **SYNC\_MODE\_PULL** means to pull data from a remote device to the local device.
- **predicates**: data and devices to be synchronized. | **Registering an RDB Store Observer** @@ -176,7 +178,7 @@ You can obtain the distributed table name for a remote device based on the local | Class| API| Description| | -------- | -------- | -------- | -| RdbStore |on(event: 'dataChange', type: SubscribeType, observer: Callback>): void;| Registers an observer for this RDB store to subscribe to distributed data changes. When data in the RDB store changes, a callback will be invoked to return the data changes.
- **type**: subscription type. **SUBSCRIBE\_TYPE\_REMOTE** means to subscribe to remote data changes.
- **observer**: observer that listens for data changes in the RDB store.| +| RdbStore |on(event: 'dataChange', type: SubscribeType, observer: Callback\>): void| Registers an observer for this RDB store to subscribe to distributed data changes. When data in the RDB store changes, a callback will be invoked to return the data changes.
- **type**: subscription type. **SUBSCRIBE\_TYPE\_REMOTE** means to subscribe to remote data changes.
- **observer**: observer that listens for data changes in the RDB store.| **Unregistering an RDB Store Observer** @@ -184,7 +186,7 @@ You can obtain the distributed table name for a remote device based on the local | Class| API| Description| | -------- | -------- | -------- | -| RdbStore |off(event:'dataChange', type: SubscribeType, observer: Callback>): void;| Unregisters the observer of the specified type for the RDB store. This method uses a callback to return the result.
-  **type**: subscription type. **SUBSCRIBE\_TYPE\_REMOTE** means to subscribe to remote data changes.
-  **observer**: observer to unregister.| +| RdbStore |off(event:'dataChange', type: SubscribeType, observer: Callback\>): void;| Unregisters the observer of the specified type for the RDB store. This API uses a callback to return the result.
- **type**: subscription type. **SUBSCRIBE\_TYPE\_REMOTE** means to subscribe to remote data changes.
- **observer**: observer to unregister.| ## How to Develop @@ -242,24 +244,37 @@ You can obtain the distributed table name for a remote device based on the local ``` 4. Set the distributed tables to be synchronized. - 1. Set the distributed tables. - 2. Check whether the setting is successful. + + 1. Add the following permission to the permission configuration file: + ```js + "requestPermissions": + { + "name": "ohos.permission.DISTRIBUTED_DATASYNC" + } + ``` + 2. Obtain the required permission. + 3. Set the distributed tables. + 4. Check whether the setting is successful. The sample code is as follows: - ```js - let promise = rdbStore.setDistributedTables(["test"]) - promise.then(() => { - console.info("setDistributedTables success.") - }).catch((err) => { - console.info("setDistributedTables failed.") - }) - ``` + ```js + let context = featureAbility.getContext(); + context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) { + console.info(`result.requestCode=${result.requestCode}`) + }) + let promise = rdbStore.setDistributedTables(["test"]) + promise.then(() => { + console.info("setDistributedTables success.") + }).catch((err) => { + console.info("setDistributedTables failed.") + }) + ``` - 5. Synchronize data across devices. +5. Synchronize data across devices. 1. Constructs an **RdbPredicates** object to specify remote devices within the network to be synchronized. 2. Call the **sync()** method to synchronize data. - 3. Check whether the data synchronization is successful. + 3. Check whether data synchronization is successful. The sample code is as follows: diff --git a/en/application-dev/device/usb-guidelines.md b/en/application-dev/device/usb-guidelines.md index 8476e88dc8ea1bf774b70991545dbd1d5f3620fe..e14b8bc1fa4e6755108faa6f9d0636f327bc95e4 100644 --- a/en/application-dev/device/usb-guidelines.md +++ b/en/application-dev/device/usb-guidelines.md @@ -8,7 +8,7 @@ In Host mode, you can obtain the list of connected devices, enable or disable th The USB service provides the following functions: query of USB device list, bulk data transfer, control transfer, and access permission management. -The following table lists the USB APIs currently available. For details, see the [API Reference](../reference/apis/js-apis-usb.md). +The following table lists the USB APIs currently available. For details, see the [API Reference](../reference/apis/js-apis-usb.md). **Table 1** Open USB APIs diff --git a/en/application-dev/media/audio-capturer.md b/en/application-dev/media/audio-capturer.md index 00ff76707d2e8d6a2d0ee7dee92fbe8ff92adc84..ab1664eb718591f8abdcd691f1b9ff37b2f97a14 100644 --- a/en/application-dev/media/audio-capturer.md +++ b/en/application-dev/media/audio-capturer.md @@ -1,152 +1,152 @@ # Audio Capture Development ---- -## ***Note***: - 1. This document applies to JavaScript. ---- -## **Summary** -This guide will show how a JS application can use AudioCapturer to record the audio. -Applications can use the APIs provided in this document to record raw audio files. - -## **AudioCapturer Framework** -The AudioCapturer interface is one of the most important components of the audio framework. -### **Audio Capturing:** -The AudioCapturer framework provides APIs for capturing raw audio files. - -## **Usage** -Here's an example of how to use AudioCapturer to capture a raw audio file. -1. Use **createAudioCapturer()** to create an AudioCapturer instance. Capturer parameters can be set in **audioCapturerOptions**.\ - This instance can be used to record, control, and obtain the recording status, as well as to register a callback for notifications. - ``` - var audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW - } - - var audioCapturerInfo = { - source: audio.SourceType.SOURCE_TYPE_MIC, - capturerFlags: 1 - } - - var audioCapturerOptions = { - streamInfo: audioStreamInfo, - capturerInfo: audioCapturerInfo - } - - let audioCapturer = await audio.createAudioCapturer(audioCapturerOptions); - var state = audioRenderer.state; - ``` +## When to Use + +You can use the APIs provided by **AudioCapturer** to record raw audio files. + +### State Check + +During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioCapturer** instance. This is because some operations can be performed only when the audio capturer is in a given state. If the application performs an operation when the audio capturer is not in the given state, the system may throw an exception or generate other undefined behavior. + +For details about the APIs, see [AudioCapturer in Audio Management](../reference/apis/js-apis-audio.md). + +**Figure 1** Audio capturer state + +![](figures/audio-capturer-state.png) + +## How to Develop + +1. Use **createAudioCapturer()** to create an **AudioCapturer** instance. + + Set parameters of the **AudioCapturer** instance in **audioCapturerOptions**. This instance is used to capture audio, control and obtain the recording status, and register a callback for notification. -2. (Optional) Subscribe to audio capturer state change events using the **on('stateChange')** API. - If an application wants to take some action based on the state updates in capturer, the application can subscribe to the state change event. - There are more events that applications can subscribe to, such as 'markReach' and 'periodReach'. Refer to [Audio](../reference/apis/js-apis-audio.md) for more details. + ```js + var audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, + channels: audio.AudioChannel.CHANNEL_1, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + } + + var audioCapturerInfo = { + source: audio.SourceType.SOURCE_TYPE_MIC, + capturerFlags: 1 + } + + var audioCapturerOptions = { + streamInfo: audioStreamInfo, + capturerInfo: audioCapturerInfo + } + + let audioCapturer = await audio.createAudioCapturer(audioCapturerOptions); + var state = audioRenderer.state; ``` + +2. (Optional) Use **on('stateChange')** to subscribe to audio renderer state changes. +If an application needs to perform some operations when the audio renderer state is updated, the application can subscribe to the state changes. For more events that can be subscribed to, see [Audio Management](../reference/apis/js-apis-audio.md). + + ```js audioCapturer.on('stateChange',(state) => { console.info('AudioCapturerLog: Changed State to : ' + state) switch (state) { - case audio.AudioState.STATE_PREPARED: - console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------'); - console.info('Audio State is : Prepared'); - break; - case audio.AudioState.STATE_RUNNING: - console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------'); - console.info('Audio State is : Running'); - break; - case audio.AudioState.STATE_STOPPED: - console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------'); - console.info('Audio State is : stopped'); - break; - case audio.AudioState.STATE_RELEASED: - console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------'); - console.info('Audio State is : released'); - break; - default: - console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------'); - console.info('Audio State is : invalid'); - break; - } + case audio.AudioState.STATE_PREPARED: + console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------'); + console.info('Audio State is : Prepared'); + break; + case audio.AudioState.STATE_RUNNING: + console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------'); + console.info('Audio State is : Running'); + break; + case audio.AudioState.STATE_STOPPED: + console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------'); + console.info('Audio State is : stopped'); + break; + case audio.AudioState.STATE_RELEASED: + console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------'); + console.info('Audio State is : released'); + break; + default: + console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------'); + console.info('Audio State is : invalid'); + break; + } }); - ``` -3. Call the **start()** function on the AudioCapturer instance to start/resume the recording task.\ - The capturer state will be STATE_RUNNING once the start is complete. The application can then begin reading buffers. - ``` - await audioCapturer.start(); - if (audioCapturer.state == audio.AudioState.STATE_RUNNING) { - console.info('AudioRecLog: Capturer started'); - } else { - console.info('AudioRecLog: Capturer start failed'); - } +3. Use **start()** to start audio recording. - ``` + The capturer state will be **STATE_RUNNING** once the audio capturer is started. The application can then begin reading buffers. -4. Obtain the minimum buffer size to read using the **getBufferSize()** API. + ```js + await audioCapturer.start(); + if (audioCapturer.state == audio.AudioState.STATE_RUNNING) { + console.info('AudioRecLog: Capturer started'); + } else { + console.info('AudioRecLog: Capturer start failed'); + } ``` - var bufferSize = await audioCapturer.getBufferSize(); - console.info('AudioRecLog: buffer size: ' + bufferSize); - ``` +4. Use **getBufferSize()** to obtain the minimum buffer size to read. -5. Read the captured audio data and convert it to a byte stream. Call the **read()** API repeatedly to read the data - until the application wants to stop the recording. The following example shows how to write recorded data into a file. + ```js + var bufferSize = await audioCapturer.getBufferSize(); + console.info('AudioRecLog: buffer size: ' + bufferSize); ``` - import fileio from '@ohos.fileio'; - - const path = '/data/data/.pulse_dir/capture_js.wav'; - let fd = fileio.openSync(path, 0o102, 0o777); - if (fd !== null) { - console.info('AudioRecLog: file fd created'); - } - else{ - console.info('AudioRecLog: file fd create : FAILED'); - return; - } - - fd = fileio.openSync(path, 0o2002, 0o666); - if (fd !== null) { - console.info('AudioRecLog: file fd opened in append mode'); - } - - var numBuffersToCapture = 150; - while (numBuffersToCapture) { - var buffer = await audioCapturer.read(bufferSize, true); - if (typeof(buffer) == undefined) { - console.info('read buffer failed'); - } else { - var number = fileio.writeSync(fd, buffer); - console.info('AudioRecLog: data written: ' + number); - } - - numBuffersToCapture--; - } - ``` -6. Once the recording is complete, call the **stop()** API on the AudioCapturer instance to stop the recording. - ``` - await audioCapturer.stop(); - if (audioCapturer.state == audio.AudioState.STATE_STOPPED) { - console.info('AudioRecLog: Capturer stopped'); - } else { - console.info('AudioRecLog: Capturer stop failed'); - } + +5. Read the captured audio data and convert it to a byte stream. Call **read()** repeatedly to read the data until the application wants to stop the recording. + + The following example shows how to write recorded data into a file. + + ```js + import fileio from '@ohos.fileio'; + + const path = '/data/data/.pulse_dir/capture_js.wav'; + let fd = fileio.openSync(path, 0o102, 0o777); + if (fd !== null) { + console.info('AudioRecLog: file fd created'); + } + else{ + console.info('AudioRecLog: file fd create : FAILED'); + return; + } + + fd = fileio.openSync(path, 0o2002, 0o666); + if (fd !== null) { + console.info('AudioRecLog: file fd opened in append mode'); + } + + var numBuffersToCapture = 150; + while (numBuffersToCapture) { + var buffer = await audioCapturer.read(bufferSize, true); + if (typeof(buffer) == undefined) { + console.info('read buffer failed'); + } else { + var number = fileio.writeSync(fd, buffer); + console.info('AudioRecLog: data written: ' + number); + } + + numBuffersToCapture--; + } ``` -7. After the recording task is complete, call the **release()** API on the AudioCapturer instance to release the stream resources. +6. Once the recording is complete, call **stop()** to stop the recording. + ``` - await audioCapturer.release(); - if (audioCapturer.state == audio.AudioState.STATE_RELEASED) { - console.info('AudioRecLog: Capturer released'); - } else { - console.info('AudioRecLog: Capturer release failed'); - } + await audioCapturer.stop(); + if (audioCapturer.state == audio.AudioState.STATE_STOPPED) { + console.info('AudioRecLog: Capturer stopped'); + } else { + console.info('AudioRecLog: Capturer stop failed'); + } ``` -## **Importance of State Check** -Application developers should keep in mind that an AudioCapturer is state-based. -That is, the AudioCapturer has an internal state that the application must always check when calling recorder control APIs, because some operations are only acceptable while the capturer is in a given state.\ -The system may throw an error/exception or generate other undefined behaviour if the application performs an operation while capturer is in an improper state. +7. After the task is complete, call **release()** to release related resources. -## **Other APIs** -See [AudioCapturer in the Audio API](../reference/apis/js-apis-audio.md) for more useful APIs like **getAudioTime**, **getCapturerInfo** and **getStreamInfo**. + ```js + await audioCapturer.release(); + if (audioCapturer.state == audio.AudioState.STATE_RELEASED) { + console.info('AudioRecLog: Capturer released'); + } else { + console.info('AudioRecLog: Capturer release failed'); + } + ``` diff --git a/en/application-dev/media/audio-renderer.md b/en/application-dev/media/audio-renderer.md index f9dfb75c2a08d6c8d641bbe0c8e7960efc6bc6ee..8e2be849396373aaa68ee7c4eb5e36a4cad28c1c 100644 --- a/en/application-dev/media/audio-renderer.md +++ b/en/application-dev/media/audio-renderer.md @@ -1,152 +1,124 @@ # Audio Rendering Development ---- -## ***Note***: - 1. This document applies to JavaScript. ---- -## **Summary** -This guide will show you how to use AudioRenderer to create an audio player app. -You can use the APIs provided in this document to play audio files in output devices and manage playback tasks. +## When to Use -## **AudioRenderer Framework** -The AudioRenderer interface is one of the most important components of the audio framework. -### **Audio Rendering:** -The AudioRenderer framework provides APIs for playing audio files and controlling the playback. -### **Audio Interruption:** -When a higher priority stream wants to play, the AudioRenderer framework interrupts the lower priority stream.\ -For example, if a call is arrived when you listen to music, the music playback, which is the lower priority stream, is paused.\ -With the sample code below, we'll look at how AudioInterrupt works in detail.\ -
-Please see [AudioRenderer in the Audio API](../reference/apis/js-apis-audio.md#audiorenderer8) for a list of supported audio stream types and formats, such as AudioSampleFormat, AudioChannel, AudioSampleFormat, and AudioEncodingType. +**AudioRenderer** provides APIs for rendering audio files and controlling playback. It also supports audio interruption. You can use the APIs provided by **AudioRenderer** to play audio files in output devices and manage playback tasks. +### Audio Interruption -## **Usage** -Here's an example of how to use AudioRenderer to play a raw audio file. -1. Use **createAudioRenderer** to create an AudioRenderer instance. Renderer parameters can be set in **audioRendererOptions**.\ - This object can be used to play, control, and obtain the status of the playback, as well as receive callback notifications. - ``` +When an audio stream with a higher priority needs to be played, the audio renderer interrupts the stream with a lower priority. For example, if a call comes in when the user is listening to music, the music playback, which is the lower priority stream, is paused. For details, see [How to Develop](#how-to-develop). + +### State Check + +During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioRenderer** instance. This is because some operations can be performed only when the audio renderer is in a given state. If the application performs an operation when the audio renderer is not in the given state, the system may throw an exception or generate other undefined behavior. + +**Figure 1** Audio renderer state + +![](figures/audio-renderer-state.png) + +### Asynchronous Operations + +To ensure that the UI thread is not blocked, most **AudioRenderer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the promise functions. For more information, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8). + + + +## How to Develop + +1. Use **createAudioRenderer()** to create an **AudioRenderer** instance. + Set parameters of the audio renderer in **audioCapturerOptions**. This instance is used to render audio, control and obtain the rendering status, and register a callback for notification. + + ```js var audioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW } - + var audioRendererInfo = { content: audio.ContentType.CONTENT_TYPE_SPEECH, usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, rendererFlags: 1 } - + var audioRendererOptions = { streamInfo: audioStreamInfo, rendererInfo: audioRendererInfo } - + let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); ``` -2. Subscribe to audio interruption events using the **on** API.\ - Stream-A is interrupted when Stream-B with a higher or equal priority requests to become active and use the output device.\ - In some cases, the framework takes forced actions like pausing and ducking, and notifies the app using **InterruptEvent**. In other cases, the app can take action. In this situation, the app can choose to act on the **InterruptEvent** or ignore it. When the app is interrupted by forced action, it should handle the state, update the user interface, and so on. - - In case of audio interrupts, the app may encounter write failures. Interrupt unaware apps can check the renderer state using the **audioRenderer.state** API before writing audio data, whereas interrupt aware apps will have more details accessible via this listener.\ -
- The following information will be provided by the Interrupt Event Notification: - - 1) **eventType:** Whether the interruption has begun or ended. - - | Value | Description | - | :------------------- | :-------------------------------------------- | - | INTERRUPT_TYPE_BEGIN | Indicates that the interruption has started. | - | INTERRUPT_TYPE_END | Indicates that the interruption has finished. | - - 2) **forceType:** Whether the framework has already taken action or if the app is being suggested to take action. - - | Value | Description | - | :-------------- | :------------------------------------------------------------------ | - | INTERRUPT_FORCE | The audio state has been changed by the framework. | - | INTERRUPT_SHARE | The app can decide whether or not to respond to the InterruptEvent. | - - 3) **hintType:** The kind of action taken or to be taken. - - | Value | Description | - | :-------------------- | :--------------------------- | - | INTERRUPT_HINT_PAUSE | Pausing the playback. | - | INTERRUPT_HINT_RESUME | Resuming the playback. | - | INTERRUPT_HINT_STOP | Stopping the playback. | - | INTERRUPT_HINT_DUCK | Ducking the stream volume. | - | INTERRUPT_HINT_UNDUCK | Unducking the stream volume. | - - 4) **Some actions are exclusively forced or shared**, which means that they are performed by either the framework or the app.\ - For instance, when a call is received while a music stream is ongoing, the framework forces the music stream to pause. When the call is finished, the framework will not forcibly resume the music stream. Instead, it will alert the app to resume the playback. - - | Action | Description | - | :-------------------- | :-------------------------------------------------------------------------------- | - | INTERRUPT_HINT_RESUME | INTERRUPT_SHARE is always the forceType. It can only be done by the app. | - | INTERRUPT_HINT_DUCK | INTERRUPT_FORCE is always the forceType. It will always be done by the framework. | - | INTERRUPT_HINT_UNDUCK | INTERRUPT_FORCE is always the forceType. It will always be done by the framework. | - +2. Use **on('interrupt')** to subscribe to audio interruption events. + + Stream-A is interrupted when Stream-B with a higher or equal priority requests to become active and use the output device. + + In some cases, the audio renderer performs forcible operations such as pausing and ducking, and notifies the application through **InterruptEvent**. In other cases, the application can choose to act on the **InterruptEvent** or ignore it. + + In the case of audio interruption, the application may encounter write failures. To avoid such failures, interruption unaware applications can use **audioRenderer.state** to check the renderer state before writing audio data. The applications can obtain more details by subscribing to the audio interruption events. For details, see [InterruptEvent](../reference/apis/js-apis-audio.md#interruptevent9). + + ```js + audioRenderer.on('interrupt', (interruptEvent) => { + console.info('InterruptEvent Received'); + console.info('InterruptType: ' + interruptEvent.eventType); + console.info('InterruptForceType: ' + interruptEvent.forceType); + console.info('AInterruptHint: ' + interruptEvent.hintType); + + if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { + switch (interruptEvent.hintType) { + // Force Pause: Action was taken by framework. + // Halt the write calls to avoid data loss. + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + isPlay = false; + break; + // Force Stop: Action was taken by framework. + // Halt the write calls to avoid data loss. + case audio.InterruptHint.INTERRUPT_HINT_STOP: + isPlay = false; + break; + // Force Duck: Action was taken by framework, + // just notifying the app that volume has been reduced. + case audio.InterruptHint.INTERRUPT_HINT_DUCK: + break; + // Force Unduck: Action was taken by framework, + // just notifying the app that volume has been restored. + case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: + break; + } + } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { + switch (interruptEvent.hintType) { + // Share Resume: Action is to be taken by App. + // Resume the force paused stream if required. + case audio.InterruptHint.INTERRUPT_HINT_RESUME: + startRenderer(); + break; + // Share Pause: Stream has been interrupted, + // It can choose to pause or play concurrently. + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + isPlay = false; + pauseRenderer(); + break; + } + } + }); ``` - audioRenderer.on('interrupt', (interruptEvent) => { - console.info('InterruptEvent Received'); - console.info('InterruptType: ' + interruptEvent.eventType); - console.info('InterruptForceType: ' + interruptEvent.forceType); - console.info('AInterruptHint: ' + interruptEvent.hintType); - if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { - switch (interruptEvent.hintType) { - // Force Pause: Action was taken by framework. - // Halt the write calls to avoid data loss. - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - isPlay = false; - break; - // Force Stop: Action was taken by framework. - // Halt the write calls to avoid data loss. - case audio.InterruptHint.INTERRUPT_HINT_STOP: - isPlay = false; - break; - // Force Duck: Action was taken by framework, - // just notifying the app that volume has been reduced. - case audio.InterruptHint.INTERRUPT_HINT_DUCK: - break; - // Force Unduck: Action was taken by framework, - // just notifying the app that volume has been restored. - case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: - break; - } - } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { - switch (interruptEvent.hintType) { - // Share Resume: Action is to be taken by App. - // Resume the force paused stream if required. - case audio.InterruptHint.INTERRUPT_HINT_RESUME: - startRenderer(); - break; - // Share Pause: Stream has been interrupted, - // It can choose to pause or play concurrently. - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - isPlay = false; - pauseRenderer(); - break; - } - } - }); - ``` +3. Use **start()** to start audio rendering. + + The renderer state will be **STATE_RUNNING** once the audio renderer is started. The application can then begin reading buffers. -4. Call the **start()** function on the AudioRenderer instance to start/resume the playback task.\ - The renderer state will be STATE_RUNNING once the start is complete. You can then begin writing buffers. - ``` + ```js async function startRenderer() { var state = audioRenderer.state; - // state should be prepared, paused or stopped. + // The state should be prepared, paused, or stopped. if (state != audio.AudioState.STATE_PREPARED || state != audio.AudioState.STATE_PAUSED || state != audio.AudioState.STATE_STOPPED) { console.info('Renderer is not in a correct state to start'); return; } - + await audioRenderer.start(); - + state = audioRenderer.state; if (state == audio.AudioState.STATE_RUNNING) { console.info('Renderer started'); @@ -154,11 +126,13 @@ Here's an example of how to use AudioRenderer to play a raw audio file. console.error('Renderer start failed'); } } - - ``` -5. Make **write** calls to start rendering the buffers. - Read the audio data to be played into a buffer. Call the write function repeatedly to write data. ``` + +4. Call **write()** to write data to the buffer. + + Read the audio data to be played to the buffer. Call **write()** repeatedly to write the data to the buffer. + + ```js async function writeBuffer(buf) { var state = audioRenderer.state; if (state != audio.AudioState.STATE_RUNNING) { @@ -167,13 +141,13 @@ Here's an example of how to use AudioRenderer to play a raw audio file. return; } let writtenbytes = await audioRenderer.write(buf); - + console.info('Actual written bytes: ' + writtenbytes); if (writtenbytes < 0) { console.error('Write buffer failed. check the state of renderer'); } } - + // Reasonable minimum buffer size for renderer. However, the renderer can accept other read sizes as well. const bufferSize = await audioRenderer.getBufferSize(); const path = '/data/file_example_WAV_2MG.wav'; @@ -183,7 +157,7 @@ Here's an example of how to use AudioRenderer to play a raw audio file. let discardHeader = new ArrayBuffer(44); ss.readSync(discardHeader); rlen += 44; - + var id = setInterval(() => { if (isPlay || isRelease) { if (rlen >= totalSize || isRelease) { @@ -201,74 +175,65 @@ Here's an example of how to use AudioRenderer to play a raw audio file. } , 30); // interval to be set based on audio file format ``` -6. (Optional) Call the **pause()** or **stop()** function on the AudioRenderer instance. -``` - async function pauseRenderer() { - var state = audioRenderer.state; - if (state != audio.AudioState.STATE_RUNNING) { - console.info('Renderer is not running'); - return; - } - - await audioRenderer.pause(); - - state = audioRenderer.state; - if (state == audio.AudioState.STATE_PAUSED) { - console.info('Renderer paused'); - } else { - console.error('Renderer pause failed'); - } - } - - async function stopRenderer() { - var state = audioRenderer.state; - if (state != audio.AudioState.STATE_RUNNING || state != audio.AudioState.STATE_PAUSED) { - console.info('Renderer is not running or paused'); - return; - } - - await audioRenderer.stop(); - - state = audioRenderer.state; - if (state == audio.AudioState.STATE_STOPPED) { - console.info('Renderer stopped'); - } else { - console.error('Renderer stop failed'); - } -} -``` - -7. After the playback task is complete, call the **release()** function on the AudioRenderer instance to release resources.\ - AudioRenderer can use a lot of system resources. As a result, whenever the resources are no longer required, they must be released. To ensure that any system resources allocated to it are appropriately released, you should always call **release()**. -``` - async function releaseRenderer() { - if (state_ == RELEASED || state_ == NEW) { - console.info('Resourced already released'); - return; - } - - await audioRenderer.release(); - - state = audioRenderer.state; - if (state == STATE_RELEASED) { - console.info('Renderer released'); - } else { - console.info('Renderer release failed'); - } - - } -``` - -## **Importance of State Check:** -You should also keep in mind that an AudioRenderer is state-based. -That is, the AudioRenderer has an internal state that you must always check when calling playback control APIs, because some operations are only acceptable while the renderer is in a given state.\ -The system may throw an error/exception or generate other undefined behaviour if you perform an operation while in the improper state.\ +5. (Optional) Call **pause()** or **stop()** to pause or stop rendering. + + ```js + async function pauseRenderer() { + var state = audioRenderer.state; + if (state != audio.AudioState.STATE_RUNNING) { + console.info('Renderer is not running'); + return; + } + + await audioRenderer.pause(); + + state = audioRenderer.state; + if (state == audio.AudioState.STATE_PAUSED) { + console.info('Renderer paused'); + } else { + console.error('Renderer pause failed'); + } + } + + async function stopRenderer() { + var state = audioRenderer.state; + if (state != audio.AudioState.STATE_RUNNING || state != audio.AudioState.STATE_PAUSED) { + console.info('Renderer is not running or paused'); + return; + } + + await audioRenderer.stop(); + + state = audioRenderer.state; + if (state == audio.AudioState.STATE_STOPPED) { + console.info('Renderer stopped'); + } else { + console.error('Renderer stop failed'); + } + } + ``` -## **Asynchronous Operations:** -Most of the AudioRenderer calls are asynchronous. As a result, the UI thread will not be blocked.\ -For each API, the framework provides both callback and promises functions.\ -In the example, promise functions are used for simplicity. [AudioRender in the Audio API](../reference/apis/js-apis-audio.md#audiorenderer8) -provides reference for both callback and promise. +6. After the task is complete, call **release()** to release related resources. + + **AudioRenderer** uses a large number of system resources. Therefore, ensure that the resources are released after the task is complete. + + ```js + async function releaseRenderer() { + if (state_ == RELEASED || state_ == NEW) { + console.info('Resourced already released'); + return; + } + + await audioRenderer.release(); + + state = audioRenderer.state; + if (state == STATE_RELEASED) { + console.info('Renderer released'); + } else { + console.info('Renderer release failed'); + } + + } + ``` -## **Other APIs:** -See [Audio](../reference/apis/js-apis-audio.md) for more useful APIs like getAudioTime, drain, and getBufferSize. + diff --git a/en/application-dev/media/figures/audio-capturer-state.png b/en/application-dev/media/figures/audio-capturer-state.png new file mode 100644 index 0000000000000000000000000000000000000000..52b5556260dbf78c5e816b37013248a07e8dbbc6 Binary files /dev/null and b/en/application-dev/media/figures/audio-capturer-state.png differ diff --git a/en/application-dev/media/figures/audio-renderer-state.png b/en/application-dev/media/figures/audio-renderer-state.png new file mode 100644 index 0000000000000000000000000000000000000000..9ae30c2a9306dc85662405c36da9e11d07ed9a2a Binary files /dev/null and b/en/application-dev/media/figures/audio-renderer-state.png differ diff --git a/en/application-dev/napi/Readme-EN.md b/en/application-dev/napi/Readme-EN.md index ebcb811f7886a097c741198f0696b61327cefefb..9ab337ed1c29e18772ff4e348c47e3202f74815f 100644 --- a/en/application-dev/napi/Readme-EN.md +++ b/en/application-dev/napi/Readme-EN.md @@ -1,6 +1,6 @@ # Native APIs - [Using Native APIs in Application Projects](napi-guidelines.md) - +- [Drawing Development](drawing-guidelines.md) - [Raw File Development](rawfile-guidelines.md) diff --git a/en/application-dev/napi/drawing-guidelines.md b/en/application-dev/napi/drawing-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..e813f84d92d4155e78c9ca651af6a3e3cd010232 --- /dev/null +++ b/en/application-dev/napi/drawing-guidelines.md @@ -0,0 +1,208 @@ +# Drawing Development + +## When to Use + +The Native Drawing module provides APIs for drawing 2D graphics and text. The following scenarios are common for drawing development: +* Drawing 2D graphics +* Drawing and painting text + +## Available APIs + +| API| Description| +| -------- | -------- | +| OH_Drawing_BitmapCreate (void) | Creates a bitmap object.| +| OH_Drawing_BitmapBuild (OH_Drawing_Bitmap *, const uint32_t width, const uint32_t height, const OH_Drawing_BitmapFormat *) | Initializes the width and height of a bitmap object and sets the pixel format for the bitmap.| +| OH_Drawing_CanvasCreate (void) | Creates a canvas object.| +| OH_Drawing_CanvasBind (OH_Drawing_Canvas *, OH_Drawing_Bitmap *) | Binds a bitmap to a canvas so that the content drawn on the canvas is output to the bitmap (this process is called CPU rendering).| +| OH_Drawing_CanvasAttachBrush (OH_Drawing_Canvas *, const OH_Drawing_Brush *) | Attaches a brush to a canvas so that the canvas will use the style and color of the brush to fill in a shape.| +| OH_Drawing_CanvasAttachPen (OH_Drawing_Canvas *, const OH_Drawing_Pen *) | Attaches a pen to a canvas so that the canvas will use the style and color of the pen to outline a shape.| +| OH_Drawing_CanvasDrawPath (OH_Drawing_Canvas *, const OH_Drawing_Path *) | Draws a path.| +| OH_Drawing_PathCreate (void) | Creates a path object.| +| OH_Drawing_PathMoveTo (OH_Drawing_Path *, float x, float y) | Sets the start point of a path.| +| OH_Drawing_PathLineTo (OH_Drawing_Path *, float x, float y) | Draws a line segment from the last point of a path to the target point. | +| OH_Drawing_PathClose (OH_Drawing_Path *) | Closes a path. A line segment from the start point to the last point of the path is added.| +| OH_Drawing_PenCreate (void) | Creates a pen object.| +| OH_Drawing_PenSetAntiAlias (OH_Drawing_Pen *, bool) | Checks whether anti-aliasing is enabled for a pen. If anti-aliasing is enabled, edges will be drawn with partial transparency.| +| OH_Drawing_PenSetWidth (OH_Drawing_Pen *, float width) | Sets the thickness for a pen. This thickness determines the width of the outline of a shape.| +| OH_Drawing_BrushCreate (void) | Creates a brush object.| +| OH_Drawing_BrushSetColor (OH_Drawing_Brush *, uint32_t color) | Sets the color for a brush. The color will be used by the brush to fill in a shape.| +| OH_Drawing_CreateTypographyStyle (void) | Creates a `TypographyStyle` object.| +| OH_Drawing_CreateTextStyle (void) | Creates a `TextStyle` object.| +| OH_Drawing_TypographyHandlerAddText (OH_Drawing_TypographyCreate *, const char *) | Sets the text content.| +| OH_Drawing_TypographyPaint (OH_Drawing_Typography *, OH_Drawing_Canvas *, double, double) | Paints text on the canvas.| + + + +## Development Procedure for 2D Graphics Drawing + +The following steps describe how to use the canvas and brush of the Native Drawing module to draw a 2D graphics. + +1. **Create a bitmap object.** Use `OH_Drawing_BitmapCreate` in `drawing_bitmap.h` to create a bitmap object (named `cBitmap` in this example), and use `OH_Drawing_BitmapBuild` to specify its length, width, and pixel format. + + ```c++ + // Create a bitmap object. + OH_Drawing_Bitmap* cBitmap = OH_Drawing_BitmapCreate(); + // Define the pixel format of the bitmap. + OH_Drawing_BitmapFormat cFormat {COLOR_FORMAT_RGBA_8888, ALPHA_FORMAT_OPAQUYE}; + // Set the pixel format for the bitmap. + OH_Drawing_BitmapBuild(cBitmap, width, height, &cFormat); + ``` + +2. **Create a canvas object.** Use `OH_Drawing_CanvasCreate` in `drawing_canvas.h` to create a canvas object (named `cCanvas` in this example), and use `OH_Drawing_CanvasBind` to bind `cBitmap` to this canvas. The content drawn on the canvas will be output to the bound `cBitmap` object. + + ```c++ + // Create a canvas object. + OH_Drawing_Canvas* cCanvas = OH_Drawing_CanvasCreate(); + // Bind the bitmap to the canvas. The content drawn on the canvas will be output to the bound bitmap memory. + OH_Drawing_CanvasBind(cCanvas, cBitmap); + // Use white to clear the canvas. + OH_Drawing_CanvasClear(cCanvas, OH_Drawing_ColorSetArgb(0xFF, 0xFF, 0xFF, 0xFF)); + ``` + +3. **Construct a shape.** Use the APIs provided in `drawing_path.h` to draw a pentagram `cPath`. + + ```c++ + int len = 300; + + float aX = 500; + float aY = 500; + + float dX = aX - len * std::sin(18.0f); + float dY = aY + len * std::cos(18.0f); + + float cX = aX + len * std::sin(18.0f); + float cY = dY; + + float bX = aX + (len / 2.0); + float bY = aY + std::sqrt((cX - dX) * (cX - dX) + (len / 2.0) * (len / 2.0)); + + float eX = aX - (len / 2.0); + float eY = bY; + + // Create a path object and use the APIs to draw a pentagram. + OH_Drawing_Path* cPath = OH_Drawing_PathCreate(); + // Specify the start point of the path. + OH_Drawing_PathMoveTo(cPath, aX, aY); + // Draw a line segment from the last point of a path to the target point. + OH_Drawing_PathLineTo(cPath, bX, bY); + OH_Drawing_PathLineTo(cPath, cX, cY); + OH_Drawing_PathLineTo(cPath, dX, dY); + OH_Drawing_PathLineTo(cPath, eX, eY); + // Close the path. Now the path is drawn. + OH_Drawing_PathClose(cPath); + ``` + +4. **Set the brush and pen styles.** Use `OH_Drawing_PenCreate` in `drawing_pen.h` to create a pen (named `cPen` in this example), and set the attributes such as the anti-aliasing, color, and thickness. The pen is used to outline a shape. Use `OH_Drawing_BrushCreate` in `drawing_brush.h` to create a brush (named `cBrush` in this example), and set the brush color. The brush is used to fill in a shape. Use `OH_Drawing_CanvasAttachPen` and `OH_Drawing_CanvasAttachBrush` in `drawing_canvas.h` to attach the pen and brush to the canvas. + + ```c++ + // Create a pen object and set the anti-aliasing, color, and thickness. + OH_Drawing_Pen* cPen = OH_Drawing_PenCreate(); + OH_Drawing_PenSetAntiAlias(cPen, true); + OH_Drawing_PenSetColor(cPen, OH_Drawing_ColorSetArgb(0xFF, 0xFF, 0x00, 0x00)); + OH_Drawing_PenSetWidth(cPen, 10.0); + OH_Drawing_PenSetJoin(cPen, LINE_ROUND_JOIN); + // Attach the pen to the canvas. + OH_Drawing_CanvasAttachPen(cCanvas, cPen); + + // Create a brush object and set the color. + OH_Drawing_Brush* cBrush = OH_Drawing_BrushCreate(); + OH_Drawing_BrushSetColor(cBrush, OH_Drawing_ColorSetArgb(0xFF, 0x00, 0xFF, 0x00)); + + // Attach the brush to the canvas. + OH_Drawing_CanvasAttachBrush(cCanvas, cBrush); + ``` + +5. **Draw a shape.** Use `OH_Drawing_CanvasDrawPath` in `drawing_canvas.h` to draw a pentagram on the canvas. Call the corresponding APIs to destroy the objects when they are no longer needed. + + ```c++ + // Draw a pentagram on the canvas. The outline of the pentagram is drawn by the pen, and the color is filled in by the brush. + OH_Drawing_CanvasDrawPath(cCanvas, cPath); + // Destroy the created objects when they are no longer needed. + OH_Drawing_BrushDestory(cBrush); + OH_Drawing_PenDestory(cPen); + OH_Drawing_PathDestory(cPath); + ``` + +6. **Obtain pixel data.** Use `OH_Drawing_BitmapGetPixels` in `drawing_bitmap.h` to obtain the pixel address of the bitmap bound to the canvas. The memory to which the address points contains the pixel data of the drawing on the canvas. + + ```c++ + // Obtain the pixel address after drawing. The memory to which the address points contains the pixel data of the drawing on the canvas. + void* bitmapAddr = OH_Drawing_BitmapGetPixels(cBitmap); + auto ret = memcpy_s(addr, addrSize, bitmapAddr, addrSize); + if (ret != EOK) { + LOGI("memcpy_s failed"); + } + // Destroy the canvas object. + OH_Drawing_CanvasDestory(cCanvas); + // Destroy the bitmap object. + OH_Drawing_BitmapDestory(cBitmap); + ``` + +## Development Procedure for Text Drawing and Display + +The following steps describe how to use the text drawing and display feature of the Native Drawing module. +1. **Create a canvas and a bitmap.** + + ```c++ + // Create a bitmap. + OH_Drawing_Bitmap* cBitmap = OH_Drawing_BitmapCreate(); + OH_Drawing_BitmapFormat cFormat {COLOR_FORMAT_RGBA_8888, ALPHA_FORMAT_OPAQUE}; + OH_Drawing_BitmapBuild(cBitmap, width, height, &cFormat); + // Create a canvas. + OH_Drawing_Canvas* cCanvas = OH_Drawing_CanvasCreate(); + OH_Drawing_CanvasBind(cCanvas, cBitmap); + OH_Drawing_CanvasClear(cCanvas, OH_Drawing_ColorSetArgb(0xFF, 0xFF, 0xFF, 0xFF)); + ``` + +2. **Set the typography style.** + + ```c++ + // Set the typography attributes such as left to right (LTR) for the text direction and left-aligned for the text alignment mode. + OH_Drawing_TypographyStyle* typoStyle = OH_Drawing_CreateTypographyStyle(); + OH_Drawing_SetTypographyTextDirection(typoStyle, TEXT_DIRECTION_LTR); + OH_Drawing_SetTypographyTextAlign(typoStyle, TEXT_ALIGN_LEFT); + ``` + +3. **Set the text style.** + + ```c++ + // Set the text color, for example, black. + OH_Drawing_TextStyle* txtStyle = OH_Drawing_CreateTextStyle(); + OH_Drawing_SetTextStyleColor(txtStyle, OH_Drawing_ColorSetArgb(0xFF, 0x00, 0x00, 0x00)); + // Set text attributes such as the font size and weight. + double fontSize = 30; + OH_Drawing_SetTextStyleFontSize(txtStyle, fontSize); + OH_Drawing_SetTextStyleFontWeight(txtStyle, FONT_WEIGHT_400); + OH_Drawing_SetTextStyleBaseLine(txtStyle, TEXT_BASELINE_ALPHABETIC); + OH_Drawing_SetTextStyleFontHeight(txtStyle, 1); + // Set the font families. + const char* fontFamilies[] = {"Roboto"}; + OH_Drawing_SetTextStyleFontFamilies(txtStyle, 1, fontFamilies); + OH_Drawing_SetTextStyleFontStyle(txtStyle, FONT_STYLE_NORMAL); + OH_Drawing_SetTextStyleLocale(txtStyle, "en"); + ``` + +4. **Generate the final text display effect.** + + ```c++ + OH_Drawing_TypographyCreate* handler = OH_Drawing_CreateTypographyHandler(typoStyle, + OH_Drawing_CreateFontCollection()); + OH_Drawing_TypographyHandlerPushTextStyle(handler, txtStyle); + // Set the text content. + const char* text = "OpenHarmony\n"; + OH_Drawing_TypographyHandlerAddText(handler, text); + OH_Drawing_TypographyHandlerPopTextStyle(handler); + OH_Drawing_Typography* typography = OH_Drawing_CreateTypography(handler); + // Set the maximum width. + double maxWidth = 800.0; + OH_Drawing_TypographyLayout(typography, maxWidth); + // Set the start position for text display. + double position[2] = {10.0, 15.0}; + OH_Drawing_TypographyPaint(typography, cCanvas, position[0], position[1]); + ``` + +## Samples + +The following samples are provided to help you better understand how to use the Native Drawing module: +* [2D Graphics Drawing Using Native Drawing](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/2d_graphics/drawing_c_sample.cpp) +* [Text Drawing and Painting Using Native Drawing](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/text/renderservice/drawing_text_c_sample.cpp) diff --git a/en/application-dev/napi/rawfile-guidelines.md b/en/application-dev/napi/rawfile-guidelines.md index 29f66194bd40cd4f7a228213734db2ad65c81180..c585b162a2dc483ca72a5369170b2ee0f43a01a1 100644 --- a/en/application-dev/napi/rawfile-guidelines.md +++ b/en/application-dev/napi/rawfile-guidelines.md @@ -4,7 +4,7 @@ ## When to Use -This document describes how to use the native Rawfile APIs to manage raw file directories and files in OpenHarmony. The table below describes the APIs. +This document describes how to use the native Rawfile APIs to manage raw file directories and files in OpenHarmony. You can use the APIs to traverse, open, search for, read, and close raw files. ## Available APIs @@ -16,14 +16,14 @@ This document describes how to use the native Rawfile APIs to manage raw file di | const char *OH_ResourceManager_GetRawFileName(RawDir *rawDir, int index) | Obtains the name of a raw file. | | RawFile *OH_ResourceManager_OpenRawFile(const NativeResourceManager *mgr, const char *fileName) | Opens a raw file. | | long OH_ResourceManager_GetRawFileSize(RawFile *rawFile) | Obtains the size of a raw file. | -| int OH_ResourceManager_SeekRawFile(const RawFile *rawFile, long offset, int whence) | Seeks a data read/write position in a raw file based on the specified offset. | +| int OH_ResourceManager_SeekRawFile(const RawFile *rawFile, long offset, int whence) | Seeks a read/write position in a raw file based on the specified offset. | | long OH_ResourceManager_GetRawFileOffset(const RawFile *rawFile) | Obtains the offset. | | int OH_ResourceManager_ReadRawFile(const RawFile *rawFile, void *buf, size_t length) | Reads a raw file. | | void OH_ResourceManager_CloseRawFile(RawFile *rawFile) | Closes a raw file to release resources. | | void OH_ResourceManager_CloseRawDir(RawDir *rawDir) | Closes a raw file directory to release resources. | -| bool OH_ResourceManager_GetRawFileDescriptor(const RawFile *rawFile, RawFileDescriptor &descriptor) | Obtains the file description (FD) of a raw file. | +| bool OH_ResourceManager_GetRawFileDescriptor(const RawFile *rawFile, RawFileDescriptor &descriptor) | Obtains the file descriptor (FD) of a raw file. | | bool OH_ResourceManager_ReleaseRawFileDescriptor(const RawFileDescriptor &descriptor) | Releases the FD of a raw file. | -| void OH_ResourceManager_ReleaseNativeResourceManager(NativeResourceManager *resMgr) | Releases native resource manager resources. | +| void OH_ResourceManager_ReleaseNativeResourceManager(NativeResourceManager *resMgr) | Releases the native resource manager. | ## How to Develop @@ -38,7 +38,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di 2. Call **OH_ResourceManager_InitNativeResourceManager(napi_env env, napi_value jsResMgr)** to obtain a **NativeResourceManager** instance. ```js - // Call the JS API to pass the JS resource manager. + // Import the JS resource manager from the JS head file and pass it to the C++ file. import resManager from '@ohos.resourceManager' import rawfileTest from 'librawFileTest.so' resManager.getResourceManager().then(resmgr => { @@ -49,7 +49,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di ``` ```c++ - // The C++ API obtains and parses the parameters passed by the JS API. + // Obtain and parse the parameters in the C++ file. NativeResourceManager* nativeResourceManager = nullptr; std::string path; if (i == 0 && valueType == napi_string) { @@ -57,7 +57,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di ...... path = buf.data(); } else if (i == 1 && valueType == napi_object) { - // Parse the second parameter, which is the resource manager. + // Parse the second parameter, which is the JS resource manager. nativeResourceManager = OH_ResourceManager_InitNativeResourceManager(env, argv[i]); } ``` @@ -80,7 +80,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di -5. Call **OH_ResourceManager_GetRawFileName** to obtain the name of the raw file based on the specified index. +5. Call **OH_ResourceManager_GetRawFileName** to obtain the name of the raw file with the specified index. ```c++ for (int index = 0; index < count; index++) { @@ -90,7 +90,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di -6. Call **OH_ResourceManager_OpenRawFile** to obtain a **RawFile** instance based on the specified file name. +6. Call **OH_ResourceManager_OpenRawFile** to obtain a **RawFile** instance with the specified file name. ```c++ RawFile* rawFile = OH_ResourceManager_OpenRawFile(nativeResourceManager, fileName.c_str()); @@ -106,7 +106,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di -8. Call **OH_ResourceManager_SeekRawFile** to seek a data read/write position in the raw file based on the specified offset. +8. Call **OH_ResourceManager_SeekRawFile** to seek a read/write position in the raw file based on the specified offset. ```c++ int position = OH_ResourceManager_SeekRawFile(rawFile, 10, 0); @@ -124,7 +124,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di -10. Call **OH_ResourceManager_ReadRawFile** to read a raw file. +10. Call **OH_ResourceManager_ReadRawFile** to read the raw file. ```c++ std::unique_ptr mediaData = std::make_unique(rawFileSize); @@ -149,7 +149,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di -13. Call **OH_ResourceManager_GetRawFileDescriptor** to obtain **RawFileDescriptor** of the raw file. +13. Call **OH_ResourceManager_GetRawFileDescriptor** to obtain the FD of the raw file. ```c++ RawFileDescriptor descriptor; diff --git a/en/application-dev/notification/assistant-guidelines.md b/en/application-dev/notification/assistant-guidelines.md index 35d3eaeaaddd023861056fe819fbe4016c59bb01..c6de99e3fee6919ef1ca1e1a0f87a7aa0a890a74 100644 --- a/en/application-dev/notification/assistant-guidelines.md +++ b/en/application-dev/notification/assistant-guidelines.md @@ -2,9 +2,9 @@ The common event and notification module provides debugging tools to facilitate your application development. With these tools, you can view common event and notification information, publish common events, and more. These tools have been integrated with the system. You can run related commands directly in the shell. -### cem Debugging Assistant +## cem Debugging Assistant -##### publish +### publish * Functionality @@ -41,7 +41,7 @@ The common event and notification module provides debugging tools to facilitate ![cem-publish-all](figures/cem-publish-all.png) -##### dump +### dump * Functionality @@ -67,7 +67,7 @@ The common event and notification module provides debugging tools to facilitate ​ ![cem-dump-e](figures/cem-dump-e.png) -##### help +### help * Functionality @@ -83,9 +83,9 @@ The common event and notification module provides debugging tools to facilitate -### anm Debugging Assistant +## anm Debugging Assistant -##### dump +### dump * Functionality @@ -119,7 +119,7 @@ The common event and notification module provides debugging tools to facilitate Set the number of the cached recent notifications to be displayed to 10. -##### help +### help * Functionality diff --git a/en/application-dev/notification/common-event.md b/en/application-dev/notification/common-event.md index 8ea3eaa2d6b2f450f28660ca9f50ad3b99947c8b..e48bcd802e2a1d16536c29193748b14193517e4c 100644 --- a/en/application-dev/notification/common-event.md +++ b/en/application-dev/notification/common-event.md @@ -1,5 +1,5 @@ # Common Event Development -### Introduction +## Introduction OpenHarmony provides a Common Event Service (CES) for applications to subscribe to, publish, and unsubscribe from common events. Common events are classified into system common events and custom common events. @@ -25,13 +25,13 @@ You can create a subscriber object to subscribe to a common event to obtain the ### How to Develop 1. Import the **commonEvent** module. -```javascript +```js import commonEvent from '@ohos.commonEvent'; ``` 2. Create a **subscribeInfo** object. For details about the data types and parameters of the object, see [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEvent.md#commoneventsubscribeinfo). -```javascript +```js private subscriber = null // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information @@ -42,7 +42,7 @@ var subscribeInfo = { 3. Create a subscriber object and save the returned object for subsequent operations such as subscription and unsubscription. -```javascript +```js // Callback for subscriber creation. commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => { if (err.code) { @@ -57,7 +57,7 @@ commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => { 4. Create a subscription callback, which is triggered when an event is received. The data returned by the subscription callback contains information such as the common event name and data carried by the publisher. For details about the data types and parameters of the common event data, see [CommonEventData](../reference/apis/js-apis-commonEvent.md#commoneventdata). -```javascript +```js // Callback for common event subscription. if (this.subscriber != null) { commonEvent.subscribe(this.subscriber, (err, data) => { @@ -74,7 +74,7 @@ if (this.subscriber != null) { } ``` -## Public Event Publishing Development +## Common Event Publishing Development ### When to Use You can use the **publish** APIs to publish a custom common event, which can carry data for subscribers to parse and process. @@ -89,13 +89,13 @@ You can use the **publish** APIs to publish a custom common event, which can car #### Development for Publishing a Common Event 1. Import the **commonEvent** module. -```javascript +```js import commonEvent from '@ohos.commonEvent'; ``` 2. Pass in the common event name and callback, and publish the event. -```javascript +```js // Publish a common event. commonEvent.publish("event", (err) => { if (err.code) { @@ -109,13 +109,13 @@ commonEvent.publish("event", (err) => { #### Development for Publishing a Common Event with Given Attributes 1. Import the **commonEvent** module. -```javascript +```js import commonEvent from '@ohos.commonEvent' ``` 2. Define attributes of the common event to publish. For details about the data types and parameters in the data to publish, see [CommonEventPublishData](../reference/apis/js-apis-commonEvent.md#commoneventpublishdata). -```javascript +```js // Attributes of a common event. var options = { code: 1, // Result code of the common event @@ -125,7 +125,7 @@ var options = { 3. Pass in the common event name, attributes of the common event, and callback, and publish the event. -```javascript +```js // Publish a common event. commonEvent.publish("event", options, (err) => { if (err.code) { @@ -149,14 +149,14 @@ You can use the **unsubscribe** API to unsubscribe from a common event. ### How to Develop 1. Import the **commonEvent** module. -```javascript +```js import commonEvent from '@ohos.commonEvent'; ``` 2. Subscribe to a common event by following instructions in [Common Event Subscription Development](#Common-Event-Subscription-Development). 3. Invoke the **unsubscribe** API in **CommonEvent** to unsubscribe from the common event. -```javascript +```js if (this.subscriber != null) { commonEvent.unsubscribe(this.subscriber, (err) => { if (err.code) { diff --git a/en/application-dev/quick-start/figures/image-20220326064841782.png b/en/application-dev/quick-start/figures/image-20220326064841782.png index ce4450151f3dc0de82cd8f57cf6018eebbc46f58..a7811ffe339baceffbfff66f2173b2e5e29a6fc1 100644 Binary files a/en/application-dev/quick-start/figures/image-20220326064841782.png and b/en/application-dev/quick-start/figures/image-20220326064841782.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326064913834.png b/en/application-dev/quick-start/figures/image-20220326064913834.png index c7fb0ea68933a659f81b1febb2ef946c2b274e42..9bb845a90c3b80db95c736cc84d2434537cf8522 100644 Binary files a/en/application-dev/quick-start/figures/image-20220326064913834.png and b/en/application-dev/quick-start/figures/image-20220326064913834.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326064955505.png b/en/application-dev/quick-start/figures/image-20220326064955505.png index bf1180a41e86bbb39c48e7c132f0929e6c448aed..89a43655a064971b721a5aee4222d7c2d37c9523 100644 Binary files a/en/application-dev/quick-start/figures/image-20220326064955505.png and b/en/application-dev/quick-start/figures/image-20220326064955505.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326065043006.png b/en/application-dev/quick-start/figures/image-20220326065043006.png index 2cf4b8a6503e6a7a3d7095d092144927384127f7..c8b11931993c83e507dbf7150a5be740430ae42f 100644 Binary files a/en/application-dev/quick-start/figures/image-20220326065043006.png and b/en/application-dev/quick-start/figures/image-20220326065043006.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326065124911.png b/en/application-dev/quick-start/figures/image-20220326065124911.png index 872f36c3bf328dcb4ff58ac6f9106d5c4726dc56..858a8af31bc83367fc4c2f696d0f69e58b36b216 100644 Binary files a/en/application-dev/quick-start/figures/image-20220326065124911.png and b/en/application-dev/quick-start/figures/image-20220326065124911.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326065201867.png b/en/application-dev/quick-start/figures/image-20220326065201867.png index 5c3b428823d5f044a2857e641ac2465beff39114..e447e34c0a80c472cb2dfd684e1822866b4134d8 100644 Binary files a/en/application-dev/quick-start/figures/image-20220326065201867.png and b/en/application-dev/quick-start/figures/image-20220326065201867.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326072448840.png b/en/application-dev/quick-start/figures/image-20220326072448840.png index dac0f9dfe41d8f7667e21f2224563910e3aa9429..861ef6a871ce38d28a1144722ff4d0d327a8bc84 100644 Binary files a/en/application-dev/quick-start/figures/image-20220326072448840.png and b/en/application-dev/quick-start/figures/image-20220326072448840.png differ diff --git a/en/application-dev/quick-start/syscap.md b/en/application-dev/quick-start/syscap.md index bd81ff6771735d0cb78be5321269460a7ebd0bd2..e74c958c4df493bd5084ad477b95f78c7893cd48 100644 --- a/en/application-dev/quick-start/syscap.md +++ b/en/application-dev/quick-start/syscap.md @@ -4,26 +4,26 @@ ### System Capabilities and APIs -SysCap is short for System Capability. It refers to a standalone feature in the operating system, for example, Bluetooth, Wi-Fi, NFC, or camera. Each system capability corresponds to a set of bound APIs, whose availability depends on the support of the target device. Such a set of APIs can be provided in the IDE for association. +SysCap is short for System Capability. It refers to a standalone feature in the operating system, for example, Bluetooth, Wi-Fi, NFC, or camera. Each SysCap corresponds to a set of bound APIs, whose availability depends on the support of the target device. Such a set of APIs are provided in DevEco Studio for association. ![image-20220326064841782](figures/image-20220326064841782.png) -### Supported Capability Set, Associated Capability Set, and Required Capability Set +### Supported SysCap Set, Associated SysCap Set, and Required SysCap Set -The supported capability set, associated capability set, and required capability set are collections of system capabilities. -The supported capability set covers the device capabilities, and the required capability set covers the application capabilities. If the capability set required by application A is a subset of the capability set supported by device N, application A can be distributed to device N for installation and running. Otherwise, application A cannot be distributed. -The associated capability set covers the system capabilities of associated APIs that the IDE offers during application development. +The supported SysCap set, associated SysCap set, and required SysCap set are collections of SysCaps. +The supported SysCap set covers the device capabilities, and the required SysCap set covers the application capabilities. If the SysCap set required by application A is a subset of the SysCap set supported by device N, application A can be distributed to device N for installation and running. Otherwise, application A cannot be distributed. +The associated SysCap set covers the system capabilities of associated APIs that the IDE offers during application development. ![image-20220326064913834](figures/image-20220326064913834.png) -### Devices and Supported Capability Sets +### Devices and Supported SysCap Sets -Each device provides a capability set that matches its hardware capability. -The SDK classifies devices into general devices and custom devices. The general devices' supported capability set is defined by OpenHarmony, and the custom devices' is defined by device vendors. +Each device provides a SysCap set that matches its hardware capability. +The SDK classifies devices into general devices and custom devices. The general devices' supported SysCap set is defined by OpenHarmony, and the custom devices' is defined by device vendors. ![image-20220326064955505](figures/image-20220326064955505.png) @@ -31,7 +31,7 @@ The SDK classifies devices into general devices and custom devices. The general ### Mapping Between Devices and SDK Capabilities -The SDK provides a full set of APIs for the IDE. The IDE identifies the supported capability set based on the devices supported by the project, filters the APIs contained in the capability set, and provides the supported APIs for association (to autocomplete input). +The SDK provides a full set of APIs for the IDE. DevEco Studio identifies the supported SysCap set based on the devices supported by the project, filters the APIs contained in the SysCap set, and provides the supported APIs for association (to autocomplete input). ![image-20220326065043006](figures/image-20220326065043006.png) @@ -49,11 +49,11 @@ Right-click the project directory and choose **Import Product Compatibility ID** -### Configuring the Associated Capability Set and Required Capability Set +### Configuring the Associated SysCap Set and Required SysCap Set -The IDE automatically configures the associated capability set and required capability set based on the settings supported by the created project. You can modify the capability sets when necessary. -You can add APIs to the associated capability set in the IDE by adding system capabilities. However, note that these APIs may not be supported on the device. Therefore, check whether these APIs are supported before using them. -Exercise caution when modifying the required capability set. Incorrect modifications may result in the application being unable to be distributed to the target device. +DevEco Studio automatically configures the associated SysCap set and required SysCap set based on the settings supported by the created project. You can modify these SysCap sets when necessary. +You can add APIs to the associated SysCap set in DevEco Studio by adding system capabilities. However, note that these APIs may not be supported on the device. Therefore, check whether these APIs are supported before using them. +Exercise caution when modifying the required SysCap set. Incorrect modifications may result in the application being unable to be distributed to the target device. ``` /* syscap.json */ @@ -74,15 +74,15 @@ Exercise caution when modifying the required capability set. Incorrect modificat ... ] }, - development: { /* The SysCap set in addedSysCaps and the SysCap set supported by each device configured in devices form the associated capability set. */ + development: { /* The SysCap set in addedSysCaps and the SysCap set supported by each device configured in devices form the associated SysCap set. */ addedSysCaps: [ "SystemCapability.Location.Location.Lite", ... ] }, production: { /* Used to generate the RPCID. Exercise caution when adding this parameter. Under incorrect settings, applications may fail to be distributed to target devices. */ - addedSysCaps: [], // Intersection of SysCap sets supported by devices configured in devices. It is the required capability set with addedSysCaps set and removedSysCaps set. - removedSysCaps: [] // When the required capability set is a capability subset of a device, the application can be distributed to the device. + addedSysCaps: [], // Intersection of SysCap sets supported by devices configured in devices. It is the required SysCap set with addedSysCaps set and removedSysCaps set. + removedSysCaps: [] // When the required SysCap set is a capability subset of a device, the application can be distributed to the device. } } ``` @@ -91,7 +91,7 @@ Exercise caution when modifying the required capability set. Incorrect modificat ### Single-Device Application Development -By default, the associated capability set and required system capability set of the application are the same as the supported system capability set of the device. Exercise caution when modifying the required capability set. +By default, the associated SysCap set and required SysCap set of the application are the same as the supported SysCap set of the device. Exercise caution when modifying the required SysCap set. ![image-20220326065124911](figures/image-20220326065124911.png) @@ -99,7 +99,7 @@ By default, the associated capability set and required system capability set of ### Cross-Device Application Development -By default, the associated capability set of an application is the union of multiple devices' supported capability sets, while the required capability set is the intersection of the devices' supported capability sets. +By default, the associated SysCap set of an application is the union of multiple devices' supported SysCap sets, while the required SysCap set is the intersection of the devices' supported SysCap sets. ![image-20220326065201867](figures/image-20220326065201867.png) @@ -133,9 +133,9 @@ if (geolocation) { -### Checking the Differences Between Devices with the Same Capability +### Checking the Differences Between Devices with a Specific SysCap -The performance of a system capability may vary by device type. For example, a tablet is superior to a smart wearable device in terms of the camera capability. +The performance of a SysCap may vary by device type. For example, a tablet is superior to a smart wearable device in terms of the camera capability. ``` import userAuth from '@ohos.userIAM.userAuth'; @@ -162,7 +162,7 @@ The device SysCaps in product solutions vary according to the component combinat ![image-20220326072448840](figures/image-20220326072448840.png) -1. A set of OpenHarmony source code consists of optional and mandatory components. Different components have different system capabilities. In other words, different components represent different SysCaps. +1. A set of OpenHarmony source code consists of optional and mandatory components. Different components represent different SysCaps. 2. In a normalized released SDK, APIs are mapped to SysCap sets. @@ -170,10 +170,10 @@ The device SysCaps in product solutions vary according to the component combinat 4. The components configured for a product can be OpenHarmony components or proprietary components developed by a third party. Since there is mapping between components and SysCap, the SysCap set of the product can be obtained after all components are assembled. -5. The SysCap set is encoded to generate the PCID. You can import the PCID to the IDE and decode it into SysCap. During development, compatibility processing is performed to mitigate the SysCap differences of devices. +5. The SysCap set is encoded to generate the PCID. You can import the PCID to DevEco Studio and decode it into SysCaps. During development, compatibility processing is performed to mitigate the SysCap differences of devices. 6. System parameters deployed on devices contain the SysCap set. The system provides native interfaces and application interfaces for components and applications to check whether a specific SysCap is available. -7. During application development, the SysCap required by the application is encoded into the Required Product Compatibility ID (RPCID) and written into the application installation package. During application installation, the package manager decodes the RPCID to obtain the SysCap required by the application and compares it with the SysCap of the device. If the SysCap required by the application is met, the application can be installed. +7. During application development, the SysCap set required by the application is encoded into the Required Product Compatibility ID (RPCID) and written into the application installation package. During application installation, the package manager decodes the RPCID to obtain the SysCap set required by the application and compares it with the SysCap set supported by the device. If the SysCap set required by the application is met, the application can be installed on the device. 8. When an application is running on a device, the **canIUse** API can be used to query whether the device is compatible with a specific SysCap. diff --git a/en/application-dev/reference/apis/js-apis-Context.md b/en/application-dev/reference/apis/js-apis-Context.md index 1a4861251195d5cfd17c4c0b2496583b29c212e7..efc0435996bf02ef9e7c5fd046c60a1faaa17f42 100644 --- a/en/application-dev/reference/apis/js-apis-Context.md +++ b/en/application-dev/reference/apis/js-apis-Context.md @@ -1,7 +1,9 @@ # Context Module -> **NOTE**
-> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> **NOTE** +> +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the FA model. ## Modules to Import @@ -834,7 +836,7 @@ Obtains information of the current ability. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\<[AbilityInfo](#abilityInfo)> | Yes |Callback used to return the ability information.| +| callback | AsyncCallback\<[AbilityInfo](#abilityInfo)> | Yes | Callback used to return the ability information.| **Example** @@ -886,7 +888,7 @@ Obtains the context of the application. | Type | Description | | --------- |------ | -| Context |Application context.| +| Context | Application context.| **Example** @@ -928,14 +930,14 @@ Describes the HAP module information. | labelId | number | Yes | No | Module label ID. | | iconId | number | Yes | No | Module icon ID. | | backgroundImg | string | Yes | No | Module background image. | -| supportedModes | number | Yes | No | Modes supported by the module. | +| supportedModes | number | Yes | No | Running modes supported by the module. | | reqCapabilities | Array | Yes | No | Capabilities required for module running.| -| deviceTypes | Array | Yes | No | An array of supported device types.| -| abilityInfo | Array | Yes | No | Ability information. | +| deviceTypes | Array | Yes | No | Device types supported by the module.| +| abilityInfo | Array | Yes | No | Ability information. | | moduleName | string | Yes | No | Module name. | -| mainAbilityName | string | Yes | No | Name of the entrance ability. | -| installationFree | boolean | Yes | No | When installation-free is supported. | -| mainElementName | string | Yes| No| Information about the entry ability.| +| mainAbilityName | string | Yes | No | Name of the main ability. | +| installationFree | boolean | Yes | No | Whether installation-free is supported. | +| mainElementName | string | Yes| No| Information about the main ability.| ## AppVersionInfo7+ diff --git a/en/application-dev/reference/apis/js-apis-ability-context.md b/en/application-dev/reference/apis/js-apis-ability-context.md index 5472f3dff854cb8e97499401954b850ec98e1fcd..88a0908ab11d2b345493aa1e364e48b328d62bd7 100644 --- a/en/application-dev/reference/apis/js-apis-ability-context.md +++ b/en/application-dev/reference/apis/js-apis-ability-context.md @@ -1,7 +1,9 @@ # AbilityContext -> **NOTE**
-> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. Implements the ability context. This module is inherited from **Context**. @@ -55,7 +57,7 @@ Starts an ability. This API uses a callback to return the result. var want = { "deviceId": "", "bundleName": "com.extreme.test", - "abilityName": "com.extreme.test.MainAbility" + "abilityName": "MainAbility" }; this.context.startAbility(want, (error) => { console.log("error.code = " + error.code) @@ -85,7 +87,7 @@ Starts an ability. This API uses a callback to return the result. var want = { "deviceId": "", "bundleName": "com.extreme.test", - "abilityName": "com.extreme.test.MainAbility" + "abilityName": "MainAbility" }; var options = { windowMode: 0, @@ -123,7 +125,7 @@ Starts an ability. This API uses a promise to return the result. var want = { "deviceId": "", "bundleName": "com.extreme.test", - "abilityName": "com.extreme.test.MainAbility" + "abilityName": "MainAbility" }; var options = { windowMode: 0, @@ -374,7 +376,7 @@ Obtains the caller interface of the specified ability, and if the specified abil onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "com.example.myservice.MainAbility", + abilityName: "MainAbility", deviceId: "" }).then((obj) => { caller = obj; diff --git a/en/application-dev/reference/apis/js-apis-animator.md b/en/application-dev/reference/apis/js-apis-animator.md index 462e56f7d18c0df2661e1ce1944bce0d159fcffe..2a9c01095ebf3ccfac93d9d96774c103fa2f6e4f 100644 --- a/en/application-dev/reference/apis/js-apis-animator.md +++ b/en/application-dev/reference/apis/js-apis-animator.md @@ -1,248 +1,240 @@ -# Animation +# Animator + +> **NOTE**
+> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -**requestAnimationFrame**: none +``` +import animator from '@ohos.animator'; +``` + + +## createAnimator + +createAnimator(options: AnimatorOptions): AnimatorResult + +Creates an **Animator** object. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| options | [AnimatorOptions](#animatoroptions) | Yes| Animator options. For details, see **AnimatorOptions**.| + +**Return value** +| Type| Description| +| -------- | -------- | +| [AnimatorResult](#animatorresult) | Animator result.| + +**Example** + + ``` + +
+
+
+
+ ``` + + ``` + // js + export default { + data : { + divWidth: 200, + divHeight: 200, + animator: null + }, + onInit() { + var options = { + duration: 1500, + easing: 'friction', + fill: 'forwards', + iterations: 2, + begin: 200.0, + end: 400.0 + }; + this.animator = animator.createAnimator(options); + }, + Show() { + var options1 = { + duration: 2000, + easing: 'friction', + fill: 'forwards', + iterations: 1, + begin: 200.0, + end: 400.0 + }; + this.animator.update(options1); + var _this = this; + this.animator.onframe = function(value) { + _this.divWidth = value; + _this.divHeight = value; + }; + this.animator.play(); + } + } + ``` + +## AnimatorResult + +Defines the animator result. + +### update + +update(options: AnimatorOptions): void + +Updates this animator. -**cancelAnimationFrame**: none +**System capability**: SystemCapability.ArkUI.ArkUI.Full -**createAnimator**: +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| options | [AnimatorOptions](#animatoroptions) | Yes| Animator options.| +**Example** ``` -import animator from '@ohos.animator'; +animator.update(options); ``` -## Required Permissions +### play -None +play(): void -## requestAnimationFrame +Plays this animation. -requestAnimationFrame\(handler\[, \[ ...args\]\]\): number +**System capability**: SystemCapability.ArkUI.ArkUI.Full -Requests an animation frame. +**Example** +``` +animator.play(); +``` -- Parameters +### finish - | Name | Type | Mandatory | Description | - | ------- | ----------- | --------- | ------------------------------------------------------------ | - | handler | Function | Yes | Handler used to request a frame. When **requestAnimationFrame** calls the **handler**, the timestamp is passed to the first parameter to indicate the time when **requestAnimationFrame** starts to execute the callback. | - | ...args | Array\ | No | Additional parameter, which is passed to the **handler** as a parameter during function callback. | +finish(): void -- Return values +Ends this animation. - | Type | Description | - | ------ | ----------- | - | number | Request ID. | - -- Example +**System capability**: SystemCapability.ArkUI.ArkUI.Full - ``` - -
- -
- ``` - - ``` - /* xxx.css */ - .container { - flex-direction: column; - justify-content: center; - align-items: center; - width: 100%; - height: 100%; - } - .btn{ - width: 300px; - margin-top: 40px; - } - ``` - - ``` - /* xxx.js */ - export default { - data: { - requestId: 0, - startTime: 0, - }, - beginAnimation() { - cancelAnimationFrame(this.requestId); - this.requestId = requestAnimationFrame(this.runAnimation); - }, - runAnimation(timestamp) { - if (this.startTime == 0) { - this.startTime = timestamp; - } - var elapsed = timestamp - this.startTime; - if (elapsed < 500) { - console.log('callback handler timestamp: ' + timestamp); - this.requestId = requestAnimationFrame(this.runAnimation); - } - } - } - ``` +**Example** +``` +animator.finish(); +``` +### pause -## cancelAnimationFrame +pause(): void -cancelAnimationFrame\(requestId: number\): void +Pauses this animation. -Cancels the animation frame request. +**System capability**: SystemCapability.ArkUI.ArkUI.Full -- Parameters +**Example** +``` +animator.pause(); +``` - | Name | Type | Mandatory | Description | -| --------- | ------ | --------- | ------------------------ | - | requestId | number | Yes | ID of the frame request. | - -- Example +### cancel - ``` - -
- - -
- ``` - - ``` - /* xxx.css */ - .container { - flex-direction: column; - justify-content: center; - align-items: center; - width: 100%; - height: 100%; - } - .btn{ - width: 300px; - margin-top: 40px; - } - ``` - - ``` - /* xxx.js */ - export default { - data: { - requestId: 0, - startTime: 0, - }, - beginAnimation() { - cancelAnimationFrame(this.requestId); - this.requestId = requestAnimationFrame(this.runAnimation); - }, - runAnimation(timestamp) { - if (this.startTime == 0) { - this.startTime = timestamp; - } - var elapsed = timestamp - this.startTime; - if (elapsed < 500) { - console.log('callback handler timestamp: ' + timestamp); - this.requestId = requestAnimationFrame(this.runAnimation); - } - }, - stopAnimation() { - cancelAnimationFrame(this.requestId); - } - } - ``` +cancel(): void +Cancels this animation. -## createAnimator +**System capability**: SystemCapability.ArkUI.ArkUI.Full -createAnimator\(options\[...\]\): void - -Creates an animation object. - -- Parameters - - | Name | Type | Mandatory | Description | - | ------- | ------ | --------- | ------------------------------------------------------------ | - | options | Object | Yes | Attributes of the **Animator** to be created. For details, see the options table. | - -- Description of options - - | Name | Type | Mandatory | Description | - | ---------- | ------ | --------- | ------------------------------------------------------------ | - | duration | number | No | Duration for playing an animation, in milliseconds. The default value is **0**. | - | easing | string | No | Animation easing curve. The default value is **ease**. | - | delay | number | No | Animation delay duration, in milliseconds. The default value is **0**, indicating that there is no delay. | - | fill | string | No | Animation start/stop mode. The default value is **none**. | - | direction | string | No | Animation playback mode. The default value is **normal**. | - | iterations | number | No | Number of times that an animation is played. The default value is **1**. If this parameter is set to **0**, the animation is not played. If this parameter is set to **-1**, the animation is played for an unlimited number of times. | - | begin | number | No | Start point of the animation easing. If this parameter is not set, the default value **0** is used. | - | end | number | No | End point of the animation easing. If this parameter is not set, the default value **1** is used. | - -- animator interfaces - - | Name | Type | Description | - | ------- | ------- | ------------------------------------------------------------ | - | update | options | Updates the animation parameters. The input parameters are the same as those of **createAnimator**. | - | play | - | Starts an animation. | - | finish | - | Ends an animation. | - | pause | - | Pauses an animation. | - | cancel | - | Cancels an animation. | - | reverse | - | Reverses an animation. | - - -- **animator** supported events: - - | Name | Type | Description | - | ------ | ------ | ----------------------------------- | - | frame | number | The frame is requested. | - | cancel | - | The animation is forcibly canceled. | - | finish | - | The animation playback is complete. | - | repeat | - | The animation replays. | - -- Example - - ``` - -
-
-
-
- ``` - - ``` - // js - export default { - data : { - divWidth: 200, - divHeight: 200, - animator: null - }, - onInit() { - var options = { - duration: 1500, - easing: 'friction', - fill: 'forwards', - iterations: 2, - begin: 200.0, - end: 400.0 - }; - this.animator = animator.createAnimator(options); - }, - Show() { - var options1 = { - duration: 2000, - easing: 'friction', - fill: 'forwards', - iterations: 1, - begin: 200.0, - end: 400.0 - }; - this.animator.update(options1); - var _this = this; - this.animator.onframe = function(value) { - _this.divWidth = value; - _this.divHeight = value; - }; - this.animator.play(); - } - } - ``` \ No newline at end of file +**Example** +``` +animator.cancel(); +``` + +### reverse + +reverse(): void + +Plays this animation in reverse order. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** +``` +animator.reverse(); +``` + +### onframe + +onframe: (progress: number) => void + +Called when a frame is received. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| progress | number | Yes| Current progress of the animation.| + +**Example** +``` +animator.onframe(); +``` + +### onfinish + +onfinish: () => void + +Called when this animation is finished. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** +``` +animator.onfinish(); +``` + +### oncancel + +oncancel: () => void + +Called when this animation is canceled. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** +``` +animator.oncancel(); +``` + +### onrepeat + +onrepeat: () => void + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** +``` +animator.onrepeat(); +``` + +Called when this animation repeats. + +## AnimatorOptions + +Defines animator options. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| duration | number | Yes| Duration for playing the animation, in milliseconds. The default value is **0**.| +| easing | string | Yes| Animation interpolation curve. The default value is **ease**.| +| delay | number | Yes| Animation delay duration, in milliseconds. The default value is **0**, indicating that there is no delay.| +| fill | "none" \| "forwards" \| "backwards" \| "both" | Yes| State of the animated target after the animation is executed. The default value is **none**, which means that the target will retain its end state (defined by the last keyframe) after the animation is executed. | +| direction | "normal" \| "reverse" \| "alternate" \| "alternate-reverse" | Yes| Animation playback mode. The default value is **normal**.| +| iterations | number | Yes| Number of times that the animation is played. The default value is **1**. The value **0** means not to play the animation, and **-1** means to play the animation for an unlimited number of times.| +| begin | number | Yes| Start point of the animation interpolation. If this parameter is not set, the default value **0** is used.| +| end | number | Yes| End point of the animation interpolation. If this parameter is not set, the default value **1** is used.| diff --git a/en/application-dev/reference/apis/js-apis-application-Want.md b/en/application-dev/reference/apis/js-apis-application-Want.md index 19509a5e771ce744b16a8f231faf6f75bccb772b..26c0cd030bcdf36cee488cba5066b2beba38a3d3 100644 --- a/en/application-dev/reference/apis/js-apis-application-Want.md +++ b/en/application-dev/reference/apis/js-apis-application-Want.md @@ -1,14 +1,13 @@ # Want -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. **Want** is the basic communication component of the system. - ## Modules to Import - ``` import Want from '@ohos.application.Want'; ``` @@ -17,14 +16,15 @@ import Want from '@ohos.application.Want'; **System capability**: SystemCapability.Ability.AbilityBase - | Name | Readable/Writable | Type | Mandatory | Description | - | ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | - | deviceId | Read only | string | No | ID of the device running the ability. | - | bundleName | Read only | string | No | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can directly match the specified ability. | - | abilityName | Read only | string | No | Name of the ability. If both **package** and **AbilityName** are specified in this field in a **Want** object, the **Want** object can directly match the specified ability. | - | uri | Read only | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**. | - | type | Read only | string | No | MIME type, for example, **text/plain** or **image/***. | - | flags | Read only | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-featureAbility.md#flags). | - | action | Read only | string | No | Action option. | - | parameters | Read only | {[key: string]: any} | No | List of parameters in the **Want** object. | - | entities | Read only | Array\ | No | List of entities. | +| Name | Readable/Writable| Type | Mandatory| Description | +| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | +| deviceId | Read only | string | No | ID of the device running the ability. | +| bundleName | Read only | string | No | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.| +| abilityName | Read only | string | No | Name of the ability. If both **package** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.| +| uri | Read only | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| +| type | Read only | string | No | MIME type, for example, **text/plain** or **image/***. | +| flags | Read only | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-featureAbility.md#flags).| +| action | Read only | string | No | Action option. | +| parameters | Read only | {[key: string]: any} | No | List of parameters in the **Want** object. | +| entities | Read only | Array\ | No | List of entities. | +| moduleName9+ | Read only | string | No | Module to which the ability belongs. Different abilities among HAP files in an application may use the same name. If the abilities cannot be distinguished by the combination of **bundleName** and **abilityName**, you can set **moduleName** for better distinguishing.| | diff --git a/en/application-dev/reference/apis/js-apis-application-ability.md b/en/application-dev/reference/apis/js-apis-application-ability.md index 136ec10fb630431a12d0455ca5e941249265267e..bdf719b34ed6e7ba0dcc227ff5866c8ae7b87a87 100644 --- a/en/application-dev/reference/apis/js-apis-application-ability.md +++ b/en/application-dev/reference/apis/js-apis-application-ability.md @@ -1,15 +1,14 @@ # Ability -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
-> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. - +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. Manages the ability lifecycle and context. - ## Modules to Import - ``` import Ability from '@ohos.application.Ability'; ``` @@ -23,6 +22,8 @@ import Ability from '@ohos.application.Ability'; | context | [AbilityContext](js-apis-ability-context.md) | Yes| No| Context of an ability.| | launchWant | [Want](js-apis-application-Want.md) | Yes| No| Parameters for starting the ability.| | lastRequestWant | [Want](js-apis-application-Want.md) | Yes| No| Parameters used when the ability was started last time.| +| callee | [Callee](#callee) | Yes| No| Object that invokes the stub service.| + ## Ability.onCreate @@ -200,11 +201,12 @@ Called to save data during the ability migration preparation process. **Example** ```js + import AbilityConstant from "@ohos.application.AbilityConstant" class myAbility extends Ability { onContinue(wantParams) { console.log('onContinue'); wantParams["myData"] = "my1234567"; - return true; + return AbilityConstant.OnContinueResult.AGREE; } } ``` @@ -212,7 +214,7 @@ Called to save data during the ability migration preparation process. ## Ability.onNewWant -onNewWant(want: Want): void; +onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; Called when the ability startup mode is set to singleton. @@ -223,13 +225,17 @@ Called when the ability startup mode is set to singleton. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-Want.md) | Yes| Want parameters, such as the ability name and bundle name.| + | launchParams | AbilityConstant.LaunchParam | Yes| Reason for the ability startup and the last abnormal exit.| **Example** ```js class myAbility extends Ability { - onNewWant(want) { + onNewWant(want, launchParams) { console.log('onNewWant, want:' + want.abilityName); + if (launchParams.launchReason === AbilityConstant.LaunchReason.CONTINUATION) { + console.log('onNewWant, launchReason is continuation'); + } } } ``` @@ -259,6 +265,32 @@ Called when the configuration of the environment where the ability is running is } ``` +## Ability.dump + +dump(params: Array\): Array\; + +Called when the client information is dumped. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | params | Array\ | Yes| Parameters in the form of a command.| + +**Example** + + ```js + class myAbility extends Ability { + dump(params) { + console.log('dump, params:' + JSON.stringify(params)); + return ["params"] + } + } + ``` + + ## Caller @@ -291,6 +323,9 @@ Sends sequenceable data to the target ability. ```js import Ability from '@ohos.application.Ability'; class MyMessageAble{ // Custom sequenceable data structure + name:"" + str:"" + num: 1 constructor(name, str) { this.name = name; this.str = str; @@ -314,7 +349,7 @@ Sends sequenceable data to the target ability. onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "com.example.myservice.MainAbility", + abilityName: "MainAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -361,6 +396,9 @@ Sends sequenceable data to the target ability and obtains the sequenceable data ```js import Ability from '@ohos.application.Ability'; class MyMessageAble{ + name:"" + str:"" + num: 1 constructor(name, str) { this.name = name; this.str = str; @@ -384,7 +422,7 @@ Sends sequenceable data to the target ability and obtains the sequenceable data onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "com.example.myservice.MainAbility", + abilityName: "MainAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -423,7 +461,7 @@ Releases the caller interface of the target ability. onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "com.example.myservice.MainAbility", + abilityName: "MainAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -445,7 +483,7 @@ Releases the caller interface of the target ability. onRelease(callback: OnReleaseCallBack): void; -Registers a callback that is invoked when the Stub on the target ability is disconnected. +Registers a callback that is invoked when the stub on the target ability is disconnected. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore @@ -464,7 +502,7 @@ Registers a callback that is invoked when the Stub on the target ability is disc onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "com.example.myservice.MainAbility", + abilityName: "MainAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -509,6 +547,9 @@ Registers a caller notification callback, which is invoked when the target abili ```js import Ability from '@ohos.application.Ability'; class MyMessageAble{ + name:"" + str:"" + num: 1 constructor(name, str) { this.name = name; this.str = str; diff --git a/en/application-dev/reference/apis/js-apis-application-applicationContext.md b/en/application-dev/reference/apis/js-apis-application-applicationContext.md index b34cb68eac4b252d24d3644c82e98f395f45c38a..517d9fb529fce872c5972a1aada50ce9f9b54ec9 100644 --- a/en/application-dev/reference/apis/js-apis-application-applicationContext.md +++ b/en/application-dev/reference/apis/js-apis-application-applicationContext.md @@ -1,8 +1,9 @@ # ApplicationContext -> **NOTE**
-> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. - +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. Provides application-level context and APIs for registering and deregistering the ability lifecycle listener in an application. @@ -41,14 +42,6 @@ Registers a listener to monitor the ability lifecycle of the application. | ------ | ------------------------------ | | number | ID of the registered listener. The ID is incremented by 1 each time the listener is registered. When the ID exceeds 2^63-1, **-1** is returned.| -**Example** - - ```js - let applicationContext = this.context.getApplicationContext(); - console.log("stage applicationContext: " + JSON.stringify(applicationContext)); - let lifecycleid = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback); - console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleid)); - ``` ## ApplicationContext.unregisterAbilityLifecycleCallback @@ -68,9 +61,47 @@ Deregisters the listener that monitors the ability lifecycle of the application. **Example** ```js - let applicationContext = this.context.getApplicationContext(); - console.log("stage applicationContext: " + JSON.stringify(applicationContext)); - applicationContext.unregisterAbilityLifecycleCallback(lifecycleid, (error, data) => { - console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); - }); + import AbilityStage from "@ohos.application.AbilityStage"; + + var lifecycleid; + + export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage onCreate") + let AbilityLifecycleCallback = { + onAbilityCreate(ability){ + console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability)); + }, + onAbilityWindowStageCreate(ability){ + console.log("AbilityLifecycleCallback onAbilityWindowStageCreate ability:" + JSON.stringify(ability)); + }, + onAbilityWindowStageDestroy(ability){ + console.log("AbilityLifecycleCallback onAbilityWindowStageDestroy ability:" + JSON.stringify(ability)); + }, + onAbilityDestroy(ability){ + console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability)); + }, + onAbilityForeground(ability){ + console.log("AbilityLifecycleCallback onAbilityForeground ability:" + JSON.stringify(ability)); + }, + onAbilityBackground(ability){ + console.log("AbilityLifecycleCallback onAbilityBackground ability:" + JSON.stringify(ability)); + }, + onAbilityContinue(ability){ + console.log("AbilityLifecycleCallback onAbilityContinue ability:" + JSON.stringify(ability)); + } + } + // 1. Obtain applicationContext through the context attribute. + let applicationContext = this.context.getApplicationContext(); + // 2. Use applicationContext to register a listener for the ability lifecycle in the application. + lifecycleid = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback); + console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleid)); + } + onDestroy() { + let applicationContext = this.context.getApplicationContext(); + applicationContext.unregisterAbilityLifecycleCallback(lifecycleid, (error, data) => { + console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); + }); + } + } ``` diff --git a/en/application-dev/reference/apis/js-apis-camera.md b/en/application-dev/reference/apis/js-apis-camera.md index 7229bf0f4c6b812c6ec52d26c0d6f289858725e9..34b0ab6878da8b7a36848c5f7d7181022009a34b 100644 --- a/en/application-dev/reference/apis/js-apis-camera.md +++ b/en/application-dev/reference/apis/js-apis-camera.md @@ -175,6 +175,17 @@ cameraManager.getCameras().then((cameraArray) => { }) ``` +### Size + +Size parameters. This interface used to get supported size for Preview + Photo + Video. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Default Value | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | ----------------------------------- | +| height | number | Yes | Desired height of the Preview + Photo + Video. | +| width | number | Yes | Desired width of the Preview + Photo + Video.| + ### createCameraInput createCameraInput(cameraId: string, callback: AsyncCallback): void @@ -249,7 +260,7 @@ Creates a **CameraInput** instance with the specified camera position and camera **Example** ``` -cameraManager.createCameraInput(cameraPosition, cameraType, (err, cameraInput) => { +cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED, (err, cameraInput) => { if (err) { console.error('Failed to create the CameraInput instance. ${err.message}'); return; @@ -282,7 +293,7 @@ Creates a **CameraInput** instance with the specified camera position and camera **Example** ``` -cameraManager.createCameraInput(cameraPosition, cameraType).then((cameraInput) => { +cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED).then((cameraInput) => { console.log('Promise returned with the CameraInput instance.'); }) ``` @@ -305,7 +316,11 @@ Listens for camera status changes. This API uses a callback to return the camera **Example** ``` -cameraManager.on('cameraStatus', (cameraStatusInfo) => { +cameraManager.on('cameraStatus', (err, cameraStatusInfo) => { + if (err) { + console.error('Failed to get cameraStatus callback. ${err.message}'); + return; + } console.log('camera : ' + cameraStatusInfo.camera.cameraId); console.log('status: ' + cameraStatusInfo.status); }) @@ -327,14 +342,14 @@ After **[camera.getCameraManager](#cameragetcameramanager)** is called, a camera **Example** ``` -async function getCameraInfo() { +async function getCameraInfo("cameraId") { var cameraManager = await camera.getCameraManager(); var cameras = await cameraManager.getCameras(); var cameraObj = cameras[0]; var cameraId = cameraObj.cameraId; var cameraPosition = cameraObj.cameraPosition; var cameraType = cameraObj.cameraType; - var cameraId = cameraObj.connectionType; + var connectionType = cameraObj.connectionType; } ``` @@ -470,7 +485,7 @@ Checks whether a specified flash mode is supported. This API uses an asynchronou **Example** ``` -cameraInput.isFlashModeSupported(flashMode, (err, status) => { +cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, (err, status) => { if (err) { console.error('Failed to check whether the flash mode is supported. ${err.message}'); return; @@ -502,7 +517,7 @@ Checks whether a specified flash mode is supported. This API uses a promise to r **Example** ``` -cameraInput.isFlashModeSupported(flashMode).then((status) => { +cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO).then((status) => { console.log('Promise returned with flash mode support status.' + status); }) ``` @@ -530,7 +545,7 @@ Before setting the parameters, do the following checks: **Example** ``` -cameraInput.setFlashMode(flashMode, (err) => { +cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, (err) => { if (err) { console.error('Failed to set the flash mode ${err.message}'); return; @@ -567,7 +582,7 @@ Before setting the parameters, do the following checks: **Example** ``` -cameraInput.setFlashMode(flashMode).then(() => { +cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO).then(() => { console.log('Promise returned with the successful execution of setFlashMode.'); }) ``` @@ -638,7 +653,7 @@ Checks whether a specified focus mode is supported. This API uses an asynchronou **Example** ``` -cameraInput.isFocusModeSupported(afMode, (err, status) => { +cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO, (err, status) => { if (err) { console.error('Failed to check whether the focus mode is supported. ${err.message}'); return; @@ -670,7 +685,7 @@ Checks whether a specified focus mode is supported. This API uses a promise to r **Example** ``` -cameraInput.isFocusModeSupported(afMode).then((status) => { +cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO).then((status) => { console.log('Promise returned with focus mode support status.' + status); }) ``` @@ -695,7 +710,7 @@ Before setting the focus mode, use **[isFocusModeSupported](#isfocusmodesupporte **Example** ``` -cameraInput.setFocusMode(afMode, (err) => { +cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO, (err) => { if (err) { console.error('Failed to set the focus mode ${err.message}'); return; @@ -729,7 +744,7 @@ Before setting the focus mode, use **[isFocusModeSupported](#isfocusmodesupporte **Example** ``` -cameraInput.setFocusMode(afMode).then(() => { +cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO).then(() => { console.log('Promise returned with the successful execution of setFocusMode.'); }) ``` @@ -848,7 +863,7 @@ Sets a zoom ratio. This API uses an asynchronous callback to return the result. **Example** ``` -cameraInput.setZoomRatio(zoomRatio, (err) => { +cameraInput.setZoomRatio(1, (err) => { if (err) { console.error('Failed to set the zoom ratio value ${err.message}'); return; @@ -880,7 +895,7 @@ Sets a zoom ratio. This API uses a promise to return the result. **Example** ``` -cameraInput.setZoomRatio(zoomRatio).then(() => { +cameraInput.setZoomRatio(1).then(() => { console.log('Promise returned with the successful execution of setZoomRatio.'); }) ``` @@ -950,7 +965,7 @@ Releases this **CameraInput** instance. This API uses an asynchronous callback t **Example** ``` -camera.release((err) => { +cameraInput.release((err) => { if (err) { console.error('Failed to release the CameraInput instance ${err.message}'); return; @@ -1027,6 +1042,27 @@ cameraInput.on('error', (cameraInputError) => { }) ``` +## CameraInputErrorCode + +Enumerates the CameraInput error code. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Default Value| Description | +| ---------------------- | ------ | ------------ | +| ERROR_UNKNOWN | -1 | Unknown error.| + +## CameraInputError + +Camera input error object which extends **Error** interface. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Default Value| Description | +| ---------------------- | ------ | ------------ | +| code | [CameraInputErrorCode](#camerainputerrorcode) | Used to get error code in CameraInput on('error') callback| ## FlashMode @@ -1836,6 +1872,28 @@ captureSession.on('error', (captureSessionError) => { }) ``` +## CaptureSessionErrorCode + +Enumerates the CaptureSession error code. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Default Value| Description | +| ---------------------- | ------ | ------------ | +| ERROR_UNKNOWN | -1 | Unknown error.| + +## CaptureSessionError + +Capture session error object which extends **Error** interface. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Default Value| Description | +| ---------------------- | ------ | ------------ | +| code | [CaptureSessionErrorCode](#capturesessionerrorcode) | Used to get error code in CaptureSession on('error') callback.| + ## camera.createPreviewOutput createPreviewOutput(surfaceId: string, callback: AsyncCallback): void @@ -1854,7 +1912,7 @@ Creates a **PreviewOutput** instance. This API uses an asynchronous callback to **Example** ``` -camera.createPreviewOutput((surfaceId), (err, previewOutput) => { +camera.createPreviewOutput(("surfaceId"), (err, previewOutput) => { if (err) { console.error('Failed to create the PreviewOutput instance. ${err.message}'); return; @@ -1886,7 +1944,7 @@ Creates a **PreviewOutput** instance. This API uses a promise to return the inst **Example** ``` -camera.createPreviewOutput(surfaceId).then((previewOutput) => { +camera.createPreviewOutput("surfaceId").then((previewOutput) => { console.log('Promise returned with the PreviewOutput instance'); }) ``` @@ -2013,6 +2071,28 @@ previewOutput.on('error', (previewOutputError) => { }) ``` +## PreviewOutputErrorCode + +Enumerates the PreviewOutput error code. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Default Value| Description | +| ---------------------- | ------ | ------------ | +| ERROR_UNKNOWN | -1 | Unknown error.| + +## PreviewOutputError + +Preview output error object which extends **Error** interface. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Default Value| Description | +| ---------------------- | ------ | ------------ | +| code | [PreviewOutputErrorCode](#previewoutputerrorcode) | Used to get error code in PreviewOutput on('error') callback.| + ## camera.createPhotoOutput createPhotoOutput(surfaceId: string, callback: AsyncCallback): void @@ -2031,7 +2111,7 @@ Creates a **PhotoOutput** instance. This API uses an asynchronous callback to re **Example** ``` -camera.createPhotoOutput((surfaceId), (err, photoOutput) => { +camera.createPhotoOutput(("surfaceId"), (err, photoOutput) => { if (err) { console.error('Failed to create the PhotoOutput instance. ${err.message}'); return; @@ -2063,7 +2143,7 @@ Creates a **PhotoOutput** instance. This API uses a promise to return the instan **Example** ``` -camera.createPhotoOutput(surfaceId).then((photoOutput) => { +camera.createPhotoOutput("surfaceId").then((photoOutput) => { console.log('Promise returned with PhotoOutput instance'); }) ``` @@ -2260,7 +2340,7 @@ Listens for photo capture start events. This API uses a callback to return the e **Example** ``` -photoOutput.on('captureStart', (captureId) => { +photoOutput.on('captureStart', (err, captureId) => { console.log('photo capture stated, captureId : ' + captureId); }) ``` @@ -2336,6 +2416,50 @@ photoOutput.on('error', (photoOutputError) => { }) ``` +### FrameShutterInfo + +Frame shutter callback info which provides **captureId** & **timestamp** parameteres & indicates the frame shutter event. + +**Parameteres** + +| Name | Type | Mandatory| Description | +| :------- | :------------------------------- | :--- | :---------------------------------------- | +| captureId | number | Yes | Capture id.| +| timestamp | number | Yes | Timestamp for frame. + +### CaptureEndInfo + +Capture end info which provides **captureId** & **frameCount** parameteres & indicates the photo capture end event. + +**Parameteres** + +| Name | Type | Mandatory| Description | +| :------- | :------------------------------- | :--- | :---------------------------------------- | +| captureId | number | Yes | Capture id.| +| frameCount | number | Yes | Frame count. + +## PhotoOutputErrorCode + +Enumerates the PhotoOutput error code. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Default Value| Description | +| ---------------------- | ------ | ------------ | +| ERROR_UNKNOWN | -1 | Unknown error.| + +## PhotoOutputError + +Photo output error object which extends **Error** interface. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Default Value| Description | +| ---------------------- | ------ | ------------ | +| code | [PhotoOutputErrorCode](#photooutputerrorcode) | Used to get error code in PhotoOutput on('error') callback.| + ## camera.createVideoOutput createVideoOutput(surfaceId: string, callback: AsyncCallback): void @@ -2354,7 +2478,7 @@ Creates a **VideoOutput** instance. This API uses an asynchronous callback to re **Example** ``` -camera.createVideoOutput((surfaceId), (err, videoOutput) => { +camera.createVideoOutput(("surfaceId"), (err, videoOutput) => { if (err) { console.error('Failed to create the VideoOutput instance. ${err.message}'); return; @@ -2386,7 +2510,8 @@ Creates a **VideoOutput** instance. This API uses a promise to return the instan **Example** ``` -camera.createVideoOutput(surfaceId).then((videoOutput) => { +camera.createVideoOutput("surfaceId" +).then((videoOutput) => { console.log('Promise returned with the VideoOutput instance'); }) ``` @@ -2609,3 +2734,25 @@ videoOutput.on('error', (VideoOutputError) => { console.log('Video output error code: ' + VideoOutputError.code); }) ``` + +## VideoOutputErrorCode + +Enumerates the VideoOutput error code. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Default Value| Description | +| ---------------------- | ------ | ------------ | +| ERROR_UNKNOWN | -1 | Unknown error.| + +## VideoOutputError + +Photo output error object which extends **Error** interface. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Default Value| Description | +| ---------------------- | ------ | ------------ | +| code | [VideoOutputErrorCode](#videooutputerrorcode) | Used to get error code in VideoOutput on('error') callback.| \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-cardEmulation.md b/en/application-dev/reference/apis/js-apis-cardEmulation.md index 8a02d10ed21fa79dce8f21e557d4564c76321451..3f0d063a7e435b2f777f79bb6934aaf8d233e13a 100644 --- a/en/application-dev/reference/apis/js-apis-cardEmulation.md +++ b/en/application-dev/reference/apis/js-apis-cardEmulation.md @@ -1,6 +1,6 @@ # Standard NFC Card Emulation -This module is used to implement Near-Field Communication (NFC) card emulation. +Implements Near-Field Communication (NFC) card emulation. > **NOTE**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -45,7 +45,7 @@ Starts HCE. | Name | Type | Mandatory| Description | | ------- | -------- | ---- | ----------------------- | -| aidList | string[] | Yes | Aid list to be registered for card emulation.| +| aidList | string[] | Yes | Application ID (AID) list to be registered for card emulation.| ### stopHCE @@ -78,7 +78,7 @@ Subscribes to messages from the peer device after **startHCE()**. sendResponse(responseApdu: number[]): void; -Sends data to the peer device. +Sends a response to the peer device. **Required permissions**: ohos.permission.NFC_CARD_EMULATION diff --git a/en/application-dev/reference/apis/js-apis-contact.md b/en/application-dev/reference/apis/js-apis-contact.md index e9ac02205ed355fb1a0933f449ebd9b304277adc..ee5cf3137c7aa5d1ef6cb8ef1c1ef47ef8b35236 100644 --- a/en/application-dev/reference/apis/js-apis-contact.md +++ b/en/application-dev/reference/apis/js-apis-contact.md @@ -195,7 +195,7 @@ Updates a contact based on the specified contact information and attributes. Thi fullName: {fullName: 'xxx'}, phoneNumbers: [{phoneNumber: '138xxxxxxxx'}] },{ - attributes:['ATTR_EMAIL', 'ATTR_NAME'] + attributes:[contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err) => { if (err) { console.log('updateContact callback: err->${JSON.stringify(err)}'); @@ -234,7 +234,7 @@ Updates a contact based on the specified contact information and attributes. Thi fullName: {fullName: 'xxx'}, phoneNumbers: [{phoneNumber: '138xxxxxxxx'}] }, { - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }); promise.then(() => { console.log('updateContact success'); @@ -564,7 +564,9 @@ Queries contacts based on the specified key and application. This API uses an as ```js contact.queryContact('xxx', { - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, (err, data) => { if (err) { console.log(`queryContact callback: err->${JSON.stringify(err)}`); @@ -596,7 +598,7 @@ Queries contacts based on the specified key and attributes. This API uses an asy ```js contact.queryContact('xxx', { - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err, data) => { if (err) { console.log(`queryContact callback: err->${JSON.stringify(err)}`); @@ -630,8 +632,11 @@ Queries contacts based on the specified key, application, and attributes. This A ```js contact.queryContact('xxx', { holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, { - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err, data) => { if (err) { console.log(`queryContact callback: err->${JSON.stringify(err)}`); @@ -669,8 +674,11 @@ Queries contacts based on the specified key, application, and attributes. This A ```js let promise = contact.queryContact('xxx', { holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, { - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }); promise.then((data) => { console.log(`queryContact success: data->${JSON.stringify(data)}`); @@ -728,7 +736,9 @@ Queries all contacts based on the specified application. This API uses an asynch ```js contact.queryContacts({ - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, (err, data) => { if (err) { console.log(`queryContacts callback: err->${JSON.stringify(err)}`); @@ -759,7 +769,7 @@ Queries all contacts based on the specified attributes. This API uses an asynchr ```js contact.queryContacts({ - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err, data) => { if (err) { console.log(`queryContacts callback: err->${JSON.stringify(err)}`); @@ -791,9 +801,11 @@ Queries all contacts based on the specified application and attributes. This API ```js contact.queryContacts({ - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, { - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err, data) => { if (err) { console.log(`queryContacts callback: err->${JSON.stringify(err)}`); @@ -829,9 +841,11 @@ Queries all contacts based on the specified application and attributes. This API ```js let promise = contact.queryContacts({ - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, { - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }); promise.then((data) => { console.log(`queryContacts success: data->${JSON.stringify(data)}`); @@ -891,7 +905,9 @@ Queries contacts based on the specified phone number and application. This API u ```js contact.queryContactsByPhoneNumber('138xxxxxxxx', { - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, (err, data) => { if (err) { console.log(`queryContactsByPhoneNumber callback: err->${JSON.stringify(err)}`); @@ -923,7 +939,7 @@ Queries contacts based on the specified phone number and attributes. This API us ```js contact.queryContactsByPhoneNumber('138xxxxxxxx', { - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err, data) => { if (err) { console.log(`queryContactsByPhoneNumber callback: err->${JSON.stringify(err)}`); @@ -956,9 +972,11 @@ Queries contacts based on the specified phone number, application, and attribute ```js contact.queryContactsByPhoneNumber('138xxxxxxxx', { - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, { - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err, data) => { if (err) { console.log(`queryContactsByPhoneNumber callback: err->${JSON.stringify(err)}`); @@ -995,9 +1013,11 @@ Queries contacts based on the specified phone number, application, and attribute ```js let promise = contact.queryContactsByPhoneNumber('138xxxxxxxx', { - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, { - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }); promise.then((data) => { console.log(`queryContactsByPhoneNumber success: data->${JSON.stringify(data)}`); @@ -1057,7 +1077,9 @@ Queries contacts based on the specified email address and application. This API ```js contact.queryContactsByEmail('xxx@email.com', { - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, (err, data) => { if (err) { console.log(`queryContactsByEmail callback: err->${JSON.stringify(err)}`); @@ -1089,7 +1111,7 @@ Queries contacts based on the specified email address and attributes. This API u ```js contact.queryContactsByEmail('xxx@email.com', { - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err, data) => { if (err) { console.log(`queryContactsByEmail callback: err->${JSON.stringify(err)}`); @@ -1122,9 +1144,11 @@ Queries contacts based on the specified email address, application, and attribut ```js contact.queryContactsByEmail('xxx@email.com', { - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, { - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err, data) => { if (err) { console.log(`queryContactsByEmail callback: err->${JSON.stringify(err)}`); @@ -1161,9 +1185,11 @@ Queries contacts based on the specified email address, application, and attribut ```js let promise = contact.queryContactsByEmail('xxx@email.com', { - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, { - attributes: ["ATTR_EMAIL", "ATTR_NAME"] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }); promise.then((data) => { console.log(`queryContactsByEmail success: data->${JSON.stringify(data)}`); @@ -1221,7 +1247,9 @@ Queries all groups of this contact based on the specified application. This API ```js contact.queryGroups({ - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }, (err, data) => { if (err) { console.log(`queryGroups callback: err->${JSON.stringify(err)}`); @@ -1256,7 +1284,9 @@ Queries all groups of this contact based on the specified application. This API ```js let promise = contact.queryGroups({ - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }); promise.then((data) => { console.log(`queryGroups success: data->${JSON.stringify(data)}`); @@ -1371,7 +1401,9 @@ Queries the key of a contact based on the specified contact ID and application. ```js contact.queryKey(id, { - holderId:1 + holderId: 0, + bundleName: "", + displayName: "" }, (err, data) => { if (err) { console.log(`queryKey callback: err->${JSON.stringify(err)}`); @@ -1407,7 +1439,9 @@ Queries the key of a contact based on the specified contact ID and application. ```js let promise = contact.queryKey(id, { - holderId: 0 + holderId: 0, + bundleName: "", + displayName: "" }); promise.then((data) => { console.log(`queryKey success: data->${JSON.stringify(data)}`); diff --git a/en/application-dev/reference/apis/js-apis-data-ability.md b/en/application-dev/reference/apis/js-apis-data-ability.md index bd14fac4882d454ba2f299ea811b89ed1d30167d..5e13507952dec34e32f7a4e49a75669ccc16fd82 100644 --- a/en/application-dev/reference/apis/js-apis-data-ability.md +++ b/en/application-dev/reference/apis/js-apis-data-ability.md @@ -1,6 +1,7 @@ # DataAbilityPredicates > **NOTE**
+> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -17,7 +18,7 @@ import dataAbility from '@ohos.data.dataAbility'; createRdbPredicates(name: string, dataAbilityPredicates: DataAbilityPredicates): rdb.RdbPredicates -Creates an **RdbPredicates** object based on a **DataAbilityPredicates** object. +Creates an **RdbPredicates** object from a **DataAbilityPredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -69,8 +70,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "lisi") + dataAbilityPredicates.equalTo("NAME", "lisi") ``` @@ -97,8 +97,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.notEqualTo("NAME", "lisi") + dataAbilityPredicates.notEqualTo("NAME", "lisi") ``` @@ -119,8 +118,7 @@ Adds a left parenthesis to this **DataAbilityPredicates**. **Example** ```js - let predicates = new dataAbilitylity.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "lisi") + dataAbilityPredicates.equalTo("NAME", "lisi") .beginWrap() .equalTo("AGE", 18) .or() @@ -146,8 +144,7 @@ Adds a right parenthesis to this **DataAbilityPredicates**. **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "lisi") + dataAbilityPredicates.equalTo("NAME", "lisi") .beginWrap() .equalTo("AGE", 18) .or() @@ -173,8 +170,7 @@ Adds the OR condition to this **DataAbilityPredicates**. **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "Lisa") + dataAbilityPredicates.equalTo("NAME", "Lisa") .or() .equalTo("NAME", "Rose") ``` @@ -197,8 +193,7 @@ Adds the AND condition to this **DataAbilityPredicates**. **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "Lisa") + dataAbilityPredicates.equalTo("NAME", "Lisa") .and() .equalTo("SALARY", 200.5) ``` @@ -227,8 +222,7 @@ Sets a **DataAbilityPredicates** object to match a string containing the specifi **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.contains("NAME", "os") + dataAbilityPredicates.contains("NAME", "os") ``` @@ -255,8 +249,7 @@ Sets a **DataAbilityPredicates** object to match a string that starts with the s **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.beginsWith("NAME", "os") + dataAbilityPredicates.beginsWith("NAME", "os") ``` @@ -283,8 +276,7 @@ Sets a **DataAbilityPredicates** object to match a string that ends with the spe **Example** ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.endsWith("NAME", "se") + dataAbilityPredicates.endsWith("NAME", "se") ``` @@ -310,8 +302,7 @@ Sets a **DataAbilityPredicates** object to match the field whose value is null. **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.isNull("NAME") + dataAbilityPredicates.isNull("NAME") ``` @@ -337,8 +328,7 @@ Sets a **DataAbilityPredicates** object to match the field whose value is not nu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.isNotNull("NAME") + dataAbilityPredicates.isNotNull("NAME") ``` @@ -365,8 +355,7 @@ Sets a **DataAbilityPredicates** object to match a string that is similar to the **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.like("NAME", "%os%") + dataAbilityPredicates.like("NAME", "%os%") ``` @@ -393,8 +382,7 @@ Sets a **DataAbilityPredicates** object to match the specified string. **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.glob("NAME", "?h*g") + dataAbilityPredicates.glob("NAME", "?h*g") ``` @@ -422,8 +410,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.between("AGE", 10, 50) + dataAbilityPredicates.between("AGE", 10, 50) ``` @@ -451,8 +438,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.notBetween("AGE", 10, 50) + dataAbilityPredicates.notBetween("AGE", 10, 50) ``` @@ -479,8 +465,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.greaterThan("AGE", 18) + dataAbilityPredicates.greaterThan("AGE", 18) ``` @@ -507,8 +492,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.lessThan("AGE", 20) + dataAbilityPredicates.lessThan("AGE", 20) ``` @@ -535,8 +519,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.greaterThanOrEqualTo("AGE", 18) + dataAbilityPredicates.greaterThanOrEqualTo("AGE", 18) ``` @@ -563,8 +546,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.lessThanOrEqualTo("AGE", 20) + dataAbilityPredicates.lessThanOrEqualTo("AGE", 20) ``` @@ -590,8 +572,7 @@ Sets a **DataAbilityPredicates** object to match the column with values sorted i **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.orderByAsc("NAME") + dataAbilityPredicates.orderByAsc("NAME") ``` @@ -617,8 +598,7 @@ Sets a **DataAbilityPredicates** object to match the column with values sorted i **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.orderByDesc("AGE") + dataAbilityPredicates.orderByDesc("AGE") ``` @@ -639,14 +619,7 @@ Sets a **DataAbilityPredicates** object to filter out duplicate records. **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "Rose").distinct("NAME") - let promiseDistinct = rdbStore.query(predicates, ["NAME"]) - promiseDistinct.then((resultSet) => { - console.log("distinct") - }).catch((err) => { - expect(null).assertFail(); - }) + dataAbilityPredicates.equalTo("NAME", "Rose").distinct() ``` @@ -672,8 +645,7 @@ Set a **DataAbilityPredicates** object to specify the maximum number of records. **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "Rose").limitAs(3) + dataAbilityPredicates.equalTo("NAME", "Rose").limitAs(3) ``` @@ -699,8 +671,7 @@ Sets a **DataAbilityPredicates** object to specify the start position of the ret **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "Rose").offsetAs(3) + dataAbilityPredicates.equalTo("NAME", "Rose").offsetAs(3) ``` @@ -726,8 +697,7 @@ Sets a **DataAbilityPredicates** object to group rows that have the same value i **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.groupBy(["AGE", "NAME"]) + dataAbilityPredicates.groupBy(["AGE", "NAME"]) ``` ### indexedBy @@ -751,8 +721,7 @@ Sets a **DataAbilityPredicates** object to specify the index column. **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.indexedBy("SALARY_INDEX") + dataAbilityPredicates.indexedBy("SALARY_INDEX") ``` @@ -780,8 +749,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array< **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.in("AGE", [18, 20]) + dataAbilityPredicates.in("AGE", [18, 20]) ``` @@ -809,8 +777,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array< **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.notIn("NAME", ["Lisa", "Rose"]) + dataAbilityPredicates.notIn("NAME", ["Lisa", "Rose"]) ``` ## ValueType diff --git a/en/application-dev/reference/apis/js-apis-data-preferences.md b/en/application-dev/reference/apis/js-apis-data-preferences.md index 1010a20849fb9da41e445bc5212e88427b3f28c5..73d27f9f20009d0674b4cf07e017139988d09fbe 100644 --- a/en/application-dev/reference/apis/js-apis-data-preferences.md +++ b/en/application-dev/reference/apis/js-apis-data-preferences.md @@ -1,6 +1,6 @@ # Preferences -Preferences provide capabilities for processing data in the form of key-value (KV) pairs and supports lightweight data persistence, modification, and query. In KV pairs, keys are of the string type, and values can be of the number, string, or Boolean type. +Preferences provide capabilities for processing data in the form of key-value (KV) pairs and support lightweight data persistence, modification, and query. In KV pairs, keys are of the string type, and values can be of the number, string, or Boolean type. > **NOTE**
@@ -19,8 +19,8 @@ import data_preferences from '@ohos.data.preferences'; | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| MAX_KEY_LENGTH | string | Yes| No| Maximum length of a key. It is 80 bytes.| -| MAX_VALUE_LENGTH | string | Yes| No| Maximum length of a value. It is 8192 bytes.| +| MAX_KEY_LENGTH | string | Yes| No| Maximum length of a key. It must be less than 80 bytes.| +| MAX_VALUE_LENGTH | string | Yes| No| Maximum length of a value. It must be less than 8192 bytes.| ## data_preferences.getPreferences @@ -33,11 +33,11 @@ Reads a **Preferences** persistence file and loads data to the **Preferences** i **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| - | name | string | Yes| Name of the **Preferences** instance persistence file.| - | callback | AsyncCallback<[Preferences](#preferences)> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| +| name | string | Yes| Name of the **Preferences** instance persistence file.| +| callback | AsyncCallback<[Preferences](#preferences)> | Yes| Callback used to return the result.| **Example** ```ts @@ -60,15 +60,15 @@ Reads a **Preferences** persistence file and loads data to the **Preferences** i **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| - | name | string | Yes| Name of the **Preferences** instance persistence file.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| +| name | string | Yes| Name of the **Preferences** instance persistence file.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[Preferences](#preferences)> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<[Preferences](#preferences)> | Promise used to return the result.| **Example** ```ts @@ -76,7 +76,7 @@ let promise = data_preferences.getPreferences(this.context, 'mystore') promise.then((preferences) => { console.info("Got preferences successfully.") }).catch((err) => { - console.info("Failed to get the preferences") + console.info("Failed to get the preferences") }) ``` @@ -91,11 +91,11 @@ Once a **Preferences** persistence file is deleted, the **Preferences** instance **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| - | name | string | Yes| Name of the **Preferences** instance persistence file.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| +| name | string | Yes| Name of the **Preferences** instance persistence file.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```ts @@ -119,15 +119,15 @@ Once a **Preferences** persistence file is deleted, the **Preferences** instance **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| - | name | string | Yes| Name of the **Preferences** instance persistence file.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| +| name | string | Yes| Name of the **Preferences** instance persistence file.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** ```ts @@ -151,11 +151,11 @@ When a **Preferences** singleton instance is removed, this instance cannot be us **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| - | name | string | Yes| Name of the **Preferences** instance persistence file.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| +| name | string | Yes| Name of the **Preferences** instance persistence file.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```ts @@ -179,16 +179,16 @@ When a **Preferences** singleton instance is removed, this instance cannot be us **System capability**: SystemCapability.DistributedDataManager.Preferences.Core -Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| - | name | string | Yes| Name of the **Preferences** instance persistence file.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.| +| name | string | Yes| Name of the **Preferences** instance persistence file.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** ```ts @@ -215,15 +215,15 @@ Obtains the value of a key. If the value is null or a non-default value, the def **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data to obtain. It cannot be empty.| - | defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, string, or Boolean value.| - | callback | AsyncCallback<ValueType> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| key | string | Yes| Key of the data to obtain. It cannot be empty.| +| defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, string, or Boolean value.| +| callback | AsyncCallback<ValueType> | Yes| Callback used to return the result.| **Example** ```ts - preferences.get('startup', 'default', function(err, value) { +preferences.get('startup', 'default', function(err, value) { if (err) { console.info("Failed to get the value of startup, err: " + err) return @@ -242,15 +242,15 @@ Obtains the value of a key. If the value is null or a non-default value, the def **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data to obtain. It cannot be empty.| - | defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, string, or Boolean value.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| key | string | Yes| Key of the data to obtain. It cannot be empty.| +| defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, string, or Boolean value.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<ValueType> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<ValueType> | Promise used to return the result.| **Example** ```ts @@ -262,6 +262,57 @@ promise.then((value) => { }) ``` +### getAll + +getAll(callback: AsyncCallback<Object>): void; + +Obtains the **Object** instance that contains all KV pairs. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<Object> | Yes| Callback used to return the **Object** instance obtained.| + +**Example** +```ts +preferences.get.getAll(function (err, value) { + if (err) { + console.info("getAll failed, err: " + err) + return + } + let keys = Object.keys(value) + console.info('getAll keys = ' + keys) + console.info("getAll object = " + JSON.stringify(value)) +}); +``` + + +### getAll + +getAll(): Promise<Object> + +Obtains the **Object** instance that contains all KV pairs. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<Object> | Promise used to return the **Object** instance obtained.| + +**Example** +```ts +let promise = preferences.getAll() +promise.then((value) => { + let keys = Object.keys(value) + console.info('getAll keys = ' + keys) + console.info("getAll object = " + JSON.stringify(value)) +}).catch((err) => { + console.info("getAll failed, err: " + err) +}) +``` ### put @@ -272,11 +323,11 @@ Puts a new value to this **Preferences** instance and its persistence file. This **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| - | value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, string, or Boolean value.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| key | string | Yes| Key of the data. It cannot be empty.| +| value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, string, or Boolean value.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```ts @@ -299,15 +350,15 @@ Puts a new value to this **Preferences** instance and its persistence file. This **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| - | value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, string, or Boolean value.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| key | string | Yes| Key of the data. It cannot be empty.| +| value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, string, or Boolean value.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** ```ts @@ -322,22 +373,17 @@ promise.then(() => { ### has -has(key: string, callback: AsyncCallback<boolean>): boolean +has(key: string, callback: AsyncCallback<boolean>): void Checks whether this **Preferences** instance contains data with a given key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data to check. It cannot be empty.| - | callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| - -**Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the **Preferences** instance contains data with the specified key; returns **false** otherwise.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| key | string | Yes| Key of the data to check. It cannot be empty.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. It returns **true** if the **Preferences** instance contains data with the given key and returns **false** otherwise.| **Example** ```ts @@ -364,14 +410,14 @@ Checks whether this **Preferences** instance contains data with a given key. Thi **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data to check. It cannot be empty.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| key | string | Yes| Key of the data to check. It cannot be empty.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result. It returns **true** if the **Preferences** instance contains data with the given key and returns **false** otherwise.| **Example** ```ts @@ -383,7 +429,7 @@ promise.then((isExist) => { console.info("The key of startup is not contained.") } }).catch((err) => { - console.info("Check the key of startup failed, err: " + err) + console.info("Failed to check the key of startup, err: " + err) }) ``` @@ -397,10 +443,10 @@ Deletes a KV pair of the specified key from this **Preferences** instance. This **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the KV pair to delete. It cannot be empty.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| key | string | Yes| Key of the KV pair to delete. It cannot be empty.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```ts @@ -423,14 +469,14 @@ Deletes a KV pair of the specified key from this **Preferences** instance. This **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the KV pair to delete. It cannot be empty.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| key | string | Yes| Key of the KV pair to delete. It cannot be empty.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** ```ts @@ -452,9 +498,9 @@ Saves the modification to this **Preferences** instance and synchronizes the mod **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```ts @@ -477,9 +523,9 @@ Saves the modification to this **Preferences** instance and synchronizes the mod **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** ```ts @@ -500,10 +546,10 @@ Clears data of this **Preferences** instance. This API uses an asynchronous call **System capability**: SystemCapability.DistributedDataManager.Preferences.Core -Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```ts @@ -526,9 +572,9 @@ Clears data of this **Preferences** instance. This API uses a promise to return **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** ```ts @@ -550,10 +596,10 @@ Subscribes to data changes. When the value of the subscribed key changes, a call **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Description| - | -------- | -------- | -------- | - | type | string | Event type. The value **change** indicates data change events.| - | callback | Callback<{ key : string }> | Callback used to return data changes.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value **change** indicates data change events.| +| callback | Callback<{ key : string }> | Yes| Callback used to return data changes.| **Example** ```ts @@ -584,17 +630,17 @@ preferences.put('startup', 'auto', function (err) { ### off('change') -off(type: 'change', callback: Callback<{ key : string }>): void +off(type: 'change', callback?: Callback<{ key : string }>): void Unsubscribes from data changes. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Description| - | -------- | -------- | -------- | - | type | string | Event type. The value **change** indicates data change events.| - | callback | Callback<{ key : string }> | Callback used to return data changes.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value **change** indicates data change events.| +| callback | Callback<{ key : string }> | No| Callback used to return data changes. If this parameter is left empty, all callbacks for data changes will be canceled.| **Example** ```ts diff --git a/en/application-dev/reference/apis/js-apis-data-rdb.md b/en/application-dev/reference/apis/js-apis-data-rdb.md index f1211dc922a699081aeab7a5b145771923d8f7fe..86b5c39b48db3bbdd15de93bd3411e915c351135 100644 --- a/en/application-dev/reference/apis/js-apis-data-rdb.md +++ b/en/application-dev/reference/apis/js-apis-data-rdb.md @@ -75,7 +75,7 @@ promise.then(async (rdbStore) => { getRdbStore(context: Context, config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void -Obtains a relational database (RDB) store. This API uses an asynchronous callback to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations. +Obtains a RDB store. This API uses an asynchronous callback to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -139,7 +139,7 @@ promise.then(async (rdbStore) => { deleteRdbStore(name: string, callback: AsyncCallback<void>): void -Deletes an RDB store. This API uses a callback to return the result. +Deletes an RDB store. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -636,7 +636,7 @@ Sets the **RdbPredicates** to match the specified string. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the database table.| -| value | string | Yes| Value to match the **RdbPredicates**.

Wildcards are supported. ***** indicates zero, one, or multiple digits or characters. **?** indicates a single digit or character.| +| value | string | Yes| Value to match the **RdbPredicates**.

Wildcards are supported. * indicates zero, one, or multiple digits or characters. **?** indicates a single digit or character.| **Return value** | Type| Description| @@ -889,10 +889,10 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose").distinct("NAME") let promise = rdbStore.query(predicates, ["NAME"]) promise.then((resultSet) => { - console.log("resultSet column names:" + resultSet.columnNames) - console.log("resultSet column count:" + resultSet.columnCount) + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) }).catch((err) => { - console.log("query err.") + console.log("Query err.") }) ``` @@ -1064,16 +1064,16 @@ Provides methods to manage an RDB store. ### insert -insert(name: string, values: ValuesBucket, callback: AsyncCallback<number>):void +insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void -Inserts a row of data into a table. This API uses a callback to return the result. +Inserts a row of data into a table. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the target table.| +| table | string | Yes| Name of the target table.| | values | [ValuesBucket](#valuesbucket) | Yes| Row of data to insert.| | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| @@ -1097,7 +1097,7 @@ rdbStore.insert("EMPLOYEE", valueBucket, function (err, ret) { ### insert -insert(name: string, values: ValuesBucket):Promise<number> +insert(table: string, values: ValuesBucket):Promise<number> Inserts a row of data into a table. This API uses a promise to return the result. @@ -1106,7 +1106,7 @@ Inserts a row of data into a table. This API uses a promise to return the result **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the target table.| +| table | string | Yes| Name of the target table.| | values | [ValuesBucket](#valuesbucket) | Yes| Row of data to insert.| **Return value** @@ -1133,17 +1133,17 @@ promise.then(async (ret) => { ### update -update(values: ValuesBucket, rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void +update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void -Updates data in the database based on the specified RdbPredicates object. This API uses a callback to return the result. +Updates data in the database based on the specified RdbPredicates object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| values | [ValuesBucket](#valuesbucket) | Yes| Data to update. The value specifies the row of data to be updated in the database. The key-value pair is associated with the column name in the target table.| -| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Row of data to insert.| +| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to be updated in the database. The key-value pair is associated with the column name in the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| Update conditions specified by the **RdbPredicates** object.| | callback | AsyncCallback<number> | Yes| Callback used to return the number of rows updated.| **Example** @@ -1168,7 +1168,7 @@ rdbStore.update(valueBucket, predicates, function (err, ret) { ### update -update(values: ValuesBucket, rdbPredicates: RdbPredicates):Promise<number> +update(values: ValuesBucket, predicates: RdbPredicates):Promise<number> Updates data in the database based on the specified RdbPredicates object. This API uses a promise to return the result. @@ -1177,8 +1177,8 @@ Updates data in the database based on the specified RdbPredicates object. This A **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| values | [ValuesBucket](#valuesbucket) | Yes| Data to update. The value specifies the row of data to be updated in the database. The key-value pair is associated with the column name in the target table.| -| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Row of data to insert.| +| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to be updated in the database. The key-value pair is associated with the column name in the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| Update conditions specified by the **RdbPredicates** object.| **Return value** | Type| Description| @@ -1203,20 +1203,92 @@ promise.then(async (ret) => { }) ``` +### update9+ +update(table: string, values: ValuesBucket, predicates: DataSharePredicates, callback: AsyncCallback<number>):void + +Updates data in the database based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| table | string | Yes| Name of the target table.| +| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to be updated in the database. The key-value pair is associated with the column name in the target table.| +| predicates | DataSharePredicates | Yes| Update conditions specified by the **DataSharePredicates** object.| +| callback | AsyncCallback<number> | Yes| Callback used to return the number of rows updated.| + +**Example** +```js +import dataShare from '@ohos.data.dataShare' +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new dataShare.DataSharePredicates() +predicates.equalTo("NAME", "Lisa") +rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, ret) { + if (err) { + console.info("Failed to update data, err: " + err) + return + } + console.log("Updated row count: " + ret) +}) +``` +### update9+ + +update(table: string, values: ValuesBucket, predicates: DataSharePredicates):Promise<number> + +Updates data in the database based on the specified **DataSharePredicates** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| table | string | Yes| Name of the target table.| +| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to be updated in the database. The key-value pair is associated with the column name in the target table.| +| predicates | DataSharePredicates | Yes| Update conditions specified by the **DataSharePredicates** object.| + +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<number> | Promise used to return the number of rows updated.| + +**Example** +```js +import dataShare from '@ohos.data.dataShare' +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new dataShare.DataSharePredicates() +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.update("EMPLOYEE", valueBucket, predicates) +promise.then(async (ret) => { + console.log("Updated row count: " + ret) +}).catch((err) => { + console.info("Failed to update data, err: " + err) +}) +``` ### delete -delete(rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void +delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void -Deletes data from the database based on the specified RdbPredicates object. This API uses a callback to return the result. +Deletes data from the database based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified for deleting data.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified by the **RdbPredicates** object for deleting data.| | callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| **Example** @@ -1235,16 +1307,16 @@ rdbStore.delete(predicates, function (err, rows) { ### delete -delete(rdbPredicates: RdbPredicates):Promise<number> +delete(predicates: RdbPredicates):Promise<number> -Deletes data from the database based on the specified RdbPredicates object. This API uses a promise to return the result. +Deletes data from the database based on the specified **RdbPredicates** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified for deleting data.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified by the **RdbPredicates** object for deleting data.| **Return value** | Type| Description| @@ -1263,19 +1335,79 @@ promise.then((rows) => { }) ``` +### delete9+ + +delete(table: string, predicates: DataSharePredicates, callback: AsyncCallback<number>):void + + +Deletes data from the database based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| table | string | Yes| Name of the target table.| +| predicates | DataSharePredicates | Yes| Conditions specified by the **DataSharePredicates** object for deleting data.| +| callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| + +**Example** +```js +import dataShare from '@ohos.data.dataShare' +let predicates = new dataShare.DataSharePredicates() +predicates.equalTo("NAME", "Lisa") +rdbStore.delete("EMPLOYEE", predicates, function (err, rows) { + if (err) { + console.info("Failed to delete data, err: " + err) + return + } + console.log("Delete rows: " + rows) +}) +``` +### delete9+ + +delete(table: string, predicates: DataSharePredicates):Promise<number> + +Deletes data from the database based on the specified **DataSharePredicates** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| table | string | Yes| Name of the target table.| +| predicates | DataSharePredicates | Yes| Conditions specified by the **DataSharePredicates** object for deleting data.| + +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<number> | Promise used to return the number of rows updated.| + +**Example** +```js +import dataShare from '@ohos.data.dataShare' +let predicates = new dataShare.DataSharePredicates() +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.delete("EMPLOYEE", predicates) +promise.then((rows) => { + console.log("Delete rows: " + rows) +}).catch((err) => { + console.info("Failed to delete data, err: " + err) +}) +``` ### query -query(rdbPredicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void +query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void -Queries data in the database based on specified conditions. This API uses a callback to return the result. +Queries data in the database based on specified conditions. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| | columns | Array<string> | Yes| Columns to query. If this parameter is not specified, the query applies to all columns.| | callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| @@ -1288,15 +1420,15 @@ rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (e console.info("Query failed, err: " + err) return } - console.log("resultSet column names:" + resultSet.columnNames) - console.log("resultSet column count:" + resultSet.columnCount) + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) }) ``` ### query -query(rdbPredicates: RdbPredicates, columns?: Array<string>):Promise<ResultSet> +query(predicates: RdbPredicates, columns?: Array<string>):Promise<ResultSet> Queries data in the database based on specified conditions. This API uses a promise to return the result. @@ -1305,7 +1437,7 @@ Queries data in the database based on specified conditions. This API uses a prom **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| | columns | Array<string> | No| Columns to query. If this parameter is not specified, the query applies to all columns.| **Return value** @@ -1319,19 +1451,81 @@ Queries data in the database based on specified conditions. This API uses a prom predicates.equalTo("NAME", "Rose") let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) promise.then((resultSet) => { - console.log("resultSet column names:" + resultSet.columnNames) - console.log("resultSet column count:" + resultSet.columnCount) + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) }).catch((err) => { console.info("Query failed, err: " + err) }) ``` +### query9+ + +query(predicates: DataSharePredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void + +Queries data in the database based on specified conditions. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| predicates | DataSharePredicates | Yes| Query conditions specified by the **DataSharePredicates** object.| +| columns | Array<string> | Yes| Columns to query. If this parameter is not specified, the query applies to all columns.| +| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** +```js +import dataShare from '@ohos.data.dataShare' +let predicates = new dataShare.DataSharePredicates() +predicates.equalTo("NAME", "Rose") +rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { + if (err) { + console.info("Query failed, err: " + err) + return + } + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) +}) +``` + +### query9+ + +query(predicates: DataSharePredicates, columns?: Array<string>):Promise<ResultSet> + +Queries data in the database based on specified conditions. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| predicates | DataSharePredicates | Yes| Query conditions specified by the **DataSharePredicates** object.| +| columns | Array<string> | No| Columns to query. If this parameter is not specified, the query applies to all columns.| + +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<[ResultSet](js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** +```js +import dataShare from '@ohos.data.dataShare' +let predicates = new dataShare.DataSharePredicates() +predicates.equalTo("NAME", "Rose") +let promise = rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +promise.then((resultSet) => { + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) +}).catch((err) => { + console.info("Query failed, err: " + err) +}) +``` ### querySql8+ querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void -Queries data in the RDB store using the specified SQL statement. This API uses a callback to return the result. +Queries data in the RDB store using the specified SQL statement. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1349,8 +1543,8 @@ rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", console.info("Query failed, err: " + err) return } - console.log("resultSet column names:" + resultSet.columnNames) - console.log("resultSet column count:" + resultSet.columnCount) + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) }) ``` @@ -1378,8 +1572,8 @@ Queries data in the RDB store using the specified SQL statement. This API uses a ```js let promise = rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo']) promise.then((resultSet) => { - console.log("resultSet column names:" + resultSet.columnNames) - console.log("resultSet column count:" + resultSet.columnCount) + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) }).catch((err) => { console.info("Query failed, err: " + err) }) @@ -1390,7 +1584,7 @@ promise.then((resultSet) => { executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void -Runs the SQL statement that contains the specified parameters but does not return a value. This API uses a callback to return the execution result. +Runs the SQL statement that contains the specified parameters but does not return a value. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1406,10 +1600,10 @@ Runs the SQL statement that contains the specified parameters but does not retur const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { if (err) { - console.info("executeSql failed, err: " + err) + console.info("ExecuteSql failed, err: " + err) return } - console.info('create table done.') + console.info('Create table done.') }) ``` @@ -1438,7 +1632,7 @@ Runs the SQL statement that contains the specified parameters but does not retur const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" let promise = rdbStore.executeSql(SQL_CREATE_TABLE) promise.then(() => { - console.info('create table done.') + console.info('Create table done.') }).catch((err) => { console.info("ExecuteSql failed, err: " + err) }) @@ -1533,12 +1727,119 @@ try { } ``` +### backup9+ + +backup(destName:string, callback: AsyncCallback<void>):void + +Backs up the database with the specified name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| destName | string | Yes| Name of the database backup file.| +| callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| + +**Example** +```js +rdbStore.backup("dbBackup.db", function(err) { + if (err) { + console.info('Backup failed, err: ' + err) + return + } + console.info('Backup success.') +}) +``` + +### backup9+ + +backup(destName:string): Promise<void> + +Backs up the database with the specified name. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| destName | string | Yes| Name of the database backup file.| + +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Example** +```js +let promiseBackup = rdbStore.backup("dbBackup.db") +promiseBackup.then(()=>{ + console.info('Backup success.') +}).catch((err)=>{ + console.info('Backup failed, err: ' + err) +}) +``` + +### restore9+ + +restore(srcName:string, callback: AsyncCallback<void>):void + +Restores a database from a specified database backup file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| srcName | string | Yes| Name of the database backup file.| +| callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| + +**Example** +```js +rdbStore.restore("dbBackup.db", function(err) { + if (err) { + console.info('Restore failed, err: ' + err) + return + } + console.info('Restore success.') +}) +``` + +### restore9+ + +restore(srcName:string): Promise<void> + +Restores a database from a specified database backup file. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| srcName | string | Yes| Name of the database backup file.| + +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Example** +```js +let promiseRestore = rdbStore.restore("dbBackup.db") +promiseRestore.then(()=>{ + console.info('Restore success.') +}).catch((err)=>{ + console.info('Restore failed, err: ' + err) +}) +``` ### setDistributedTables8+ setDistributedTables(tables: Array<string>, callback: AsyncCallback<void>): void -Sets a list of distributed tables. This API uses a callback to return the result. +Sets a list of distributed tables. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1552,10 +1853,10 @@ Sets a list of distributed tables. This API uses a callback to return the result ```js rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { if (err) { - console.info('setDistributedTables failed, err: ' + err) + console.info('Failed to set distributed tables, err: ' + err) return } - console.info('setDistributedTables successful.') + console.info('Set distributed tables successfully.') }) ``` @@ -1566,6 +1867,8 @@ rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { Sets a list of distributed tables. This API uses a promise to return the result. +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** @@ -1582,9 +1885,9 @@ Sets a list of distributed tables. This API uses a promise to return the result. ```js let promise = rdbStore.setDistributedTables(["EMPLOYEE"]) promise.then(() => { - console.info("setDistributedTables successful.") + console.info("Set distributed tables successfully.") }).catch((err) => { - console.info("setDistributedTables failed, err: " + err) + console.info("Failed to set distributed tables, err: " + err) }) ``` @@ -1592,7 +1895,9 @@ promise.then(() => { obtainDistributedTableName(device: string, table: string, callback: AsyncCallback<string>): void -Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the database of a remote device is queried. This API uses a callback to return the result. +Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the database of a remote device is queried. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1607,10 +1912,10 @@ Obtains the distributed table name for a remote device based on the local table ```js rdbStore.obtainDistributedTableName(deviceId, "EMPLOYEE", function (err, tableName) { if (err) { - console.info('obtainDistributedTableName failed, err: ' + err) + console.info('Failed to obtain distributed table name, err: ' + err) return } - console.info('obtainDistributedTableName successful, tableName=.' + tableName) + console.info('Obtained distributed table name successfully, tableName=.' + tableName) }) ``` @@ -1621,6 +1926,8 @@ rdbStore.obtainDistributedTableName(deviceId, "EMPLOYEE", function (err, tableNa Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the database of a remote device is queried. This API uses a promise to return the result. +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** @@ -1638,9 +1945,9 @@ Obtains the distributed table name for a remote device based on the local table ```js let promise = rdbStore.obtainDistributedTableName(deviceId, "EMPLOYEE") promise.then((tableName) => { - console.info('obtainDistributedTableName successful, tableName=' + tableName) + console.info('Obtained distributed table name successfully, tableName= ' + tableName) }).catch((err) => { - console.info('obtainDistributedTableName failed, err: ' + err) + console.info('Failed to obtain distributed table name, err: ' + err) }) ``` @@ -1648,7 +1955,9 @@ promise.then((tableName) => { sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback<Array<[string, number]>>): void -Synchronizes data between devices. This API uses a callback to return the result. +Synchronizes data between devices. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1665,10 +1974,10 @@ let predicates = new rdb.RdbPredicates('EMPLOYEE') predicates.inDevices(['12345678abcde']) rdbStore.sync(rdb.SyncMode.SYNC_MODE_PUSH, predicates, function (err, result) { if (err) { - console.log('sync failed, err: ' + err) + console.log('Sync failed, err: ' + err) return } - console.log('sync done.') + console.log('Sync done.') for (let i = 0; i < result.length; i++) { console.log('device=' + result[i][0] + ' status=' + result[i][1]) } @@ -1682,6 +1991,8 @@ rdbStore.sync(rdb.SyncMode.SYNC_MODE_PUSH, predicates, function (err, result) { Synchronizes data between devices. This API uses a promise to return the result. +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** @@ -1702,12 +2013,12 @@ let predicates = new data_rdb.RdbPredicates('EMPLOYEE') predicates.inDevices(['12345678abcde']) let promise = rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates) promise.then((result) =>{ - console.log('sync done.') + console.log('Sync done.') for (let i = 0; i < result.length; i++) { console.log('device=' + result[i][0] + ' status=' + result[i][1]) } }).catch((err) => { - console.log('sync failed') + console.log('Sync failed') }) ``` @@ -1717,6 +2028,8 @@ on(event: 'dataChange', type: SubscribeType, observer: Callback<Array<stri Registers an observer for this RDB store. When the data in the RDB store changes, a callback is invoked to return the data changes. +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** @@ -1747,6 +2060,8 @@ off(event:'dataChange', type: SubscribeType, observer: Callback<Array<stri Deletes the specified observer of the RDB store. This API uses a callback to return the result. +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** @@ -1821,6 +2136,8 @@ Defines the database synchronization mode. Defines the subscription type. +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core | Name | Default Value| Description| diff --git a/en/application-dev/reference/apis/js-apis-data-storage.md b/en/application-dev/reference/apis/js-apis-data-storage.md index 63ae9d95bc7da1a827030de4e644d44d68c7235c..6cdfcf94fdf36dd3f9d4adb4e44420394120fd10 100644 --- a/en/application-dev/reference/apis/js-apis-data-storage.md +++ b/en/application-dev/reference/apis/js-apis-data-storage.md @@ -22,15 +22,15 @@ import dataStorage from '@ohos.data.storage'; | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| MAX_KEY_LENGTH | string | Yes| No| Maximum length of a key. It is 80 bytes.| -| MAX_VALUE_LENGTH | string | Yes| No| Maximum length of a value. It is 8192 bytes.| +| MAX_KEY_LENGTH | string | Yes| No| Maximum length of a key. It must be less than 80 bytes.| +| MAX_VALUE_LENGTH | string | Yes| No| Maximum length of a value. It must be less than 8192 bytes.| ## dataStorage.getStorageSync getStorageSync(path: string): Storage -Reads the specified file and load its data to the **Storage** instance for data operations. +Reads the specified file and loads its data to the **Storage** instance for data operations. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core diff --git a/en/application-dev/reference/apis/js-apis-device-info.md b/en/application-dev/reference/apis/js-apis-device-info.md index 0f5dd2a794e92690820f12d6ab8e82e9f6b3b340..c23ee9f6eaccd02c06f9723a6544c61b2d821acb 100644 --- a/en/application-dev/reference/apis/js-apis-device-info.md +++ b/en/application-dev/reference/apis/js-apis-device-info.md @@ -1,6 +1,6 @@ # Device Information -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE**
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -24,7 +24,7 @@ import deviceInfo from '@ohos.deviceInfo' | softwareModel | string | Yes| No| Software model.| | hardwareModel | string | Yes| No| Hardware model.| | hardwareProfile | string | Yes| No| Hardware profile.| -| serial | string | Yes| No| Device serial number.| +| serial | string | Yes| No| Device serial number.
**Required permissions**: ohos.permission.sec.ACCESS_UDID (a system permission)| | bootloaderVersion | string | Yes| No| Bootloader version.| | abiList | string | Yes| No| Application binary interface (Abi) list.| | securityPatchTag | string | Yes| No| Security patch tag.| @@ -44,4 +44,4 @@ import deviceInfo from '@ohos.deviceInfo' | buildHost | string | Yes| No| Build host.| | buildTime | string | Yes| No| Build time.| | buildRootHash | string | Yes| No| Build root hash.| -| udid7+ | string | Yes| No| Device UDID.| +| udid7+ | string | Yes| No| Device UDID.
**Required permissions**: ohos.permission.sec.ACCESS_UDID (a system permission)| diff --git a/en/application-dev/reference/apis/js-apis-enterprise-device-manager.md b/en/application-dev/reference/apis/js-apis-enterprise-device-manager.md index 869472d43c046a68cd3d50cfe262b424b660dd0d..25c0dbf964cc82eaddc85ff1114c440afbd00d2d 100644 --- a/en/application-dev/reference/apis/js-apis-enterprise-device-manager.md +++ b/en/application-dev/reference/apis/js-apis-enterprise-device-manager.md @@ -11,11 +11,11 @@ import enterpriseDeviceManager from '@ohos.enterpriseDeviceManager'; ``` -## enterpriseDeviceManager.activateAdmin +## enterpriseDeviceManager.enableAdmin -activateAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, callback: AsyncCallback\): void +enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId?: number, callback: AsyncCallback\): void -Activates a device administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. +Enables a device administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. **Required permissions** @@ -27,12 +27,13 @@ SystemCapability.Customation.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | - | enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | - | type | [AdminType](#AdminType) | Yes | Type of the device administrator to activate. | - | callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | +| type | [AdminType](#AdminType) | Yes | Type of the device administrator to enable. | +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -45,7 +46,7 @@ let enterpriseInfo = { name: "enterprise name", description: "enterprise description" } -enterpriseDeviceManager.activateAdmin(wantTemp, enterpriseInfo, enterpriseDeviceManager.AdminType.ADMIN_TYPE_NORMAL, (error, result) => { +enterpriseDeviceManager.enableAdmin(wantTemp, enterpriseInfo, enterpriseDeviceManager.AdminType.ADMIN_TYPE_NORMAL, 100, (error, result) => { if (error != null) { console.log("error occurs" + error); return; @@ -54,11 +55,11 @@ enterpriseDeviceManager.activateAdmin(wantTemp, enterpriseInfo, enterpriseDevice }); ``` -## enterpriseDeviceManager.activateAdmin +## enterpriseDeviceManager.enableAdmin -activateAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType): Promise\ +enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId?: number): Promise\ -Activates a device administrator application based on the specified bundle name and class name. This API uses a promise to return the result. +Enables a device administrator application based on the specified bundle name and class name. This API uses a promise to return the result. **Required permissions** @@ -70,11 +71,12 @@ SystemCapability.Customation.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | -------------- | ---------------------------------------------- | ---- | ------------------------ | - | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | - | enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | - | type | [AdminType](#AdminType) | Yes | Type of the device administrator to activate. | +| Name | Type | Mandatory | Description | +| -------------- | ---------------------------------------------- | ---- | ------------------------ | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | +| type | [AdminType](#AdminType) | Yes | Type of the device administrator to enable. | +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -93,7 +95,7 @@ let enterpriseInfo = { name: "enterprise name", description: "enterprise description" } -enterpriseDeviceManager.activateAdmin(wantTemp, enterpriseInfo, enterpriseDeviceManager.AdminType.ADMIN_TYPE_NORMAL) +enterpriseDeviceManager.enableAdmin(wantTemp, enterpriseInfo, enterpriseDeviceManager.AdminType.ADMIN_TYPE_NORMAL, 100) .then((result) => { console.log(result); }).catch(error => { @@ -101,11 +103,11 @@ enterpriseDeviceManager.activateAdmin(wantTemp, enterpriseInfo, enterpriseDevice }); ``` -## enterpriseDeviceManager.deactivateAdmin +## enterpriseDeviceManager.disableAdmin -deactivateAdmin(admin: Want, callback: AsyncCallback\): void +disableAdmin(admin: Want, userId?: number, callback: AsyncCallback\): void -Deactivates a device common administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. +Disables a device common administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. **Required permissions** @@ -117,10 +119,11 @@ SystemCapability.Customation.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | -------- | ---------------------------------------------- | ---- | ------------------------------ | - | admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. | - | callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------------- | ---- | ------------------------------ | +| admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. | +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -129,7 +132,7 @@ let wantTemp = { bundleName: elementName.bundleName, abilityName: elementName.abilityName, }; -enterpriseDeviceManager.deactivateAdmin(wantTemp, (error, result) => { +enterpriseDeviceManager.disableAdmin(wantTemp, 100, (error, result) => { if (error != null) { console.log("error occurs" + error); return; @@ -140,11 +143,11 @@ enterpriseDeviceManager.deactivateAdmin(wantTemp, (error, result) => { -## enterpriseDeviceManager.deactivateAdmin +## enterpriseDeviceManager.disableAdmin -deactivateAdmin(admin: Want): Promise\ +disableAdmin(admin: Want, userId?: number): Promise\ -Deactivates a device common administrator application based on the specified bundle name and class name. This API uses a promise to return the result. +Disables a device common administrator application based on the specified bundle name and class name. This API uses a promise to return the result. **Required permissions** @@ -156,9 +159,10 @@ SystemCapability.Customation.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | ------ | ---------------------------------------------- | ---- | ------------------ | - | admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. | +| Name | Type | Mandatory | Description | +| ------ | ---------------------------------------------- | ---- | ------------------ | +| admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. | +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -173,18 +177,18 @@ let wantTemp = { bundleName: "bundleName", abilityName: "abilityName", }; -enterpriseDeviceManager.deactivateAdmin(wantTemp).then((result) => { +enterpriseDeviceManager.disableAdmin(wantTemp, 100).then((result) => { console.log(result); }).catch(error => { console.log("error occurs" + error); }); ``` -## enterpriseDeviceManager.deactivateSuperAdmin +## enterpriseDeviceManager.disableSuperAdmin -deactivateSuperAdmin(bundleName: String, callback: AsyncCallback\): void +disableSuperAdmin(bundleName: String, callback: AsyncCallback\): void -Deactivates a device super administrator application based on the specified bundle name. This API uses an asynchronous callback to return the result. +Disables a device super administrator application based on the specified bundle name. This API uses an asynchronous callback to return the result. **System capability** @@ -201,7 +205,7 @@ SystemCapability.Customation.EnterpriseDeviceManager ``` let bundleName = "com.example.myapplication"; -enterpriseDeviceManager.deactivateSuperAdmin(bundleName, (error, result) => { +enterpriseDeviceManager.disableSuperAdmin(bundleName, (error, result) => { if (error != null) { console.log("error occurs" + error); return; @@ -210,11 +214,11 @@ enterpriseDeviceManager.deactivateSuperAdmin(bundleName, (error, result) => { }); ``` -## enterpriseDeviceManager.deactivateSuperAdmin +## enterpriseDeviceManager.disableSuperAdmin -deactivateSuperAdmin(bundleName: String): Promise\ +disableSuperAdmin(bundleName: String): Promise\ -Deactivates a device super administrator application based on the specified bundle name. This API uses a promise to return the result. +Disables a device super administrator application based on the specified bundle name. This API uses a promise to return the result. **System capability** @@ -236,18 +240,18 @@ SystemCapability.Customation.EnterpriseDeviceManager ``` let bundleName = "com.example.myapplication"; -enterpriseDeviceManager.deactivateSuperAdmin(bundleName).then((result) => { +enterpriseDeviceManager.disableSuperAdmin(bundleName).then((result) => { console.log(result); }).catch(error => { console.log("error occurs" + error); }); ``` -## enterpriseDeviceManager.isAdminAppActive +## enterpriseDeviceManager.isAdminEnabled -isAdminAppActive(admin: Want, callback: AsyncCallback\): void +isAdminEnabled(admin: Want, userId?: number, callback: AsyncCallback\): void -Checks whether a device administrator application is activated based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. +Checks whether a device administrator application is enabled based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. **System capability** @@ -255,10 +259,11 @@ SystemCapability.Customation.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | -------- | ---------------------------------------------- | ---- | -------------------------------- | - | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | - | callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------------- | ---- | -------------------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -267,7 +272,7 @@ let wantTemp = { bundleName: elementName.bundleName, abilityName: elementName.abilityName, }; -enterpriseDeviceManager.isAdminAppActive(wantTemp, (error, result) => { +enterpriseDeviceManager.isAdminEnabled(wantTemp, 100, (error, result) => { if (error != null) { console.log("error occurs" + error); return; @@ -278,11 +283,11 @@ enterpriseDeviceManager.isAdminAppActive(wantTemp, (error, result) => { -## enterpriseDeviceManager.isAdminAppActive +## enterpriseDeviceManager.isAdminEnabled -isAdminAppActive(admin: Want): Promise\ +isAdminEnabled(admin: Want, userId?: number): Promise\ -Checks whether a device administrator application is activated based on the specified bundle name and class name. This API uses a promise to return the result. +Checks whether a device administrator application is enabled based on the specified bundle name and class name. This API uses a promise to return the result. **System capability** @@ -290,9 +295,10 @@ SystemCapability.Customation.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | ------ | ---------------------------------------------- | ---- | -------------- | - | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| Name | Type | Mandatory | Description | +| ------ | ---------------------------------------------- | ---- | -------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -307,7 +313,7 @@ let wantTemp = { bundleName: "bundleName", abilityName: "abilityName", }; -enterpriseDeviceManager.isAdminAppActive(wantTemp).then((result) => { +enterpriseDeviceManager.isAdminEnabled(wantTemp, 100).then((result) => { console.log(result); }).catch(error => { console.log("error occurs" + error); @@ -318,7 +324,7 @@ enterpriseDeviceManager.isAdminAppActive(wantTemp).then((result) => { isSuperAdmin(bundleName: String, callback: AsyncCallback\): void -Checks whether a device super administrator application is activated based on the specified bundle name. This API uses an asynchronous callback to return the result. +Checks whether a device super administrator application is enabled based on the specified bundle name. This API uses an asynchronous callback to return the result. **System capability** @@ -350,7 +356,7 @@ enterpriseDeviceManager.isSuperAdmin(bundleName, (error, result) => { isSuperAdmin(bundleName: String): Promise\ -Checks whether a device super administrator application is activated based on the specified bundle name. This API uses a promise to return the result. +Checks whether a device super administrator application is enabled based on the specified bundle name. This API uses a promise to return the result. **System capability** diff --git a/en/application-dev/reference/apis/js-apis-featureAbility.md b/en/application-dev/reference/apis/js-apis-featureAbility.md index 578fb21ef40144ad14616abd58e9219dc57e3cbd..9ec94e3742fd02c72880475bb2fc59c34f296a14 100644 --- a/en/application-dev/reference/apis/js-apis-featureAbility.md +++ b/en/application-dev/reference/apis/js-apis-featureAbility.md @@ -923,7 +923,7 @@ Enumerates operation types of the Data ability. **System capability**: SystemCapability.Ability.AbilityBase -| Name | Name | Description | +| Name | Value | Description | | ------------------------------------ | ---------- | ---------------------------------------- | | FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. | | FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write the URI. | diff --git a/en/application-dev/reference/apis/js-apis-formextension.md b/en/application-dev/reference/apis/js-apis-formextension.md index 0329e0cf3595887133d17c9af400df4b916d7845..87660f087b82eca3e1a3e16538be564d94ed8dd9 100644 --- a/en/application-dev/reference/apis/js-apis-formextension.md +++ b/en/application-dev/reference/apis/js-apis-formextension.md @@ -21,7 +21,7 @@ None | Name | Type | Readable| Writable| Description | | ------- | ------------------------------------------------------- | ---- | ---- | --------------------------------------------------- | -| context | [FormExtensionContext](js-apis-formextensioncontext.md) | Yes | No | Context of the **FormExtension**. This class is inherited from **ExtensionContext**.| +| context | [FormExtensionContext](js-apis-formextensioncontext.md) | Yes | No | Context of the **FormExtension**. This context is inherited from **ExtensionContext**.| ## onCreate @@ -227,7 +227,7 @@ Called when the configuration of the environment where the ability is running is onAcquireFormState?(want: Want): formInfo.FormState; -Used by the widget provider to receive the widget state query request. By default, the initial widget state is returned. +Called when the widget provider receives the status query result of a specified service widget. By default, the initial state is returned. **System capability**: SystemCapability.Ability.Form diff --git a/en/application-dev/reference/apis/js-apis-hilog.md b/en/application-dev/reference/apis/js-apis-hilog.md index 107d3419b8a8b2840d54b90c5e239ea2fea85ac3..4d45271a8791a8370ed4950c75ac96c0fb408b8c 100644 --- a/en/application-dev/reference/apis/js-apis-hilog.md +++ b/en/application-dev/reference/apis/js-apis-hilog.md @@ -1,7 +1,6 @@ # HiLog The HiLog subsystem allows your applications or services to output logs based on the specified type, level, and format string. Such logs help you learn the running status of applications and better debug programs. -This document describes only API functions. For details about log printing requirements, see [Logging Guide](../../../contribute/OpenHarmony-Log-guide.md). > **NOTE**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/apis/js-apis-hisysevent.md b/en/application-dev/reference/apis/js-apis-hisysevent.md new file mode 100644 index 0000000000000000000000000000000000000000..5564b1a7fc8024284fabf6ada9efaa08f8d0cb73 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-hisysevent.md @@ -0,0 +1,345 @@ +# System Event Logging + +Provides system event logging APIs for system HAP applications. + +> **NOTE**
+> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs of this module are system APIs and cannot be called by third-party applications. + + +## Modules to Import + +```js +import hiSysEvent from '@ohos.hiSysEvent'; +``` + +## EventType + +Enumerates event types. + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| FAULT | 1 | Error event.| +| STATISTIC | 2 | Statistic event.| +| SECURITY | 3 | Security event.| +| BEHAVIOR | 4 | User behavior event.| + +## SysEventInfo + +Defines a system event. + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| domain | string | Yes| Event domain.| +| name | string | Yes| Event name.| +| eventType | [EventType](#eventtype) | Yes| Event type.| +| params | object | No| Event parameters.| + + +## hiSysEvent.write + +write(info: SysEventInfo, callback: AsyncCallback<void>): void + +Writes event information to the event file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------- | ---- | ------------------------------------------------------------ | +| info | [SysEventInfo](#syseventinfo) | Yes| System event information.| +| callback | AsyncCallback<void> | Yes| Callback used to process the received return value.
- Value **0**: The event verification is successful, and the event will be written to the event file asynchronously.
- A value greater than **0**: Invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored.
- A value smaller than **0**: The event parameter verification fails, and the event will not be written to the event file.| + +**Example** + +```js +import hiSysEvent from '@ohos.hiSysEvent'; + +hiSysEvent.write({ + domain: "RELIABILITY", + name: "STACK", + eventType: hiSysEvent.EventType.FAULT, + params: { + PID: 487, + UID: 103, + PACKAGE_NAME: "com.ohos.hisysevent.test", + PROCESS_NAME: "syseventservice", + MSG: "no msg." + } +}, (err, val) => { + // do something here. +}) +``` + + +## hiSysEvent.write + +write(info: SysEventInfo): Promise<void> + +Writes event information to the event file. This API uses a promise to return the result. + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +**Parameters** + +| Name | Type | Mandatory| Description| +| --------- | ----------------------- | ---- | --------------- | +| eventType | [EventType](#eventtype) | Yes | Application event type.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------------------------------------ | +| Promise<void> | Promise used to return the result. Depending on whether event writing is successful, you can use the **then()** or **catch()** method to process the callback.| + +**Example** + +```js +import hiSysEvent from '@ohos.hiSysEvent'; + +hiSysEvent.write({ + domain: "RELIABILITY", + name: "STACK", + eventType: hiSysEvent.EventType.FAULT, + params: { + PID: 487, + UID: 103, + PACKAGE_NAME: "com.ohos.hisysevent.test", + PROCESS_NAME: "syseventservice", + MSG: "no msg." + } +}).then( + (val) => { + // do something here. + } +).catch( + (err) => { + // do something here. + } +) +``` + +## RuleType + +Enumerates matching rule types. + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| WHOLE_WORD | 1 | Whole word matching.| +| PREFIX | 2 | Prefix matching.| +| REGULAR | 3 | Regular expression matching.| + +## WatchRule + +Defines rules for event subscription. + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| domain | string | Yes| Event domain.| +| name | string | Yes| Event name.| +| tag | string | No| Event tag.| +| ruleType | [RuleType](#ruletype) | Yes| Matching rule type.| + +## Watcher + +Defines a watcher for event subscription. + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| rules | [WatchRule](#watchrule)[] | Yes| Array of matching rules for event subscription.| +| onEvent | function | Yes| Callback for event subscription: (info: [SysEventInfo](#syseventinfo)) => void| +| onServiceDied | function | Yes| Callback for disabling of event subscription: () => void| + +## hiSysEvent.addWatcher + +addWatcher(watcher: Watcher): number + +Adds a watcher for event subscription. + +**Required permission**: ohos.permission.READ_DFX_SYSEVENT + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------ | ----------------------------- | ---- | ------------------------ | +| watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.| + +**Return value** + +| Type | Description| +| ------- | -------------------------------------------------- | +| number | Event subscription result.
- **0**: Event subscription is successful.
- A value smaller than **0**: Event subscription has failed.| + +**Example** + +```js +import hiSysEvent from '@ohos.hiSysEvent'; + +let watcher = { + rules: [{ + domain: "RELIABILITY", + name: "STACK", + tag: "STABILITY", + ruleType: hiSysEvent.RuleType.WHOLE_WORD, + }], + onEvent: (info) => { + // do something here. + }, + onServiceDied: () => { + // do something here. + } +} +let ret = hiSysEvent.addWatcher(watcher) +``` + +## hiSysEvent.removeWatcher + +removeWatcher(wathcer: Watcher): number + +Removes a watcher used for event subscription. + +**Required permission**: ohos.permission.READ_DFX_SYSEVENT + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------- | ---- | ------------------------ | +| watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.| + +**Return value** + +| Type | Description| +| ------- | ----------------------------------------------------------- | +| number | Result of removing the watcher.
- **0**: Removing the watcher is successful.
- A value smaller than **0**: Removing the watcher has failed.| + +**Example** + +```js +import hiSysEvent from '@ohos.hiSysEvent'; + +let watcher = { + rules: [{ + domain: "RELIABILITY", + name: "STACK", + tag: "STABILITY", + ruleType: hiSysEvent.RuleType.WHOLE_WORD, + }], + onEvent: (info) => { + // do something here. + }, + onServiceDied: () => { + // do something here. + } +} +let ret = hiSysEvent.addWatcher(watcher) +hiSysEvent.removeWatcher(watcher) +``` + +## QueryArg + +Defines arguments for event query. + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| beginTime | number | Yes| Start time (13-digit timestamp) for event query.| +| endTime | number | Yes| End time (13-digit timestamp) for event query.| +| maxEvents | number | Yes| Maximum number of events that can be queried.| + +## QueryRule + +Defines rules for event query. + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| domain | string | Yes| Event domain.| +| names | string[] | Yes| Array of event names.| + +## Querier + +Defines an event query instance. + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| onQuery | function | Yes| Callback of queried events: (infos: [SysEventInfo](#syseventinfo)[], seqs: number[]) => void| +| onComplete | function | Yes| Callback of query result statistics: (reason: number, total: number) => void| + +## hiSysEvent.query + +query(queryArg: QueryArg, rules: QueryRule[], querier: Querier): number + +Queries system events. + +**Required permission**: ohos.permission.READ_DFX_SYSEVENT + +**System capability**: SystemCapability.HiviewDFX.HiSysEvent + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------ | ----------------------------- | ---- | ------------------------ | +| queryArg | [QueryArg](#queryarg) | Yes | Arguments for event query.| +| rules | [QueryRule](#queryrule)[] | Yes | Array of event query rules.| +| querier | [Querier](#querier) | Yes | Event query instance.| + +**Return value** + +| Type | Description | +| ------- | ----------------------------------------------------------- | +| number | Event query result.
- **0**: Event query is successful.
- A value smaller than **0**: Event query has failed.| + +**Example** + +```js +import hiSysEvent from '@ohos.hiSysEvent'; + +hiSysEvent.write({ + domain: "RELIABILITY", + name: "STACK", + eventType: hiSysEvent.EventType.FAULT, + params: { + PID: 487, + UID: 103, + PACKAGE_NAME: "com.ohos.hisysevent.test", + PROCESS_NAME: "syseventservice", + MSG: "no msg." + } +}, (err, val) => { + // do something here. +}) +hiSysEvent.query({ + beginTime: -1, + endTime: -1, + maxEvents: 5, +}, [{ + domain: "RELIABILITY", + names: ["STACK"], +}], { + onQuery: function (infos, seqs) { + // do something here. + }, + onComplete: function(reason, total) { + // do something here. + } +}) +``` diff --git a/en/application-dev/reference/apis/js-apis-inputdevice.md b/en/application-dev/reference/apis/js-apis-inputdevice.md index b7dc7ccd495f9ea74eb31f17af6bee58036703ad..c47a977b1f2b1559488b6f6602a6ed116ad88197 100644 --- a/en/application-dev/reference/apis/js-apis-inputdevice.md +++ b/en/application-dev/reference/apis/js-apis-inputdevice.md @@ -36,7 +36,7 @@ Enables listening for hot swap events of an input device. let isPhysicalKeyboardExist = true; inputDevice.on("change", (data) => { console.log("type: " + data.type + ", deviceId: " + data.deviceId); - inputDevice.getKeyboardType(data.deviceId, (ret) => { + inputDevice.getKeyboardType(data.deviceId, (err, ret) => { console.log("The keyboard type of the device is: " + ret); if (ret == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'add') { // The physical keyboard is connected. @@ -68,12 +68,12 @@ Disables listening for hot swap events of an input device. **Example** ```js -listener: function(data) { +function listener(data) { console.log("type: " + data.type + ", deviceId: " + data.deviceId); } // Disable this listener. -inputDevice.off("change", this.listener); +inputDevice.off("change", listener); // Disable all listeners. inputDevice.off("change"); @@ -104,7 +104,7 @@ inputDevice.getDeviceIds((ids)=>{ ## inputDevice.getDeviceIds -function getDeviceIds(): Promise<<Array<number>> +getDeviceIds(): Promise<Array<number>> Obtains the IDs of all input devices. This API uses a promise to return the result. @@ -150,7 +150,7 @@ inputDevice.getDevice(1, (inputDevice)=>{ ## inputDevice.getDevice -function getDevice(deviceId: number): Promise<InputDeviceData> +getDevice(deviceId: number): Promise<InputDeviceData> Obtains information about an input device. This API uses a promise to return the result. @@ -336,7 +336,7 @@ Defines the axis range of an input device. | Name | Type | Description | | ----------------------- | ------------------------- | -------- | | source | [SourceType](#sourcetype) | Input source type of the axis.| -| axis | [AxisType](axistype) | Axis type. | +| axis | [AxisType](#axistype) | Axis type. | | max | number | Maximum value of the axis. | | min | number | Minimum value of the axis. | | fuzz9+ | number | Fuzzy value of the axis. | diff --git a/en/application-dev/reference/apis/js-apis-inputmethod.md b/en/application-dev/reference/apis/js-apis-inputmethod.md index a89590f552dd1a55408fd2743bffc9cde1f73e14..c61ca55fd32ff103763e4271392c0e23c83deda7 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod.md @@ -1,6 +1,6 @@ # Input Method Framework -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> **NOTE**
The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > @@ -48,9 +48,9 @@ Obtains an [InputMethodController](#InputMethodController) instance. **Example** -``` -var InputMethodController = inputMethod.getInputMethodController(); -``` + ```js + var InputMethodController = inputMethod.getInputMethodController(); + ``` ## inputMethod.getInputMethodSetting8+ @@ -140,18 +140,18 @@ Obtains the list of installed input methods. This API uses an asynchronous callb **Example** -```js - InputMethodSetting.listInputMethod((properties)=>{ - for (var i = 0;i < properties.length; i++) { - var property = properties[i]; - console.info(property.packageName + "/" + property.methodId); - } -}); -``` + ```js + InputMethodSetting.listInputMethod((properties)=>{ + for (var i = 0;i < properties.length; i++) { + var property = properties[i]; + console.info(property.packageName + "/" + property.methodId); + } + }); + ``` ### listInputMethod -listInputMethod(): Array<InputMethodProperty> +listInputMethod(): Promise<Array<InputMethodProperty>> Obtains the list of installed input methods. This API uses an asynchronous callback to return the result. diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index 90041e190287f35f80ed0913690a8cdc3b11ae45..248e344bf277209c341e2d88d91bd98a13add52b 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -1,6 +1,7 @@ # Media > **NOTE** +> > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. The multimedia subsystem provides a set of simple and easy-to-use APIs for you to access the system and use media resources. @@ -117,7 +118,7 @@ Creates an **AudioRecorder** instance to control audio recording. **Example** ```js -let audiorecorder = media.createAudioRecorder(); +let audioRecorder = media.createAudioRecorder(); ``` ## media.createVideoRecorder9+ @@ -1679,34 +1680,34 @@ let audioRecorderConfig = { uri : 'fd://xx', // The file must be created by the caller and granted with proper permissions. location : { latitude : 30, longitude : 130}, } -audioRecorder.on('error', (error) => { // Set the 'error' event callback. +audioRecorder.on('error', (error) => { // Set the error event callback. console.info(`audio error called, errName is ${error.name}`); console.info(`audio error called, errCode is ${error.code}`); console.info(`audio error called, errMessage is ${error.message}`); }); -audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. +audioRecorder.on('prepare', () => { // Set the prepare event callback. console.log('prepare success'); - audioRecorder.start(); // Start recording and trigger the 'start' event callback. + audioRecorder.start(); // Start recording and trigger the start event callback. }); -audioRecorder.on('start', () => { // Set the 'start' event callback. +audioRecorder.on('start', () => { // Set the start event callback. console.log('audio recorder start success'); }); -audioRecorder.on('pause', () => { // Set the 'pause' event callback. +audioRecorder.on('pause', () => { // Set the pause event callback. console.log('audio recorder pause success'); }); -audioRecorder.on('resume', () => { // Set the 'resume' event callback. +audioRecorder.on('resume', () => { // Set the resume event callback. console.log('audio recorder resume success'); }); -audioRecorder.on('stop', () => { // Set the 'stop' event callback. +audioRecorder.on('stop', () => { // Set the stop event callback. console.log('audio recorder stop success'); }); -audioRecorder.on('release', () => { // Set the 'release' event callback. +audioRecorder.on('release', () => { // Set the release event callback. console.log('audio recorder release success'); }); -audioRecorder.on('reset', () => { // Set the 'reset' event callback. +audioRecorder.on('reset', () => { // Set the reset event callback. console.log('audio recorder reset success'); }); -audioRecorder.prepare(audioRecorderConfig) // Set recording parameters and trigger the 'prepare' event callback. +audioRecorder.prepare(audioRecorderConfig) // Set recording parameters and trigger the prepare event callback. ``` ### on('error') @@ -1727,12 +1728,12 @@ Subscribes to the audio recording error event. **Example** ```js -audioRecorder.on('error', (error) => { // Set the 'error' event callback. +audioRecorder.on('error', (error) => { // Set the error event callback. console.info(`audio error called, errName is ${error.name}`); // Print the error name. console.info(`audio error called, errCode is ${error.code}`); // Print the error code. console.info(`audio error called, errMessage is ${error.message}`); // Print the detailed description of the error type. }); -audioRecorder.prepare(); // Do no set any parameter in prepare and trigger the 'error' event callback. +audioRecorder.prepare(); // Do no set any parameter in prepare and trigger the error event callback. ``` ## AudioRecorderConfig @@ -1749,7 +1750,7 @@ Describes audio recording configurations. | numberOfChannels | number | No | Number of audio channels. The default value is **2**. | | format | [AudioOutputFormat](#audiooutputformat) | No | Audio output format. The default value is **MPEG_4**. | | location | [Location](#location) | No | Geographical location of the recorded audio. | -| uri | string | Yes | Audio output URI. Supported: fd://xx (fd number)
![en-us_image_0000001164217678](figures/en-us_image_url.png)
The file must be created by the caller and granted with proper permissions.| +| uri | string | Yes | Audio output URI. Supported: fd://xx (fd number)
![en-us_image_0000001164217678](figures/en-us_image_url.png)
The file must be created by the caller and granted with proper permissions.| | audioEncoderMime | [CodecMimeType](#codecmimetype8) | No | Audio encoding format. | @@ -2347,7 +2348,7 @@ Subscribes to the video recording error event. **Example** ```js -videoRecorder.on('error', (error) => { // Set the 'error' event callback. +videoRecorder.on('error', (error) => { // Set the error event callback. console.info(`audio error called, errName is ${error.name}`); // Print the error name. console.info(`audio error called, errCode is ${error.code}`); // Print the error code. console.info(`audio error called, errMessage is ${error.message}`); // Print the detailed description of the error type. @@ -2383,7 +2384,7 @@ Describes the video recording parameters. | profile | [VideoRecorderProfile](#videorecorderprofile9) | Yes | Video recording profile. | | rotation | number | No | Rotation angle of the recorded video. | | location | [Location](#location) | No | Geographical location of the recorded video. | -| url | string | Yes | Video output URL. Supported: fd://xx (fd number)
![](figures/en-us_image_url.png)
The file must be created by the caller and granted with proper permissions.| +| url | string | Yes | Video output URL. Supported: fd://xx (fd number)
![](figures/en-us_image_url.png)
The file must be created by the caller and granted with proper permissions.| ## AudioSourceType9+ @@ -2434,7 +2435,7 @@ Enumerates the container format types (CFTs). | Name | Value | Description | | ----------- | ----- | --------------------- | -| CFT_MPEG_4 | "mp4" | Video container format MPEG-4 .| +| CFT_MPEG_4 | "mp4" | Video container format MPEG-4.| | CFT_MPEG_4A | "m4a" | Audio container format M4A.| ## Location diff --git a/en/application-dev/reference/apis/js-apis-medialibrary.md b/en/application-dev/reference/apis/js-apis-medialibrary.md index 46ad60a5fe4baee84f673dee354d688e1be4b2a2..3d2f6f3e9703e606847e92822c62aa20c2811e8f 100644 --- a/en/application-dev/reference/apis/js-apis-medialibrary.md +++ b/en/application-dev/reference/apis/js-apis-medialibrary.md @@ -1,6 +1,7 @@ -# Media Library Management +# MediaLibrary -> **NOTE**
+> **NOTE** +> > This component is supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -93,7 +94,7 @@ let imagesfetchOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], }; -mediaLibrary.getFileAssets(imagesfetchOp, (error, fetchFileResult) => { +media.getFileAssets(imagesfetchOp, (error, fetchFileResult) => { if (fetchFileResult != undefined) { console.info('mediaLibraryTest : ASSET_CALLBACK fetchFileResult success'); fetchFileResult.getAllObject((err, fileAssetList) => { @@ -135,7 +136,7 @@ let imagesfetchOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], }; -mediaLibrary.getFileAssets(imagesfetchOp).then(function(fetchFileResult){ +media.getFileAssets(imagesfetchOp).then(function(fetchFileResult){ console.info("getFileAssets successfully:"+ JSON.stringify(dir)); }).catch(function(err){ console.info("getFileAssets failed with error:"+ err); @@ -182,7 +183,7 @@ Unsubscribes from the media library changes. This API uses an asynchronous callb **Example** ``` -mediaLibrary.off('imageChange', () => { +media.off('imageChange', () => { // stop listening success }) ``` @@ -350,7 +351,7 @@ let AlbumNoArgsfetchOp = { selections: '', selectionArgs: [], }; -mediaLibrary.getAlbums(AlbumNoArgsfetchOp, (err, albumList) => { +media.getAlbums(AlbumNoArgsfetchOp, (err, albumList) => { if (albumList != undefined) { const album = albumList[0]; console.info('album.albumName = ' + album.albumName); @@ -390,7 +391,7 @@ let AlbumNoArgsfetchOp = { selections: '', selectionArgs: [], }; -mediaLibrary.getAlbums(AlbumNoArgsfetchOp).then(function(albumList){ +media.getAlbums(AlbumNoArgsfetchOp).then(function(albumList){ console.info("getAlbums successfully:"+ JSON.stringify(albumList)); }).catch(function(err){ console.info("getAlbums failed with error:"+ err); @@ -439,7 +440,6 @@ Call this API when you no longer need to use the APIs in the **MediaLibrary** in **Example** ``` -var media = mediaLibrary.getMediaLibrary(context); media.release() ``` @@ -1957,7 +1957,7 @@ async function example() { Provides APIs to implement a physical album. -### **Attributes** +### Attributes **System capability**: SystemCapability.Multimedia.MediaLibrary.Core diff --git a/en/application-dev/reference/apis/js-apis-mediaquery.md b/en/application-dev/reference/apis/js-apis-mediaquery.md index 7cb3263efc4800810a185bf908ae98fef33808ec..1f754aa69bee3f93a3420df473d06e915a673c4f 100644 --- a/en/application-dev/reference/apis/js-apis-mediaquery.md +++ b/en/application-dev/reference/apis/js-apis-mediaquery.md @@ -1,12 +1,13 @@ # Media Query -> ![icon-note.gif](public_sys-resources/icon-note.gif)**NOTE** +> **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. ## Modules to Import -``` +```js import mediaquery from '@ohos.mediaquery' ``` @@ -22,19 +23,19 @@ matchMediaSync(condition: string): MediaQueryListener Sets the media query criteria and returns the corresponding listening handle. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | condition | string | Yes| Matching condition of a media event.| +**Parameters** +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | ---------- | +| condition | string | Yes | Matching condition of a media event.| -- Return value - | Type| Description| - | -------- | -------- | - | MediaQueryListener | Listening handle to a media event, which is used to register or unregister the listening callback.| +**Return value** +| Type | Description | +| ------------------ | ---------------------- | +| MediaQueryListener | Listening handle to a media event, which is used to register or unregister the listening callback.| -- Example - ``` - listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. +**Example** + ```js +listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. ``` @@ -45,10 +46,10 @@ Media query handle, including the first query result when the handle is applied ### Attributes -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| matches | boolean | Yes| No| Whether the match condition is met.| -| media | string | Yes| No| Matching condition of a media event.| +| Name | Type | Readable | Writable | Description | +| ------- | ------- | ---- | ---- | ---------- | +| matches | boolean | Yes | No | Whether the match condition is met. | +| media | string | Yes | No | Matching condition of a media event.| ### on @@ -57,13 +58,13 @@ on(type: 'change', callback: Callback<MediaQueryResult>): void Registers a callback with the corresponding query condition by using the handle. This callback is triggered when the media attributes change. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Must enter the string **change**.| - | callback | Callback<MediaQueryResult> | Yes| Callback registered with media query.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | -------------------------------- | ---- | ---------------- | +| type | string | Yes | Must enter the string **change**.| +| callback | Callback<MediaQueryResult> | Yes | Callback registered with media query. | -- Example +**Example** For details, see [off Example](#off). @@ -72,14 +73,14 @@ Registers a callback with the corresponding query condition by using the handle. off(type: 'change', callback?: Callback<MediaQueryResult>): void Unregisters a callback with the corresponding query condition by using the handle, so that no callback is triggered when the media attributes change. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | boolean | Yes| Must enter the string **change**.| - | callback | Callback<MediaQueryResult> | No| Callback to be unregistered. If the default value is used, all callbacks of the handle are unregistered.| - -- Example - ``` +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | -------------------------------- | ---- | ----------------------------- | +| type | boolean | Yes | Must enter the string **change**. | +| callback | Callback<MediaQueryResult> | No | Callback to be unregistered. If the default value is used, all callbacks of the handle are unregistered.| + +**Example** + ```js import mediaquery from '@ohos.mediaquery' listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. @@ -90,8 +91,8 @@ Unregisters a callback with the corresponding query condition by using the handl // do something here } } - this.listener.on('change', this.onPortrait) // Registration callback. - this.listener.off('change', this.onPortrait) // Deregistration callback. + listener.on('change', onPortrait) // Register a callback. + listener.off('change', onPortrait) // Unregister a callback. ``` @@ -100,15 +101,15 @@ Unregisters a callback with the corresponding query condition by using the handl ### Attributes -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| matches | boolean | Yes| No| Whether the match condition is met.| -| media | string | Yes| No| Matching condition of a media event.| +| Name | Type | Readable | Writable | Description | +| ------- | ------- | ---- | ---- | ---------- | +| matches | boolean | Yes | No | Whether the match condition is met. | +| media | string | Yes | No | Matching condition of a media event.| ### Example -``` +```js import mediaquery from '@ohos.mediaquery' let portraitFunc = null diff --git a/en/application-dev/reference/apis/js-apis-nfcController.md b/en/application-dev/reference/apis/js-apis-nfcController.md index 3f5bc3c0db412c3837e6a8259c3bd2365d27553c..d4c99452483b63a9893905329d4fd1aae0be4505 100644 --- a/en/application-dev/reference/apis/js-apis-nfcController.md +++ b/en/application-dev/reference/apis/js-apis-nfcController.md @@ -1,6 +1,6 @@ # Standard NFC -This module is used to implement Near-Field Communication (NFC). +Implements Near-Field Communication (NFC). > **NOTE**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -90,7 +90,7 @@ Obtains the NFC state. on(type: "nfcStateChange", callback: Callback<NfcState>): void -Registers NFC state changes. +Subscribes to NFC state changes. **System capability**: SystemCapability.Communication.NFC @@ -107,7 +107,7 @@ Registers NFC state changes. off(type: "nfcStateChange", callback?: Callback<NfcState>): void -Unregisters the NFC state changes. +Unsubscribes from the NFC state changes. **System capability**: SystemCapability.Communication.NFC @@ -129,10 +129,10 @@ Unregisters the NFC state changes. console.info("nfc state receive state: " + result); } - // Register the NFC state changes. + // Subscribe to the NFC state changes. nfcController.on(NFC_STATE_NOTIFY, recvNfcStateNotifyFunc); - // Unregister the NFC state changes. + // Unsubscribe from the NFC state changes. nfcController.off(NFC_STATE_NOTIFY, recvNfcStateNotifyFunc); ``` diff --git a/en/application-dev/reference/apis/js-apis-nfcTag.md b/en/application-dev/reference/apis/js-apis-nfcTag.md index 160bac7842cbdb4a289361eb00de1ba12892d64e..51731e95e192713e71add3304331475c11dd6629 100644 --- a/en/application-dev/reference/apis/js-apis-nfcTag.md +++ b/en/application-dev/reference/apis/js-apis-nfcTag.md @@ -1,6 +1,6 @@ # Standard NFC Tag -This module is used to manage Near-Field Communication (NFC) tags. +Manages Near-Field Communication (NFC) tags. > **NOTE**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -17,7 +17,7 @@ import tag from '@ohos.nfc.tag'; getNfcATag(tagInfo: TagInfo): NfcATag -Obtains the **NfcATag** object, which allows access to the tags that use the NfcA technology. +Obtains an **NfcATag** object, which allows access to the tags that use the NFC-A technology. **Required permissions**: ohos.permission.NFC_TAG @@ -33,7 +33,7 @@ Obtains the **NfcATag** object, which allows access to the tags that use the Nfc getNfcBTag(tagInfo: TagInfo): NfcBTag -Obtains the **NfcBTag** object, which allows access to the tags that use the NfcB technology. +Obtains an **NfcBTag** object, which allows access to the tags that use the NFC-B technology. **Required permissions**: ohos.permission.NFC_TAG @@ -49,7 +49,7 @@ Obtains the **NfcBTag** object, which allows access to the tags that use the Nfc getNfcFTag(tagInfo: TagInfo): NfcFTag -Obtains the **NfcFTag** object, which allows access to the tags that use the NfcF technology. +Obtains an **NfcFTag** object, which allows access to the tags that use the NFC-F technology. **Required permissions**: ohos.permission.NFC_TAG @@ -65,7 +65,7 @@ Obtains the **NfcFTag** object, which allows access to the tags that use the Nfc getNfcVTag(tagInfo: TagInfo): NfcVTag -Obtains the **NfcVTag** object, which allows access to the tags that use the NfcV technology. +Obtains an **NfcVTag** object, which allows access to the tags that use the NFC-V technology. **Required permissions**: ohos.permission.NFC_TAG diff --git a/en/application-dev/reference/apis/js-apis-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md index f0e93479b923928923f27bcda147a7c8d23f0d59..bb62764d00730e1abb51a3b302915cd6bee264ca 100644 --- a/en/application-dev/reference/apis/js-apis-osAccount.md +++ b/en/application-dev/reference/apis/js-apis-osAccount.md @@ -1,6 +1,6 @@ # OS Account Management -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -48,7 +48,7 @@ Provides methods to manage OS accounts. activateOsAccount(localId: number, callback: AsyncCallback<void>): void -Activates an OS account. This method uses an asynchronous callback to return the result. +Activates an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -76,7 +76,7 @@ This is a system API and cannot be called by third-party applications. activateOsAccount(localId: number): Promise<void> -Activates an OS account. This method uses a promise to return the result. +Activates an OS account. This API uses a promise to return the result asynchronously. This is a system API and cannot be called by third-party applications. @@ -111,7 +111,7 @@ This is a system API and cannot be called by third-party applications. isMultiOsAccountEnable(callback: AsyncCallback<boolean>): void -Checks whether multiple OS accounts are supported. This method uses an asynchronous callback to return the result. +Checks whether multiple OS accounts are supported. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -135,7 +135,7 @@ Checks whether multiple OS accounts are supported. This method uses an asynchron isMultiOsAccountEnable(): Promise<boolean> -Checks whether multiple OS accounts are supported. This method uses a promise to return the result. +Checks whether multiple OS accounts are supported. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.Account.OsAccount @@ -160,7 +160,7 @@ Checks whether multiple OS accounts are supported. This method uses a promise to isOsAccountActived(localId: number, callback: AsyncCallback<boolean>): void -Checks whether an OS account is activated. This method uses an asynchronous callback to return the result. +Checks whether an OS account is activated. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -188,7 +188,7 @@ Checks whether an OS account is activated. This method uses an asynchronous call isOsAccountActived(localId: number): Promise<boolean> -Checks whether an OS account is activated. This method uses a promise to return the result. +Checks whether an OS account is activated. This API uses a promise to return the result asynchronously. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -222,7 +222,7 @@ Checks whether an OS account is activated. This method uses a promise to return isOsAccountConstraintEnable(localId: number, constraint: string, callback: AsyncCallback<boolean>): void -Checks whether the specified constraint is enabled for an OS account. This method uses an asynchronous callback to return the result. +Checks whether the specified constraint is enabled for an OS account. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -251,7 +251,7 @@ Checks whether the specified constraint is enabled for an OS account. This metho isOsAccountConstraintEnable(localId: number, constraint: string): Promise<boolean> -Checks whether the specified constraint is enabled for an OS account. This method uses a promise to return the result. +Checks whether the specified constraint is enabled for an OS account. This API uses a promise to return the result asynchronously. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -286,7 +286,7 @@ Checks whether the specified constraint is enabled for an OS account. This metho isTestOsAccount(callback: AsyncCallback<boolean>): void -Checks whether this OS account is a test account. This method uses an asynchronous callback to return the result. +Checks whether this OS account is a test account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -310,7 +310,7 @@ Checks whether this OS account is a test account. This method uses an asynchrono isTestOsAccount(): Promise<boolean> -Checks whether this OS account is a test account. This method uses a promise to return the result. +Checks whether this OS account is a test account. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.Account.OsAccount @@ -335,7 +335,7 @@ Checks whether this OS account is a test account. This method uses a promise to isOsAccountVerified(callback: AsyncCallback<boolean>): void -Checks whether this OS account has been verified. This method uses an asynchronous callback to return the result. +Checks whether this OS account has been verified. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -359,7 +359,7 @@ Checks whether this OS account has been verified. This method uses an asynchrono isOsAccountVerified(localId: number, callback: AsyncCallback<boolean>): void -Checks whether an OS account has been verified. This method uses an asynchronous callback to return the result. +Checks whether an OS account has been verified. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -386,7 +386,7 @@ Checks whether an OS account has been verified. This method uses an asynchronous isOsAccountVerified(localId?: number): Promise<boolean> -Checks whether an OS account has been verified. This method uses a promise to return the result. +Checks whether an OS account has been verified. This API uses a promise to return the result asynchronously. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -419,7 +419,7 @@ Checks whether an OS account has been verified. This method uses a promise to re removeOsAccount(localId: number, callback: AsyncCallback<void>): void -Removes an OS account. This method uses an asynchronous callback to return the result. +Removes an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -451,7 +451,7 @@ This is a system API and cannot be called by third-party applications. removeOsAccount(localId: number): Promise<void> -Removes an OS account. This method uses a promise to return the result. +Removes an OS account. This API uses a promise to return the result asynchronously. This is a system API and cannot be called by third-party applications. @@ -491,7 +491,7 @@ This is a system API and cannot be called by third-party applications. setOsAccountConstraints(localId: number, constraints: Array<string>, enable: boolean,callback: AsyncCallback<void>): void -Sets or removes constraints for an OS account. This method uses an asynchronous callback to return the result. +Sets or removes constraints for an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -522,7 +522,7 @@ This is a system API and cannot be called by third-party applications. setOsAccountConstraints(localId: number, constraints: Array<string>, enable: boolean): Promise<void> -Sets or removes constraints for an OS account. This method uses a promise to return the result. +Sets or removes constraints for an OS account. This API uses a promise to return the result asynchronously. This is a system API and cannot be called by third-party applications. @@ -560,7 +560,7 @@ This is a system API and cannot be called by third-party applications. setOsAccountName(localId: number, localName: string, callback: AsyncCallback<void>): void -Sets a name for an OS account. This method uses an asynchronous callback to return the result. +Sets a name for an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -591,7 +591,7 @@ This is a system API and cannot be called by third-party applications. setOsAccountName(localId: number, localName: string): Promise<void> -Sets a name for an OS account. This method uses a promise to return the result. +Sets a name for an OS account. This API uses a promise to return the result asynchronously. This is a system API and cannot be called by third-party applications. @@ -629,7 +629,7 @@ This is a system API and cannot be called by third-party applications. getCreatedOsAccountsCount(callback: AsyncCallback<number>): void -Obtains the number of OS accounts created. This method uses an asynchronous callback to return the result. +Obtains the number of OS accounts created. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -655,7 +655,7 @@ Obtains the number of OS accounts created. This method uses an asynchronous call getCreatedOsAccountsCount(): Promise<number> -Obtains the number of OS accounts created. This method uses a promise to return the result. +Obtains the number of OS accounts created. This API uses a promise to return the result asynchronously. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -682,7 +682,7 @@ Obtains the number of OS accounts created. This method uses a promise to return getOsAccountLocalIdFromProcess(callback: AsyncCallback<number>): void -Obtains the ID of the OS account to which the current process belongs. This method uses an asynchronous callback to return the result. +Obtains the ID of the OS account to which the current process belongs. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -706,7 +706,7 @@ Obtains the ID of the OS account to which the current process belongs. This meth getOsAccountLocalIdFromProcess(): Promise<number> -Obtains the ID of the OS account to which the current process belongs. This method uses a promise to return the result. +Obtains the ID of the OS account to which the current process belongs. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.Account.OsAccount @@ -731,7 +731,7 @@ Obtains the ID of the OS account to which the current process belongs. This meth getOsAccountLocalIdFromUid(uid: number, callback: AsyncCallback<number>): void -Obtains the OS account ID based on the process UID. This method uses an asynchronous callback to return the result. +Obtains the OS account ID based on the process UID. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -757,7 +757,7 @@ Obtains the OS account ID based on the process UID. This method uses an asynchro getOsAccountLocalIdFromUid(uid: number): Promise<number> -Obtains the OS account ID based on the process UID. This method uses a promise to return the result. +Obtains the OS account ID based on the process UID. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.Account.OsAccount @@ -789,7 +789,7 @@ Obtains the OS account ID based on the process UID. This method uses a promise t getOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo, callback: AsyncCallback<number>): void -Obtains the OS account ID based on domain account information. This method uses an asynchronous callback to return the result. +Obtains the OS account ID based on domain account information. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -817,7 +817,7 @@ Obtains the OS account ID based on domain account information. This method uses getOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo): Promise<number> -Obtains the OS account ID based on domain account information. This method uses a promise to return the result. +Obtains the OS account ID based on domain account information. This API uses a promise to return the result asynchronously. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -851,7 +851,7 @@ Obtains the OS account ID based on domain account information. This method uses queryMaxOsAccountNumber(callback: AsyncCallback<number>): void -Obtains the maximum number of OS accounts that can be created. This method uses an asynchronous callback to return the result. +Obtains the maximum number of OS accounts that can be created. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -877,7 +877,7 @@ This is a system API and cannot be called by third-party applications. queryMaxOsAccountNumber(): Promise<number> -Obtains the maximum number of OS accounts that can be created. This method uses a promise to return the result. +Obtains the maximum number of OS accounts that can be created. This API uses a promise to return the result asynchronously. This is a system API and cannot be called by third-party applications. @@ -904,7 +904,7 @@ This is a system API and cannot be called by third-party applications. getOsAccountAllConstraints(localId: number, callback: AsyncCallback<Array<string>>): void -Obtains all constraints enabled for an OS account. This method uses an asynchronous callback to return the result. +Obtains all constraints enabled for an OS account. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -932,7 +932,7 @@ Obtains all constraints enabled for an OS account. This method uses an asynchron getOsAccountAllConstraints(localId: number): Promise<Array<string>> -Obtains all constraints enabled for an OS account. This method uses a promise to return the result. +Obtains all constraints enabled for an OS account. This API uses a promise to return the result asynchronously. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -966,7 +966,7 @@ Obtains all constraints enabled for an OS account. This method uses a promise to queryAllCreatedOsAccounts(callback: AsyncCallback<Array<OsAccountInfo>>): void -Obtains information about all the OS accounts created. This method uses an asynchronous callback to return the result. +Obtains information about all the OS accounts created. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -992,7 +992,7 @@ This is a system API and cannot be called by third-party applications. queryAllCreatedOsAccounts(): Promise<Array<OsAccountInfo>> -Obtains information about all the OS accounts created. This method uses a promise to return the result. +Obtains information about all the OS accounts created. This API uses a promise to return the result asynchronously. This is a system API and cannot be called by third-party applications. @@ -1019,7 +1019,7 @@ This is a system API and cannot be called by third-party applications. queryActivatedOsAccountIds(callback: AsyncCallback<Array<number>>): void -Obtains information about all activated OS accounts. This method uses an asynchronous callback to return the result. +Obtains information about all activated OS accounts. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -1046,7 +1046,7 @@ Obtains information about all activated OS accounts. This method uses an asynchr queryActivatedOsAccountIds(): Promise<Array<number>> -Obtains information about all activated OS accounts. This method uses a promise to return the result. +Obtains information about all activated OS accounts. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.Account.OsAccount @@ -1071,7 +1071,7 @@ Obtains information about all activated OS accounts. This method uses a promise createOsAccount(localName: string, type: OsAccountType, callback: AsyncCallback<OsAccountInfo>): void -Creates an OS account. This method uses an asynchronous callback to return the result. +Creates an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1101,7 +1101,7 @@ This is a system API and cannot be called by third-party applications. createOsAccount(localName: string, type: OsAccountType): Promise<OsAccountInfo> -Creates an OS account. This method uses a promise to return the result. +Creates an OS account. This API uses a promise to return the result asynchronously. This is a system API and cannot be called by third-party applications. @@ -1137,7 +1137,7 @@ This is a system API and cannot be called by third-party applications. createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo, callback: AsyncCallback<OsAccountInfo>): void -Creates an OS account and associates it with the specified domain account. This method uses an asynchronous callback to return the result. +Creates an OS account and associates it with the specified domain account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1168,7 +1168,7 @@ This is a system API and cannot be called by third-party applications. createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo): Promise<OsAccountInfo> -Creates an OS account and associates it with the specified domain account. This method uses a promise to return the result. +Creates an OS account and associates it with the specified domain account. This API uses a promise to return the result asynchronously. This is a system API and cannot be called by third-party applications. @@ -1205,7 +1205,7 @@ This is a system API and cannot be called by third-party applications. queryCurrentOsAccount(callback: AsyncCallback<OsAccountInfo>): void -Obtains information about the OS account to which the current process belongs. This method uses an asynchronous callback to return the result. +Obtains information about the OS account to which the current process belongs. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -1231,7 +1231,7 @@ Obtains information about the OS account to which the current process belongs. T queryCurrentOsAccount(): Promise<OsAccountInfo> -Obtains information about the OS account to which the current process belongs. This method uses a promise to return the result. +Obtains information about the OS account to which the current process belongs. This API uses a promise to return the result asynchronously. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -1258,7 +1258,7 @@ Obtains information about the OS account to which the current process belongs. T queryOsAccountById(localId: number, callback: AsyncCallback<OsAccountInfo>): void -Obtains information about an OS account. This method uses an asynchronous callback to return the result. +Obtains information about an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1288,7 +1288,7 @@ This is a system API and cannot be called by third-party applications. queryOsAccountById(localId: number): Promise<OsAccountInfo> -Obtains information about an OS account. This method uses a promise to return the result. +Obtains information about an OS account. This API uses a promise to return the result asynchronously. This is a system API and cannot be called by third-party applications. @@ -1324,7 +1324,7 @@ This is a system API and cannot be called by third-party applications. getOsAccountTypeFromProcess(callback: AsyncCallback<OsAccountType>): void -Obtains the type of the OS account to which the current process belongs. This method uses an asynchronous callback to return the result. +Obtains the type of the OS account to which the current process belongs. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -1348,7 +1348,7 @@ Obtains the type of the OS account to which the current process belongs. This me getOsAccountTypeFromProcess(): Promise<OsAccountType> -Obtains the type of the OS account to which the current process belongs. This method uses a promise to return the result. +Obtains the type of the OS account to which the current process belongs. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.Account.OsAccount @@ -1373,7 +1373,7 @@ Obtains the type of the OS account to which the current process belongs. This me getDistributedVirtualDeviceId(callback: AsyncCallback<string>): void -Obtains the ID of this distributed virtual device. This method uses an asynchronous callback to return the result. +Obtains the ID of this distributed virtual device. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC or ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -1399,7 +1399,7 @@ Obtains the ID of this distributed virtual device. This method uses an asynchron getDistributedVirtualDeviceId(): Promise<string> -Obtains the ID of this distributed virtual device. This method uses a promise to return the result. +Obtains the ID of this distributed virtual device. This API uses a promise to return the result asynchronously. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC or ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -1426,7 +1426,7 @@ Obtains the ID of this distributed virtual device. This method uses a promise to getOsAccountProfilePhoto(localId: number, callback: AsyncCallback<string>): void -Obtains the profile photo of an OS account. This method uses an asynchronous callback to return the result. +Obtains the profile photo of an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1456,7 +1456,7 @@ This is a system API and cannot be called by third-party applications. getOsAccountProfilePhoto(localId: number): Promise<string> -Obtains the profile photo of an OS account. This method uses a promise to return the result. +Obtains the profile photo of an OS account. This API uses a promise to return the result asynchronously. This is a system API and cannot be called by third-party applications. @@ -1492,7 +1492,7 @@ This is a system API and cannot be called by third-party applications. setOsAccountProfilePhoto(localId: number, photo: string, callback: AsyncCallback<void>): void -Sets a profile photo for an OS account. This method uses an asynchronous callback to return the result. +Sets a profile photo for an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1526,7 +1526,7 @@ This is a system API and cannot be called by third-party applications. setOsAccountProfilePhoto(localId: number, photo: string): Promise<void> -Sets a profile photo for an OS account. This method uses a promise to return the result. +Sets a profile photo for an OS account. This API uses a promise to return the result asynchronously. This is a system API and cannot be called by third-party applications. @@ -1567,7 +1567,7 @@ This is a system API and cannot be called by third-party applications. getOsAccountLocalIdBySerialNumber(serialNumber: number, callback: AsyncCallback<number>): void -Obtains the OS account ID based on the SN. This method uses an asynchronous callback to return the result. +Obtains the OS account ID based on the SN. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -1593,7 +1593,7 @@ Obtains the OS account ID based on the SN. This method uses an asynchronous call getOsAccountLocalIdBySerialNumber(serialNumber: number): Promise<number> -Obtains the OS account ID based on the SN. This method uses a promise to return the result. +Obtains the OS account ID based on the SN. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.Account.OsAccount @@ -1625,7 +1625,7 @@ Obtains the OS account ID based on the SN. This method uses a promise to return getSerialNumberByOsAccountLocalId(localId: number, callback: AsyncCallback<number>): void -Obtains the SN of an OS account based on the account ID. This method uses an asynchronous callback to return the result. +Obtains the SN of an OS account based on the account ID. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -1651,7 +1651,7 @@ Obtains the SN of an OS account based on the account ID. This method uses an asy getSerialNumberByOsAccountLocalId(localId: number): Promise<number> -Obtains the SN of an OS account based on the account ID. This method uses a promise to return the result. +Obtains the SN of an OS account based on the account ID. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.Account.OsAccount @@ -1683,7 +1683,7 @@ Obtains the SN of an OS account based on the account ID. This method uses a prom on(type: 'activate' | 'activating', name: string, callback: Callback<number>): void -Subscribes to OS account changes. This method uses an asynchronous callback to return the result. +Subscribes to OS account changes. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1713,7 +1713,7 @@ This is a system API and cannot be called by third-party applications. off(type: 'activate' | 'activating', name: string, callback?: Callback<number>): void -Unsubscribes from the OS account changes. This method uses an asynchronous callback to return the result. +Unsubscribes from the OS account changes. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1739,6 +1739,173 @@ This is a system API and cannot be called by third-party applications. accountManager.off("activating", "osAccountOnOffNameA", offCallback); ``` +### getBundleIdFromUid9+ + +getBundleIdFromUid(uid: number, callback: AsyncCallback<number>): void; + +Obtains the bundle ID based on the UID. This API uses an asynchronous callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------- | ---- | ------------------------------------------------------------ | +| uid | number | Yes | Process UID.| +| callback | AsyncCallback<number> | Yes | Callback used to return the bundle ID obtained. | + +**Example** + + ```js + var testUid = 1000000; + osAccountManager.getBundleIdFromUid(testUid,(err,bundleId)=>{ + console.info("getBundleIdFromUid errInfo:" + JSON.stringify(err)); + console.info("getBundleIdFromUid bundleId:" + JSON.stringify(bundleId)); + }); + ``` +### getBundleIdFromUid9+ + +getBundleIdFromUid(uid: number): Promise<number>; + +Obtains the bundle ID based on the UID. This API uses a promise to return the result asynchronously. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------ | +| uid | number | Yes | Process UID.| + +**Return Value** + +| Type | Description | +| :-------------------- | :----------------------------------------------------------- | +| Promise<number> | Promise used to return the bundle ID obtained.| + +**Example** + + ```js + var testUid = 1000000; + var bundleIdInfo = await osAccountManager.getBundleIdFromUid(testUid).catch((err)=>{ + console.info("getBundleIdFromUid errInfo:" + JSON.stringify(err));}) + console.info("getBundleIdFromUid bundleId:" + JSON.stringify(bundleIdInfo)); + ``` + +### isMainOsAccount9+ + +isMainOsAccount(callback: AsyncCallback<boolean>): void; + +Checks whether the current process belongs to the main OS account. This API uses an asynchronous callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the current process belongs to the main OS account, **true** will be returned. Otherwise, **false** will be returned. | + +**Example** + + ```js + osAccountManager.isMainOsAccount((err,result)=>{ + console.info("isMainOsAccount errInfo:" + JSON.stringify(err)); + console.info("isMainOsAccount result:" + JSON.stringify(result)); + }); + ``` +### isMainOsAccount9+ + +isMainOsAccount(): Promise<boolean>; + +Checks whether the current process belongs to the main OS account. This API uses a promise to return the result asynchronously. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Return Value** + +| Type | Description | +| :-------------------- | :----------------------------------------------------------- | +| Promise<boolean> | Promise used to return the result. If the current process belongs to the main OS account, **true** will be returned. Otherwise, **false** will be returned.| + +**Example** + + ```js + var result = await osAccountManager.isMainOsAccount().catch((err)=>{ + console.info("isMainOsAccount errInfo:" + JSON.stringify(err)); + }); + console.info("isMainOsAccount result:" + JSON.stringify(result)); + ``` +### queryOsAccountConstraintSourceTypes9+ + +queryOsAccountConstraintSourceTypes(localId: number, constraint: string, callback: AsyncCallback<Array<ConstraintSourceTypeInfo>>): void; + +Obtains the constraint source information of an OS account. + +This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------- | ---- | ------------------------------------------------------------ | +| localId | number | Yes | ID of the target OS account.| +| constraint | string | Yes | Name of the [constraint](#constraints) to query.| +| callback | AsyncCallback<Array<[ConstraintSourceTypeInfo](#constraintsourcetypeinfo)>> | Yes | Callback used to return the source information about the specified [constraint] (#constraints). | + +**Example** + + ```js + osAccountManager.queryOsAccountConstraintSourceTypes(100, "constraint.wifi",(err,sourceTypeInfos)=>{ + console.info("queryOsAccountConstraintSourceType errInfo:" + JSON.stringify(err)); + console.info("queryOsAccountConstraintSourceType sourceTypeInfos:" + JSON.stringify(sourceTypeInfos)); + }); + ``` + +### queryOsAccountConstraintSourceTypes9+ + +queryOsAccountConstraintSourceTypes(localId: number, constraint: string): Promise<Array<ConstraintSourceTypeInfo>>; + +Obtains the constraint source information of an OS account. This API uses a promise to return the result asynchronously. + +This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------ | +| localId | number | Yes | ID of the target OS account.| +| constraint | string | Yes | Name of the [constraint](#constraints) to query.| + +**Return Value** + +| Type | Description | +| :-------------------- | :----------------------------------------------------------- | +| Promise<Array<[ConstraintSourceTypeInfo](#constraintsourcetypeinfo)>> | Promise used to return the source information about the specified [constraint] (#constraints).| + +**Example** + + ```js + var sourceTypeInfos = await osAccountManager.queryOsAccountConstraintSourceTypes(100, "constraint.wifi").catch((err)=>{ + console.info("queryOsAccountConstraintSourceType errInfo:" + JSON.stringify(err));}) + console.info("queryOsAccountConstraintSourceType sourceTypeInfos:" + JSON.stringify(sourceTypeInfos)); + ``` + ## OsAccountInfo Defines information about an OS account. @@ -1839,3 +2006,27 @@ Domain account information. | constraint.screen.timeout.set | A user is not allowed to configure the screen off timeout.| | constraint.print | A user is not allowed to print.| | constraint.private.dns.set | A user is not allowed to configure a private domain name server (DNS).| + +## ConstraintSourceTypeInfo9+ + +Defines information about the source of a constraint. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ---------- | +| localId | number | Yes | ID of the OS account. | +| type | [ConstraintSourceType](#constraintsourcetype) | Yes | Type of the constrain source.| + +## ConstraintSourceType9+ + +Enumerates the constraint sources. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| ------ | ------ | ------------ | +| CONSTRAINT_NOT_EXIST | 0 | The constraint does not exist.| +| CONSTRAINT_TYPE_BASE | 1 | Constraint from system settings. | +| CONSTRAINT_TYPE_DEVICE_OWNER | 2 | Constraint from the device owners' settings. | +| CONSTRAINT_TYPE_PROFILE_OWNER | 3 | Constraint from the profile owners' settings. | diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index 4df1f4e33d37e28fc1ea83d7fde57d32c21df143..86d29eebedf8fb206589a7770a92362a79873c69 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -408,7 +408,7 @@ Checks whether the current device supports 5G \(NR\). ```js let slotId = 0; let result = radio.isNrSupported(slotId); -console.log(result); +console.log("Result: "+ result); ``` diff --git a/en/application-dev/reference/apis/js-apis-request.md b/en/application-dev/reference/apis/js-apis-request.md index fec9be3f8e6b9e7cf42f741f357710c99650c2c3..d1c0ffc0d035800ab2a68f419555abde627c3fb6 100644 --- a/en/application-dev/reference/apis/js-apis-request.md +++ b/en/application-dev/reference/apis/js-apis-request.md @@ -7,7 +7,7 @@ ## Modules to Import -``` +```js import request from '@ohos.request'; ``` @@ -84,8 +84,10 @@ Uploads files. This API uses a promise to return the result. ```js let file1 = { filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }; + let data = { name: "name123", value: "123" }; + let header = { key1: value1, key2: value2 }; let uploadTask; - request.upload({ url: 'https://patch', files: [file1] }).then((data) => { + request.upload({ url: 'https://patch', header: header, method: "POST", files: [file1], data: [data] }).then((data) => { uploadTask = data; }).catch((err) => { console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); @@ -114,8 +116,10 @@ Uploads files. This API uses an asynchronous callback to return the result. ```js let file1 = { filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }; + let data = { name: "name123", value: "123" }; + let header = { key1: value1, key2: value2 }; let uploadTask; - request.upload({ url: 'https://patch', files: [file1] }, (err, data) => { + request.upload({ url: 'https://patch', header: header, method: "POST", files: [file1], data: [data] }, (err, data) => { if (err) { console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); return; @@ -335,10 +339,10 @@ Removes this upload task. This API uses an asynchronous callback to return the r | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | url | string | Yes | Resource URL. | -| header | object | No | HTTP or HTTPS header added to an upload request. | -| method | string | No | Request methods available: **POST** and **PUT**. The default value is **POST**. | +| header | object | Yes | HTTP or HTTPS header added to an upload request. | +| method | string | Yes | Request methods available: **POST** and **PUT**. The default value is **POST**. | | files | Array<[File](#file)> | Yes | List of files to upload, which is submitted through **multipart/form-data**. | -| data | Array<[RequestData](#requestdata)> | No | Form data in the request body. | +| data | Array<[RequestData](#requestdata)> | Yes | Form data in the request body. | ## File @@ -349,7 +353,7 @@ Removes this upload task. This API uses an asynchronous callback to return the r | -------- | -------- | -------- | -------- | | filename | string | No | File name in the header when **multipart** is used. | | name | string | No | Name of a form item when **multipart** is used. The default value is **file**. | -| uri | string | Yes | Local path for storing files.
The **dataability** and **internal** protocol types are supported. However, the **internal** protocol type supports only temporary directories. The following is an example:
dataability:///com.domainname.dataability.persondata/person/10/file.txt
internal://cache/path/to/file.txt | +| uri | string | Yes | Local path for storing files.
The **dataability** and **internal** protocol types are supported. However, the **internal** protocol type supports only temporary directories. Below are examples:
dataability:///com.domainname.dataability.persondata/person/10/file.txt
internal://cache/path/to/file.txt | | type | string | No | Type of the file content. By default, the type is obtained based on the extension of the file name or URI. | diff --git a/en/application-dev/reference/apis/js-apis-resource-manager.md b/en/application-dev/reference/apis/js-apis-resource-manager.md index 2effb8b20a713c2c1f9a27baa8c12cabdcd37cda..335e31cdb21bacd975db26b726f503c0a44e431d 100644 --- a/en/application-dev/reference/apis/js-apis-resource-manager.md +++ b/en/application-dev/reference/apis/js-apis-resource-manager.md @@ -2,7 +2,7 @@ The resource management module provides APIs to obtain information about the current device configuration (including the language, region, screen direction, and MCC/MNC) and device capability (including the device type and resolution). -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE**
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -12,31 +12,41 @@ The resource management module provides APIs to obtain information about the cur import resourceManager from '@ohos.resourceManager'; ``` +## Usage + +Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its APIs without first importing the required bundle. This method, however, is not applicable to the FA model. + +``` +this.context.resourceManager; +``` + ## resourceManager.getResourceManager getResourceManager(callback: AsyncCallback<ResourceManager>): void -Obtains the **ResourceManager** object of this application. This API uses a callback to return the result. +Obtains the **ResourceManager** object of this application. This API uses an asynchronous callback to return the result. + +This API is used only in the FA model. **System capability**: SystemCapability.Global.ResourceManager **Parameters** | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------------------- | -| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Asynchronous callback used to return the **ResourceManager** object obtained.| +| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { if (error != null) { - console.log("error occurs" + error); + console.log("error is " + error); return; } mgr.getString(0x1000000, (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let str = value; } }); }); @@ -47,7 +57,9 @@ Obtains the **ResourceManager** object of this application. This API uses a call getResourceManager(bundleName: string, callback: AsyncCallback<ResourceManager>): void -Obtains the **ResourceManager** object of an application. This API uses an asynchronous callback to return the result. +Obtains the **ResourceManager** object of an application based on the specified bundle name. This API uses an asynchronous callback to return the result. + +This API is used only in the FA model. **System capability**: SystemCapability.Global.ResourceManager @@ -55,7 +67,7 @@ Obtains the **ResourceManager** object of an application. This API uses an async | Name | Type | Mandatory | Description | | ---------- | ---------------------------------------- | ---- | ----------------------------- | | bundleName | string | Yes | Bundle name of the target application. | -| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Asynchronous callback used to return the **ResourceManager** object obtained.| +| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Asynchronous callback used to return the result.| **Example** ``` @@ -70,25 +82,27 @@ getResourceManager(): Promise<ResourceManager> Obtains the **ResourceManager** object of this application. This API uses a promise to return the result. +This API is used only in the FA model. + **System capability**: SystemCapability.Global.ResourceManager **Return value** | Type | Description | | ---------------------------------------- | ----------------- | -| Promise<[ResourceManager](#resourcemanager)> | Promise used to return the **ResourceManager** object obtained.| +| Promise<[ResourceManager](#resourcemanager)> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager().then(mgr => { mgr.getString(0x1000000, (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let str = value; } }); }).catch(error => { - console.log(error); + console.log("error is " + error); }); ``` @@ -97,7 +111,9 @@ Obtains the **ResourceManager** object of this application. This API uses a prom getResourceManager(bundleName: string): Promise<ResourceManager> -Obtains the **ResourceManager** object of an application. This API uses a promise to return the result. +Obtains the **ResourceManager** object of an application based on the specified bundle name. This API uses a promise to return the result. + +This API is used only in the FA model. **System capability**: SystemCapability.Global.ResourceManager @@ -109,7 +125,7 @@ Obtains the **ResourceManager** object of an application. This API uses a promis **Return value** | Type | Description | | ---------------------------------------- | ------------------ | -| Promise<[ResourceManager](#resourcemanager)> | Promise used to return the **ResourceManager** object obtained.| +| Promise<[ResourceManager](#resourcemanager)> | Promise used to return the result.| **Example** ``` @@ -129,8 +145,8 @@ Enumerates the screen directions. | Name | Default Value | Description | | -------------------- | ---- | ---- | -| DIRECTION_VERTICAL | 0 | Portrait | -| DIRECTION_HORIZONTAL | 1 | Landscape | +| DIRECTION_VERTICAL | 0 | Portrait. | +| DIRECTION_HORIZONTAL | 1 | Landscape. | ## DeviceType @@ -141,12 +157,12 @@ Enumerates the device types. | Name | Default Value | Description | | -------------------- | ---- | ---- | -| DEVICE_TYPE_PHONE | 0x00 | Phone | -| DEVICE_TYPE_TABLET | 0x01 | Tablet | -| DEVICE_TYPE_CAR | 0x02 | Head unit | -| DEVICE_TYPE_PC | 0x03 | PC | -| DEVICE_TYPE_TV | 0x04 | TV | -| DEVICE_TYPE_WEARABLE | 0x06 | Wearable | +| DEVICE_TYPE_PHONE | 0x00 | Phone. | +| DEVICE_TYPE_TABLET | 0x01 | Tablet. | +| DEVICE_TYPE_CAR | 0x02 | Head unit. | +| DEVICE_TYPE_PC | 0x03 | PC. | +| DEVICE_TYPE_TV | 0x04 | TV. | +| DEVICE_TYPE_WEARABLE | 0x06 | Wearable. | ## ScreenDensity @@ -182,8 +198,8 @@ Defines the device configuration. ``` resourceManager.getResourceManager((error, mgr) => { mgr.getConfiguration((error, value) => { - console.log(value.direction); - console.log(value.locale); + let direction = value.direction; + let locale = value.locale; }); }); ``` @@ -205,8 +221,8 @@ Defines the device capability. ``` resourceManager.getResourceManager((error, mgr) => { mgr.getDeviceCapability((error, value) => { - console.log(value.screenDensity); - console.log(value.deviceType); + let screenDensity = value.screenDensity; + let deviceType = value.deviceType; }); }); ``` @@ -227,7 +243,7 @@ Defines the descriptor information of the raw file.
Defines the capability of accessing application resources. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE**
> - The methods involved in **ResourceManager** are applicable only to the TypeScript-based declarative development paradigm. > > - Resource files are defined in the **resources** directory of the project. You can obtain the resource ID using **$r(resource address).id**, for example, **$r('app.string.test').id**. @@ -245,16 +261,16 @@ Obtains the string corresponding to the specified resource ID. This API uses an | Name | Type | Mandatory | Description | | -------- | --------------------------- | ---- | --------------- | | resId | number | Yes | Resource ID. | -| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the obtained string.| +| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getString($r('app.string.test').id, (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let str = value; } }); }); @@ -277,15 +293,15 @@ Obtains the string corresponding to the specified resource ID. This API uses a p **Return value** | Type | Description | | --------------------- | ----------- | -| Promise<string> | Promise used to return the string obtained.| +| Promise<string> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getString($r('app.string.test').id).then(value => { - console.log(value); + let str = value; }).catch(error => { - console.log("getstring promise " + error); + console.log("getstring promise error is " + error); }); }); ``` @@ -295,7 +311,7 @@ Obtains the string corresponding to the specified resource ID. This API uses a p getStringArray(resId: number, callback: AsyncCallback<Array<string>>): void -Obtains the array of strings corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. +Obtains the string array corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -303,16 +319,16 @@ Obtains the array of strings corresponding to the specified resource ID. This AP | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------- | | resId | number | Yes | Resource ID. | -| callback | AsyncCallback<Array<string>> | Yes | Asynchronous callback used to return the obtained array of strings.| +| callback | AsyncCallback<Array<string>> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getStringArray($r('app.strarray.test').id, (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let strArray = value; } }); }); @@ -323,7 +339,7 @@ Obtains the array of strings corresponding to the specified resource ID. This AP getStringArray(resId: number): Promise<Array<string>> -Obtains the array of strings corresponding to the specified resource ID. This API uses a promise to return the result. +Obtains the string array corresponding to the specified resource ID. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -335,15 +351,15 @@ Obtains the array of strings corresponding to the specified resource ID. This AP **Return value** | Type | Description | | ---------------------------------- | ------------- | -| Promise<Array<string>> | Promise used to return the array of strings obtained.| +| Promise<Array<string>> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getStringArray($r('app.strarray.test').id).then(value => { - console.log(value); + let strArray = value; }).catch(error => { - console.log("getstring promise " + error); + console.log("getStringArray promise error is " + error); }); }); ``` @@ -361,16 +377,16 @@ Obtains the content of the media file corresponding to the specified resource ID | Name | Type | Mandatory | Description | | -------- | ------------------------------- | ---- | ------------------ | | resId | number | Yes | Resource ID. | -| callback | AsyncCallback<Uint8Array> | Yes | Asynchronous callback used to return the content of the media file obtained.| +| callback | AsyncCallback<Uint8Array> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getMedia($r('app.media.test').id, (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let media = value; } }); }); @@ -393,15 +409,15 @@ Obtains the content of the media file corresponding to the specified resource ID **Return value** | Type | Description | | ------------------------- | -------------- | -| Promise<Uint8Array> | Promise used to return the content of the media file obtained.| +| Promise<Uint8Array> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getMedia($r('app.media.test').id).then(value => { - console.log(value); + let media = value; }).catch(error => { - console.log("getstring promise " + error); + console.log("getMedia promise error is " + error); }); }); ``` @@ -419,16 +435,16 @@ Obtains the Base64 code of the image corresponding to the specified resource ID. | Name | Type | Mandatory | Description | | -------- | --------------------------- | ---- | ------------------------ | | resId | number | Yes | Resource ID. | -| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the Base64 code of the image obtained.| +| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getMediaBase64($r('app.media.test').id, (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let media = value; } }); }); @@ -451,15 +467,15 @@ Obtains the Base64 code of the image corresponding to the specified resource ID. **Return value** | Type | Description | | --------------------- | -------------------- | -| Promise<string> | Promise used to return the Base64 code of the image obtained.| +| Promise<string> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getMediaBase64($r('app.media.test').id).then(value => { - console.log(value); + let media = value; }).catch(error => { - console.log("getstring promise " + error); + console.log("getMediaBase64 promise error is " + error); }); }); ``` @@ -476,16 +492,17 @@ Obtains the device configuration. This API uses an asynchronous callback to retu **Parameters** | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ------------------------- | -| callback | AsyncCallback<[Configuration](#configuration)> | Yes | Asynchronous callback used to return the obtained device configuration.| +| callback | AsyncCallback<[Configuration](#configuration)> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getConfiguration((error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let direction = value.direction; + let locale = value.locale; } }); }); @@ -503,15 +520,16 @@ Obtains the device configuration. This API uses a promise to return the result. **Return value** | Type | Description | | ---------------------------------------- | ---------------- | -| Promise<[Configuration](#configuration)> | Promise used to return the device configuration.| +| Promise<[Configuration](#configuration)> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getConfiguration().then(value => { - console.log(value); + let direction = value.direction; + let locale = value.locale; }).catch(error => { - console.log("getstring promise " + error); + console.log("getConfiguration promise error is " + error); }); }); ``` @@ -528,16 +546,17 @@ Obtains the device capability. This API uses an asynchronous callback to return **Parameters** | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------- | -| callback | AsyncCallback<[DeviceCapability](#devicecapability)> | Yes | Asynchronous callback used to return the obtained device capability.| +| callback | AsyncCallback<[DeviceCapability](#devicecapability)> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getDeviceCapability((error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let screenDensity = value.screenDensity; + let deviceType = value.deviceType; } }); }); @@ -555,15 +574,16 @@ Obtains the device capability. This API uses a promise to return the result. **Return value** | Type | Description | | ---------------------------------------- | ------------------- | -| Promise<[DeviceCapability](#devicecapability)> | Promise used to return the obtained device capability.| +| Promise<[DeviceCapability](#devicecapability)> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getDeviceCapability().then(value => { - console.log(value); + let screenDensity = value.screenDensity; + let deviceType = value.deviceType; }).catch(error => { - console.log("getstring promise " + error); + console.log("getDeviceCapability promise error is " + error); }); }); ``` @@ -582,16 +602,16 @@ Obtains the specified number of singular-plural strings corresponding to the spe | -------- | --------------------------- | ---- | ------------------------------- | | resId | number | Yes | Resource ID. | | num | number | Yes | Number that determines the plural or singular form. | -| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the singular-plural string obtained.| +| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getPluralString($r("app.plural.test").id, 1, (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let str = value; } }); }); @@ -615,15 +635,15 @@ Obtains the specified number of singular-plural strings corresponding to the spe **Return value** | Type | Description | | --------------------- | ------------------------- | -| Promise<string> | Promise used to return the singular-plural string obtained.| +| Promise<string> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getPluralString($r("app.plural.test").id, 1).then(value => { - console.log(value); + let str = value; }).catch(error => { - console.log("getstring promise " + error); + console.log("getPluralString promise error is " + error); }); }); ``` @@ -632,7 +652,7 @@ Obtains the specified number of singular-plural strings corresponding to the spe getRawFile(path: string, callback: AsyncCallback<Uint8Array>): void -Obtains the content of rawfile in the specified path. This API uses an asynchronous callback to return the result. +Obtains the content of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -640,16 +660,16 @@ Obtains the content of rawfile in the specified path. This API uses an asynchron | Name | Type | Mandatory | Description | | -------- | ------------------------------- | ---- | ----------------------- | | path | string | Yes | Path of the raw file. | -| callback | AsyncCallback<Uint8Array> | Yes | Asynchronous callback used to return the raw file content, in byte arrays.| +| callback | AsyncCallback<Uint8Array> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getRawFile("test.xml", (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let rawFile = value; } }); }); @@ -659,7 +679,7 @@ Obtains the content of rawfile in the specified path. This API uses an asynchron getRawFile(path: string): Promise<Uint8Array> -Obtains the content of the raw file in the specified path. This API uses a promise to return the result. +Obtains the content of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -671,15 +691,15 @@ Obtains the content of the raw file in the specified path. This API uses a promi **Return value** | Type | Description | | ------------------------- | ----------- | -| Promise<Uint8Array> | Promise used to return the raw file content, in byte arrays.| +| Promise<Uint8Array> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getRawFile("test.xml").then(value => { - console.log(value); + let rawFile = value; }).catch(error => { - console.log("getrawfile promise " + error); + console.log("getRawFile promise error is " + error); }); }); ``` @@ -688,7 +708,7 @@ Obtains the content of the raw file in the specified path. This API uses a promi getRawFileDescriptor(path: string, callback: AsyncCallback<RawFileDescriptor>): void -Obtains the descriptor of the raw file in the specified path. This API uses an asynchronous callback to return the result. +Obtains the descriptor of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -696,14 +716,14 @@ Obtains the descriptor of the raw file in the specified path. This API uses an a | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | -------------------------------- | | path | string | Yes | Path of the raw file. | -| callback | AsyncCallback<[RawFileDescriptor](#rawfiledescriptor8)> | Yes | Asynchronous callback used to return the raw file descriptor.| +| callback | AsyncCallback<[RawFileDescriptor](#rawfiledescriptor8)> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getRawFileDescriptor("test.xml", (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { let fd = value.fd; let offset = value.offset; @@ -717,7 +737,7 @@ Obtains the descriptor of the raw file in the specified path. This API uses an a getRawFileDescriptor(path: string): Promise<RawFileDescriptor> -Obtains the descriptor of the raw file in the specified path. This API uses a promise to return the result. +Obtains the descriptor of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -729,7 +749,7 @@ Obtains the descriptor of the raw file in the specified path. This API uses a pr **Return value** | Type | Description | | ---------------------------------------- | ------------------- | -| Promise<[RawFileDescriptor](#rawfiledescriptor8)> | Promise used to return the raw file descriptor.| +| Promise<[RawFileDescriptor](#rawfiledescriptor8)> | Promise used to return the result.| **Example** ``` @@ -739,7 +759,7 @@ Obtains the descriptor of the raw file in the specified path. This API uses a pr let offset = value.offset; let length = value.length; }).catch(error => { - console.log("getRawFileDescriptor promise " + error); + console.log("getRawFileDescriptor promise error is " + error); }); }); ``` @@ -748,7 +768,7 @@ Obtains the descriptor of the raw file in the specified path. This API uses a pr closeRawFileDescriptor(path: string, callback: AsyncCallback<void>): void -Closes the descriptor of the raw file in the specified path. This API uses an asynchronous callback to return the result. +Closes the descriptor of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -763,7 +783,7 @@ Closes the descriptor of the raw file in the specified path. This API uses an as resourceManager.getResourceManager((error, mgr) => { mgr.closeRawFileDescriptor("test.xml", (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } }); }); @@ -773,7 +793,7 @@ Closes the descriptor of the raw file in the specified path. This API uses an as closeRawFileDescriptor(path: string): Promise<void> -Closes the descriptor of the raw file in the specified path. This API uses a promise to return the result. +Closes the descriptor of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -791,9 +811,9 @@ Closes the descriptor of the raw file in the specified path. This API uses a pro ``` resourceManager.getResourceManager((error, mgr) => { mgr.closeRawFileDescriptor("test.xml").then(value => { - console.log(value); + let result = value; }).catch(error => { - console.log("closeRawFileDescriptor promise " + error); + console.log("closeRawFileDescriptor promise error is " + error); }); }); ``` @@ -809,10 +829,408 @@ Releases the created **resourceManager**. **Example** ``` resourceManager.getResourceManager((error, mgr) => { - mgr.release((error, value) => { - if (error != null) { - console.log(value); - } - }); + mgr.release(); + }); + ``` + +### getStringByName9+ + +getStringByName(resName: string, callback: AsyncCallback<string>): void + +Obtains the string corresponding to the specified resource name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | --------------- | +| resName | string | Yes | Resource name. | +| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.| + +**Example** + ``` + resourceManager.getStringByName("test", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let string = value; + } + }); + ``` + +### getStringByName9+ + +getStringByName(resName: string): Promise<string> + +Obtains the string corresponding to the specified resource name. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---- | +| resName | string | Yes | Resource name.| + +**Return value** +| Type | Description | +| --------------------- | ----------- | +| Promise<string> | String corresponding to the resource name.| + +**Example** + ``` + resourceManager.getStringByName("test").then(value => { + let string = value; + }).catch(error => { + console.log("getStringByName promise error is " + error); + }); + ``` + +### getStringArrayByName9+ + +getStringArrayByName(resName: string, callback: AsyncCallback<Array<string>>): void + +Obtains the string array corresponding to the specified resource name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------- | +| resName | string | Yes | Resource name. | +| callback | AsyncCallback<Array<string>> | Yes | Asynchronous callback used to return the result.| + +**Example** + ``` + resourceManager.getStringArrayByName("test", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let strArray = value; + } + }); + ``` + +### getStringArrayByName9+ + +getStringArrayByName(resName: string): Promise<Array<string>> + +Obtains the string array corresponding to the specified resource name. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ----- | +| resName | string | Yes | Resource name.| + +**Return value** +| Type | Description | +| ---------------------------------- | ------------- | +| Promise<Array<string>> | Promise used to return the result.| + +**Example** + ``` + resourceManager.getStringArrayByName("test").then(value => { + let strArray = value; + }).catch(error => { + console.log("getStringArrayByName promise error is " + error); + }); + ``` + +### getMediaByName9+ + +getMediaByName(resName: string, callback: AsyncCallback<Uint8Array>): void + +Obtains the content of the media file corresponding to the specified resource name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ------------------ | +| resName | string | Yes | Resource name. | +| callback | AsyncCallback<Uint8Array> | Yes | Asynchronous callback used to return the result.| + +**Example** + ``` + resourceManager.getMediaByName("test", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let media = value; + } + }); + ``` + +### getMediaByName9+ + +getMediaByName(resName: string): Promise<Uint8Array> + +Obtains the content of the media file corresponding to the specified resource name. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resName | string | Yes | Resource name.| + +**Return value** +| Type | Description | +| ------------------------- | -------------- | +| Promise<Uint8Array> | Promise used to return the result.| + +**Example** + ``` + resourceManager.getMediaByName("test").then(value => { + let media = value; + }).catch(error => { + console.log("getMediaByName promise error is " + error); + }); + ``` + +### getMediaBase64ByName9+ + +getMediaBase64ByName(resName: string, callback: AsyncCallback<string>): void + +Obtains the Base64 code of the image corresponding to the specified resource name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------ | +| resName | string | Yes | Resource name. | +| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.| + +**Example** + ``` + resourceManager.getMediaBase64ByName("test", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let media = value; + } }); ``` + +### getMediaBase64ByName9+ + +getMediaBase64ByName(resName: string): Promise<string> + +Obtains the Base64 code of the image corresponding to the specified resource name. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ----- | +| resName | string | Yes | Resource name.| + +**Return value** +| Type | Description | +| --------------------- | -------------------- | +| Promise<string> | Promise used to return the result.| + +**Example** + ``` + resourceManager.getMediaByName("test").then(value => { + let media = value; + }).catch(error => { + console.log("getMediaBase64ByName promise error is " + error); + }); + ``` + +### getPluralStringByName9+ + +getPluralStringByName(resName: string, num: number, callback: AsyncCallback<string>): void + +Obtains the plural string corresponding to the specified resource name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------------- | +| resName | string | Yes | Resource name. | +| num | number | Yes | Number that determines the plural or singular form. | +| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.| + +**Example** + ``` + resourceManager.getPluralStringByName("test", 1, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let str = value; + } + }); + ``` + +### getPluralStringByName9+ + +getPluralStringByName(resName: string, num: number): Promise<string> + +Obtains the plural string corresponding to the specified resource name. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ----- | +| resName | string | Yes | Resource name.| +| num | number | Yes | Number that determines the plural or singular form. | + +**Return value** +| Type | Description | +| --------------------- | ------------------------- | +| Promise<string> | Promise used to return the result.| + +**Example** + ``` + resourceManager.getPluralStringByName("test", 1).then(value => { + let str = value; + }).catch(error => { + console.log("getPluralStringByName promise error is " + error); + }); + ``` + +### getStringSync9+ + +getStringSync(resId: number): string + +Obtains the string corresponding to the specified resource ID. This API returns the result synchronously. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| + +**Return value** +| Type | Description | +| --------------------- | ----------- | +| string | String corresponding to the specified resource ID.| + +**Example** + ``` + resourceManager.getStringSync($r('app.string.test').id); + ``` + +### getStringByNameSync9+ + +getStringByNameSync(resName: string): string + +Obtains the string corresponding to the specified resource name. This API returns the result synchronously. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resName | string | Yes | Resource name.| + +**Return value** +| Type | Description | +| --------------------- | ----------- | +| string | String corresponding to the resource name.| + +**Example** + ``` + resourceManager.getStringByNameSync("test"); + ``` + + ### getBoolean9+ + +getBoolean(resId: number): boolean + +Obtains the Boolean result corresponding to the specified resource ID. This API returns the result synchronously. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| + +**Return value** +| Type | Description | +| --------------------- | ----------- | +| boolean | Boolean result corresponding to the specified resource ID.| + +**Example** + ``` + resourceManager.getBoolean($r('app.boolean.boolean_test').id); + ``` + +### getBooleanByName9+ + +getBooleanByName(resName: string): boolean + +Obtains the Boolean result corresponding to the specified resource name. This API returns the result synchronously. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ----- | +| resName | string | Yes | Resource name.| + +**Return value** +| Type | Description | +| --------------------- | ----------- | +| boolean | Boolean result corresponding to the specified resource name.| + +**Example** + ``` + resourceManager.getBooleanByName("boolean_test"); + ``` + + ### getNumber9+ + +getNumber(resId: number): number + +Obtains the integer or float value corresponding to the specified resource ID. This API returns the result synchronously. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| + +**Return value** +| Type | Description | +| --------------------- | ----------- | +| number | Integer or float value corresponding to the specified resource ID.| + +**Example** + ``` + resourceManager.getNumber($r('app.integer.integer_test').id); + resourceManager.getNumber($r('app.float.float_test').id); + ``` + +### getNumberByName9+ + +getNumberByName(resName: string): number + +Obtains the integer or float value corresponding to the specified resource name. This API returns the result synchronously. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resName | string | Yes | Resource name.| + +**Return value** +| Type | Description | +| --------------------- | ----------- | +| number | Integer or float value corresponding to the specified resource name.| + +**Example** + ``` + resourceManager.getNumberByName("integer_test"); + resourceManager.getNumberByName("float_test"); + ``` diff --git a/en/application-dev/reference/apis/js-apis-screenshot.md b/en/application-dev/reference/apis/js-apis-screenshot.md index 690a77e0d9563a066d7f1da9352aca640b6fbea3..573909893ea8c182e91b739d753a2f36bf244d16 100644 --- a/en/application-dev/reference/apis/js-apis-screenshot.md +++ b/en/application-dev/reference/apis/js-apis-screenshot.md @@ -1,6 +1,7 @@ # Screenshot -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -56,14 +57,14 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a cal **System capability**: SystemCapability.WindowManager.WindowManager.Core -**Required permissions**: ohos.permission.CAPTURE_SCREEN +**Required permissions**: ohos.permission.CAPTURE_SCREEN (available only to system applications) **Parameters** - | Name | Type | Mandatory| Description | - | -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | - | options | [ScreenshotOptions](#screenshotoptions) | No | Screenshot options, which consist of **screenRect**, **imageSize**, and **rotation**. You need to set these parameters.| - | callback | AsyncCallback<image.PixelMap> | Yes | Callback used to return a **PixelMap** object. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | +| options | [ScreenshotOptions](#screenshotoptions) | No | Screenshot options, which consist of **screenRect**, **imageSize**, and **rotation**. You need to set these parameters.| +| callback | AsyncCallback<image.PixelMap> | Yes | Callback used to return a **PixelMap** object. | **Example** @@ -96,7 +97,7 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a pro **System capability**: SystemCapability.WindowManager.WindowManager.Core -**Required permissions**: ohos.permission.CAPTURE_SCREEN +**Required permissions**: ohos.permission.CAPTURE_SCREEN (available only to system applications) **Parameters** @@ -106,9 +107,9 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a pro **Return value** - | Type | Description | - | ----------------------------- | ----------------------------------------------- | - | Promise<image.PixelMap> | Promise used to return an **image.PixelMap** object.| +| Type | Description | +| ----------------------------- | ----------------------------------------------- | +| Promise<image.PixelMap> | Promise used to return an **image.PixelMap** object.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-sensor.md b/en/application-dev/reference/apis/js-apis-sensor.md index c04e503414020d5c0b6107ef2313df58d91b52f5..aab544f7f78bd2b755ab24443aa1d0acd5d683c1 100644 --- a/en/application-dev/reference/apis/js-apis-sensor.md +++ b/en/application-dev/reference/apis/js-apis-sensor.md @@ -1,17 +1,19 @@ # Sensor -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```js import sensor from '@ohos.sensor'; ``` +## sensor.on -## sensor.on(SensorType.SENSOR_TYPE_ID_ACCELEROMETER) +### ACCELEROMETER on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<AccelerometerResponse>,options?: Options): void @@ -30,7 +32,7 @@ Subscribes to data changes of the acceleration sensor. If this API is called mul | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -40,8 +42,7 @@ Subscribes to data changes of the acceleration sensor. If this API is called mul ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION) +### LINEAR_ACCELERATION on(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>, options?: Options): void @@ -59,7 +60,7 @@ Subscribes to data changes of the linear acceleration sensor. If this API is cal | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -69,8 +70,7 @@ Subscribes to data changes of the linear acceleration sensor. If this API is cal ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED) +### ACCELEROMETER_UNCALIBRATED on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback<AccelerometerUncalibratedResponse>, options?: Options): void @@ -88,7 +88,7 @@ Subscribes to data changes of the uncalibrated acceleration sensor. If this API | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -101,8 +101,7 @@ Subscribes to data changes of the uncalibrated acceleration sensor. If this API ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_GRAVITY) +### GRAVITY on(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityResponse>,options?: Options): void @@ -118,7 +117,7 @@ Subscribes to data changes of the gravity sensor. If this API is called multiple | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -128,8 +127,7 @@ Subscribes to data changes of the gravity sensor. If this API is called multiple ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_GYROSCOPE) +### GYROSCOPE on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeResponse>, options?: Options): void @@ -147,7 +145,7 @@ Subscribes to data changes of the gyroscope sensor. If this API is called multip | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -157,8 +155,7 @@ Subscribes to data changes of the gyroscope sensor. If this API is called multip ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED) +### GYROSCOPE_UNCALIBRATED on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:Callback<GyroscopeUncalibratedResponse>, options?: Options): void @@ -176,7 +173,7 @@ Subscribes to data changes of the uncalibrated gyroscope sensor. If this API is | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -189,8 +186,7 @@ Subscribes to data changes of the uncalibrated gyroscope sensor. If this API is ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION) +### SIGNIFICANT_MOTION on(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback: Callback<SignificantMotionResponse>, options?: Options): void @@ -206,7 +202,7 @@ Subscribes to data changes of the significant motion sensor. If this API is call | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,function(data){ console.info('Scalar data: ' + data.scalar); }, @@ -214,8 +210,7 @@ Subscribes to data changes of the significant motion sensor. If this API is call ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION) +### PEDOMETER_DETECTION on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback: Callback<PedometerDetectionResponse>, options?: Options): void @@ -233,7 +228,7 @@ Subscribes to data changes of the pedometer detection sensor. If this API is cal | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,function(data){ console.info('Scalar data: ' + data.scalar); }, @@ -241,8 +236,7 @@ Subscribes to data changes of the pedometer detection sensor. If this API is cal ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_PEDOMETER) +### PEDOMETER on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerResponse>, options?: Options): void @@ -260,7 +254,7 @@ Subscribes to data changes of the pedometer sensor. If this API is called multip | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER,function(data){ console.info('Steps: ' + data.steps); }, @@ -268,8 +262,7 @@ Subscribes to data changes of the pedometer sensor. If this API is called multip ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE) +### AMBIENT_TEMPERATURE on(type:SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:Callback<AmbientTemperatureResponse>, options?: Options): void @@ -285,7 +278,7 @@ Subscribes to data changes of the ambient temperature sensor. If this API is cal | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,function(data){ console.info('Temperature: ' + data.temperature); }, @@ -293,8 +286,7 @@ Subscribes to data changes of the ambient temperature sensor. If this API is cal ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD) +### MAGNETIC_FIELD on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>,options?: Options): void @@ -310,7 +302,7 @@ Subscribes to data changes of the magnetic field sensor. If this API is called m | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -320,8 +312,7 @@ Subscribes to data changes of the magnetic field sensor. If this API is called m ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED) +### MAGNETIC_FIELD_UNCALIBRATED on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callback<MagneticFieldUncalibratedResponse>, options?: Options): void @@ -337,7 +328,7 @@ Subscribes to data changes of the uncalibrated magnetic field sensor. If this AP | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -350,8 +341,7 @@ Subscribes to data changes of the uncalibrated magnetic field sensor. If this AP ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_PROXIMITY) +### PROXIMITY on(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityResponse>,options?: Options): void @@ -367,7 +357,7 @@ Subscribes to data changes of the proximity sensor. If this API is called multip | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY,function(data){ console.info('Distance: ' + data.distance); }, @@ -375,8 +365,7 @@ Subscribes to data changes of the proximity sensor. If this API is called multip ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_HUMIDITY) +### HUMIDITY on(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityResponse>,options?: Options): void @@ -392,7 +381,7 @@ Subscribes to data changes of the humidity sensor. If this API is called multipl | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY,function(data){ console.info('Humidity: ' + data.humidity); }, @@ -400,8 +389,7 @@ Subscribes to data changes of the humidity sensor. If this API is called multipl ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_BAROMETER) +### BAROMETER on(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerResponse>,options?: Options): void @@ -417,7 +405,7 @@ Subscribes to data changes of the barometer sensor. If this API is called multip | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER,function(data){ console.info('Atmospheric pressure: ' + data.pressure); }, @@ -425,8 +413,7 @@ Subscribes to data changes of the barometer sensor. If this API is called multip ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_HALL) +### HALL on(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse>, options?: Options): void @@ -442,7 +429,7 @@ Subscribes to data changes of the Hall effect sensor. If this API is called mult | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HALL,function(data){ console.info('Status: ' + data.status); }, @@ -450,8 +437,7 @@ Subscribes to data changes of the Hall effect sensor. If this API is called mult ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT) +### AMBIENT_LIGHT on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightResponse>, options?: Options): void @@ -467,7 +453,7 @@ Subscribes to data changes of the ambient light sensor. If this API is called mu | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT,function(data){ console.info(' Illumination: ' + data.intensity); }, @@ -475,8 +461,7 @@ Subscribes to data changes of the ambient light sensor. If this API is called mu ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_ORIENTATION) +### ORIENTATION on(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<OrientationResponse>, options?: Options): void @@ -492,7 +477,7 @@ Subscribes to data changes of the orientation sensor. If this API is called mult | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION,function(data){ console.info('The device rotates at an angle around the X axis: ' + data.beta); console.info('The device rotates at an angle around the Y axis: ' + data.gamma); @@ -502,7 +487,7 @@ Subscribes to data changes of the orientation sensor. If this API is called mult ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_HEART_RATE) +### HEART_RATE on(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>, options?: Options): void @@ -521,7 +506,7 @@ Subscribes to only one data change of the heart rate sensor. **Example** -``` +```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE,function(data){ console.info("Heart rate: " + data.heartRate); }, @@ -529,7 +514,7 @@ sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE,function(data){ ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR) +### ROTATION_VECTOR on(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback: Callback<RotationVectorResponse>,options?: Options): void @@ -545,7 +530,7 @@ Subscribes to data changes of the rotation vector sensor. If this API is called | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -556,8 +541,7 @@ Subscribes to data changes of the rotation vector sensor. If this API is called ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_WEAR_DETECTION) +### WEAR_DETECTION on(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDetectionResponse>,options?: Options): void @@ -573,7 +557,7 @@ Subscribes to data changes of the wear detection sensor. If this API is called m | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION,function(data){ console.info('Wear status: ' + data.value); }, @@ -581,8 +565,9 @@ Subscribes to data changes of the wear detection sensor. If this API is called m ); ``` +## sensor.once -## sensor.once(SensorType.SENSOR_TYPE_ID_ACCELEROMETER) +### ACCELEROMETER once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<AccelerometerResponse>): void @@ -599,7 +584,7 @@ Subscribes to only one data change of the acceleration sensor. | callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | One-shot callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -608,8 +593,7 @@ Subscribes to only one data change of the acceleration sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION) +### LINEAR_ACCELERATION once(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>): void @@ -626,7 +610,7 @@ Subscribes to only one data change of the linear acceleration sensor. | callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -635,8 +619,7 @@ Subscribes to only one data change of the linear acceleration sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED) +### ACCELEROMETER_UNCALIBRATED once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback<AccelerometerUncalibratedResponse>): void @@ -665,8 +648,7 @@ Subscribes to only one data change of the uncalibrated acceleration sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_GRAVITY) +### GRAVITY once(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityResponse>): void @@ -681,7 +663,7 @@ Subscribes to only one data change of the gravity sensor. | callback | Callback<[GravityResponse](#gravityresponse)> | Yes | One-shot callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -690,8 +672,7 @@ Subscribes to only one data change of the gravity sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_GYROSCOPE) +### GYROSCOPE once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeResponse>): void @@ -708,7 +689,7 @@ Subscribes to only one data change of the gyroscope sensor. | callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | One-shot callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -717,8 +698,7 @@ Subscribes to only one data change of the gyroscope sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED) +### GYROSCOPE_UNCALIBRATED once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback: Callback<GyroscopeUncalibratedResponse>): void @@ -735,7 +715,7 @@ Subscribes to only one data change of the uncalibrated gyroscope sensor. | callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -747,8 +727,7 @@ Subscribes to only one data change of the uncalibrated gyroscope sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION) +### SIGNIFICANT_MOTION once(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,callback: Callback<SignificantMotionResponse>): void @@ -763,15 +742,14 @@ Subscribes to only one data change of the significant motion sensor. | callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | One-shot callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, function(data) { console.info('Scalar data: ' + data.scalar); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION) +### PEDOMETER_DETECTION once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,callback: Callback<PedometerDetectionResponse>): void @@ -788,15 +766,14 @@ Subscribes to only one data change of the pedometer detection sensor. | callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | One-shot callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, function(data) { console.info('Scalar data: ' + data.scalar); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_PEDOMETER) +### PEDOMETER once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerResponse>): void @@ -813,15 +790,14 @@ Subscribes to only one data change of the pedometer sensor. | callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | One-shot callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, function(data) { console.info('Steps: ' + data.steps); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE) +### AMBIENT_TEMPERATURE once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback: Callback<AmbientTemperatureResponse>): void @@ -836,15 +812,14 @@ Subscribes to only one data change of the ambient temperature sensor. | callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | One-shot callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, function(data) { console.info('Temperature: ' + data.temperature); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD) +### MAGNETIC_FIELD once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>): void @@ -859,7 +834,7 @@ Subscribes to only one data change of the magnetic field sensor. | callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | One-shot callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -868,8 +843,7 @@ Subscribes to only one data change of the magnetic field sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED) +### MAGNETIC_FIELD_UNCALIBRATED once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callback<MagneticFieldUncalibratedResponse>): void @@ -884,7 +858,7 @@ Subscribes to only one data change of the uncalibrated magnetic field sensor. | callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -896,8 +870,7 @@ Subscribes to only one data change of the uncalibrated magnetic field sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_PROXIMITY) +### PROXIMITY once(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityResponse>): void @@ -912,7 +885,7 @@ Subscribes to only one data change of the proximity sensor. | callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | One-shot callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, function(error, data) { if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); @@ -923,8 +896,7 @@ Subscribes to only one data change of the proximity sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_HUMIDITY) +### HUMIDITY once(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityResponse>): void @@ -939,15 +911,14 @@ Subscribes to only one data change of the humidity sensor. | callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | One-shot callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, function(data) { console.info('Humidity: ' + data.humidity); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_BAROMETER) +### BAROMETER once(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerResponse>): void @@ -962,15 +933,14 @@ Subscribes to only one data change of the barometer sensor. | callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | One-shot callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function(data) { console.info('Atmospheric pressure: ' + data.pressure); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_HALL) +### HALL once(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse>): void @@ -985,15 +955,14 @@ Subscribes to only one data change of the Hall effect sensor. | callback | Callback<[HallResponse](#hallresponse)> | Yes | One-shot callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HALL, function(data) { console.info('Status: ' + data.status); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT) +### AMBIENT_LIGHT once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightResponse>): void @@ -1008,15 +977,14 @@ Subscribes to only one data change of the ambient light sensor. | callback | Callback<[LightResponse](#lightresponse)> | Yes | One-shot callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, function(data) { console.info(' Illumination: ' + data.intensity); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_ORIENTATION) +### ORIENTATION once(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<OrientationResponse>): void @@ -1031,7 +999,7 @@ Subscribes to only one data change of the orientation sensor. | callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | One-shot callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, function(data) { console.info('The device rotates at an angle around the X axis: ' + data.beta); console.info('The device rotates at an angle around the Y axis: ' + data.gamma); @@ -1040,8 +1008,7 @@ Subscribes to only one data change of the orientation sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR) +### ROTATION_VECTOR once(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback: Callback<RotationVectorResponse>): void @@ -1056,7 +1023,7 @@ Subscribes to only one data change of the rotation vector sensor. | callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | One-shot callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1066,8 +1033,7 @@ Subscribes to only one data change of the rotation vector sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_HEART_RATE) +### HEART_RATE once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>): void @@ -1084,15 +1050,14 @@ Subscribes to only one data change of the heart rate sensor. | callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE, function(data) { console.info("Heart rate: " + data.heartRate); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_WEAR_DETECTION) +### WEAR_DETECTION once(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDetectionResponse>): void @@ -1107,14 +1072,16 @@ Subscribes to only one data change of the wear detection sensor. | callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | One-shot callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, function(data) { console.info("Wear status: "+ data.value); } ); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_ACCELEROMETER) +## sensor.off + +### ACCELEROMETER off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback?: Callback<AccelerometerResponse>): void @@ -1133,7 +1100,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('x-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1142,7 +1109,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED) +### ACCELEROMETER_UNCALIBRATED off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback?: Callback<AccelerometerUncalibratedResponse>): void @@ -1161,7 +1128,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1173,7 +1140,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT) +### AMBIENT_LIGHT off(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback?: Callback<LightResponse>): void @@ -1190,14 +1157,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info(' Illumination: ' + data.intensity); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE) +### AMBIENT_TEMPERATURE off(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback?: Callback<AmbientTemperatureResponse>): void @@ -1214,14 +1181,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('Temperature: ' + data.temperature); } sensor.off( sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE) +### AMBIENT_TEMPERATURE off(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback?: Callback<BarometerResponse>): void @@ -1238,14 +1205,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('Atmospheric pressure: ' + data.pressure); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_GRAVITY) +### GRAVITY off(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback?: Callback<GravityResponse>): void @@ -1262,7 +1229,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1271,7 +1238,7 @@ function callback(data) { sensor.off( sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_GYROSCOPE) +### GYROSCOPE off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback?: Callback<GyroscopeResponse>): void @@ -1290,7 +1257,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1299,7 +1266,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED) +### GYROSCOPE_UNCALIBRATED off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback?: Callback<GyroscopeUncalibratedResponse>): void @@ -1318,7 +1285,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1327,7 +1294,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_HALL) +### HALL off(type: SensorType.SENSOR_TYPE_ID_HALL, callback?: Callback<HallResponse>): void @@ -1344,14 +1311,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('Status: ' + data.status); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HALL, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_HEART_RATE) +### HEART_RATE off(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback?: Callback<HeartRateResponse>): void @@ -1370,14 +1337,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info("Heart rate: " + data.heartRate); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_HUMIDITY) +### HUMIDITY off(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback?: Callback<HumidityResponse>): void @@ -1396,14 +1363,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('Humidity: ' + data.humidity); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION) +### LINEAR_ACCELERATION off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback?: Callback<LinearAccelerometerResponse>): void @@ -1422,7 +1389,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1431,7 +1398,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD) +### MAGNETIC_FIELD off(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback?: Callback<MagneticFieldResponse>): void @@ -1450,7 +1417,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1459,7 +1426,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED) +### MAGNETIC_FIELD_UNCALIBRATED off(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callback?: Callback<MagneticFieldUncalibratedResponse>): void @@ -1476,7 +1443,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1488,7 +1455,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_ORIENTATION) +### ORIENTATION off(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback?: Callback<OrientationResponse>): void @@ -1505,7 +1472,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('The device rotates at an angle around the X axis: ' + data.beta); console.info('The device rotates at an angle around the Y axis: ' + data.gamma); @@ -1514,7 +1481,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_PEDOMETER) +### PEDOMETER off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback?: Callback<PedometerResponse>): void @@ -1529,16 +1496,16 @@ Unsubscribes from sensor data changes. | type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PEDOMETER**. | | callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| -**Return value** +**Example** -``` +```js function callback(data) { console.info('Steps: ' + data.steps); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION) +### PEDOMETER_DETECTION off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback?: Callback<PedometerDetectionResponse>): void @@ -1557,14 +1524,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('Scalar data: ' + data.scalar); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_PROXIMITY) +### PROXIMITY off(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback?: Callback<ProximityResponse>): void @@ -1581,14 +1548,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('Distance: ' + data.distance); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR) +### ROTATION_VECTOR off(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback?: Callback<RotationVectorResponse>): void @@ -1605,7 +1572,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1615,7 +1582,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION) +### SIGNIFICANT_MOTION off(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback?: Callback<SignificantMotionResponse>): void @@ -1632,14 +1599,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('Scalar data: ' + data.scalar); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_WEAR_DETECTION) +### WEAR_DETECTION off(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback?: Callback<WearDetectionResponse>): void @@ -1656,7 +1623,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function accCallback(data) { console.info('Wear status: ' + data.value); } @@ -1681,13 +1648,13 @@ Rotates a rotation vector so that it can represent the coordinate system in diff **Example** -``` -sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {'axisX':2, 'axisY':3}, function(err, data) { +```js +sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}, function(err, data) { if (err) { console.error("Operation failed. Error code: " + err.code + ", message: " + err.message); return; } - console.info("Operation successed. Data obtained: " + data.x); + console.info("Operation successed. Data obtained: " + data); for (var i=0; i < data.length; i++) { console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); } @@ -1716,8 +1683,8 @@ Rotates a rotation vector so that it can represent the coordinate system in diff **Example** -``` -const promise = sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {'axisX':2, 'axisY':3}); +```js +const promise = sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}); promise.then((data) => { console.info("Operation successed."); for (var i=0; i < data.length; i++) { @@ -1744,8 +1711,8 @@ Obtains the geomagnetic field of a geographic location. This API uses a callback | callback | AsyncCallback<[GeomagneticResponse](#geomagneticresponse)> | Yes | Callback used to return the geomagnetic field. | **Example** -``` -sensor.getGeomagneticField([80, 0, 0], 1580486400000, function(err, data) { +```js +sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000, function(err, data) { if (err) { console.error('Operation failed. Error code: ' + err.code + '; message: ' + err.message); return; @@ -1772,11 +1739,11 @@ Obtains the geomagnetic field of a geographic location. This API uses a promise **Return value** | Type | Description | | ---------------------------------------- | ------- | -| Promise<[GeomagneticResponse](#geomagneticresponse)> | Promise used to return the geomagnetic field.| +| Promise<[GeomagneticResponse](#geomagneticresponse)> | Promise used to return the geomagnetic field. | -**Return value** - ``` - const promise = sensor.getGeomagneticField([80, 0, 0], 1580486400000); +**Example** + ```js + const promise = sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000); promise.then((data) => { console.info('sensor_getGeomagneticField_promise x: ' + data.x + ',y: ' + data.y + ',z: ' + data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + @@ -1802,9 +1769,9 @@ Obtains the altitude at which the device is located based on the sea-level atmos | currentPressure | number | Yes | Atmospheric pressure at the altitude where the device is located, in hPa.| | callback | AsyncCallback<number> | Yes | Callback used to return the altitude, in meters. | -**Return value** +**Example** - ``` + ```js sensor.getAltitude(0, 200, function(err, data) { if (err) { console.error( @@ -1836,9 +1803,9 @@ Obtains the altitude at which the device is located based on the sea-level atmos | --------------------- | ------------------ | | Promise<number> | Promise used to return the altitude, in meters.| -**Return value** +**Example** - ``` + ```js const promise = sensor.getAltitude(0, 200); promise.then((data) => { console.info(' sensor_getAltitude_Promise success', data); @@ -1863,12 +1830,12 @@ Obtains the magnetic dip based on the inclination matrix. This API uses a callba | inclinationMatrix | Array<number> | Yes | Inclination matrix. | | callback | AsyncCallback<number> | Yes | Callback used to return the magnetic dip, in radians.| -**Return value** +**Example** - ``` + ```js sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { if (err) { - console.error(LABEL + 'SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + err.message); return; } @@ -1896,9 +1863,9 @@ Obtains the magnetic dip based on the inclination matrix. This API uses a promis | --------------------- | -------------- | | Promise<number> | Promise used to return the magnetic dip, in radians.| -**Return value** +**Example** - ``` + ```js const promise = sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1]); promise.then((data) => { console.info(' getGeomagneticDip_promise successed', data); @@ -1923,18 +1890,18 @@ Obtains the angle change between two rotation matrices. This API uses a callback | preRotationMatrix | Array<number> | Yes | The other rotation matrix. | | callback | AsyncCallback<Array<number>> | Yes | Callback used to return the angle change around the z, x, and y axes.| -**Return value** +**Example** - ``` + ```js sensor. getAngleModify([1,0,0,0,1,0,0,0,1], [1, 0, 0, 0, 0.87, -0.50, 0, 0.50, 0.87], function(err, data) { if (err) { - console.error(LABEL + 'Failed to register data, error code is: ' + err.code + ', message: ' + + console.error('Failed to register data, error code is: ' + err.code + ', message: ' + err.message); return; } console.info("SensorJsAPI--->Successed to get getAngleModifiy interface get data: " + data.x); for (var i=0; i < data.length; i++) { - console.info(LABEL + "data[" + i + "]: " + data[i]); + console.info("data[" + i + "]: " + data[i]); } }) ``` @@ -1961,17 +1928,17 @@ Obtains the angle change between two rotation matrices. This API uses a promise | ---------------------------------- | ------------------ | | Promise<Array<number>> | Promise used to return the angle change around the z, x, and y axes.| -**Return value** +**Example** - ``` + ```js const promise = sensor.getAngleModify([1,0,0,0,1,0,0,0,1], [1,0,0,0,0.87,-0.50,0,0.50,0.87]); promise.then((data) => { - console.info(LABEL + 'getAngleModifiy_promise success'); + console.info('getAngleModifiy_promise success'); for (var i=0; i < data.length; i++) { - console.info(LABEL + "data[" + i + "]: " + data[i]); + console.info("data[" + i + "]: " + data[i]); } }).catch((reason) => { - console.info(LABEL + "promise::catch", reason); + console.info("promise::catch", reason); }) ``` @@ -1991,18 +1958,18 @@ Converts a rotation vector into a rotation matrix. This API uses a callback to r | rotationVector | Array<number> | Yes | Rotation vector to convert.| | callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation matrix.| -**Return value** +**Example** - ``` + ```js sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877], function(err, data) { if (err) { - console.error(LABEL + 'SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + err.message); return; } console.info("SensorJsAPI--->Successed to get createRotationMatrix interface get data: " + data.x); for (var i=0; i < data.length; i++) { - console.info(LABEL + "data[" + i + "]: " + data[i]); + console.info("data[" + i + "]: " + data[i]); } }) ``` @@ -2028,17 +1995,17 @@ Converts a rotation vector into a rotation matrix. This API uses a promise to re | ---------------------------------- | ------- | | Promise<Array<number>> | Promise used to return the rotation matrix.| -**Return value** +**Example** - ``` + ```js const promise = sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877]); promise.then((data) => { - console.info(LABEL + 'createRotationMatrix_promise success'); + console.info('createRotationMatrix_promise success'); for (var i=0; i < data.length; i++) { - console.info(LABEL + "data[" + i + "]: " + data[i]); + console.info("data[" + i + "]: " + data[i]); } }).catch((reason) => { - console.info(LABEL + "promise::catch", reason); + console.info("promise::catch", reason); }) ``` @@ -2058,18 +2025,18 @@ Converts a rotation vector into a quaternion. This API uses a callback to return | rotationVector | Array<number> | Yes | Rotation vector to convert.| | callback | AsyncCallback<Array<number>> | Yes | Callback used to return the quaternion. | -**Return value** +**Example** - ``` + ```js sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877], function(err, data) { if (err) { - console.error(LABEL + 'SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + err.message); return; } console.info("SensorJsAPI--->Successed to get createQuaternion interface get data: " + data.x); for (var i=0; i < data.length; i++) { - console.info(LABEL + "data[" + i + "]: " + data[i]); + console.info("data[" + i + "]: " + data[i]); } }) ``` @@ -2095,14 +2062,14 @@ Converts a rotation vector into a quaternion. This API uses a promise to return | ---------------------------------- | ------ | | Promise<Array<number>> | Promise used to return the quaternion.| -**Return value** +**Example** - ``` + ```js const promise = sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877]); promise.then((data) => { console.info('createQuaternion_promise successed'); for (var i=0; i < data.length; i++) { - console.info(LABEL + "data[" + i + "]: " + data[i]); + console.info("data[" + i + "]: " + data[i]); } }).catch((err) => { console.info('promise failed'); @@ -2125,18 +2092,18 @@ Obtains the device direction based on the rotation matrix. This API uses a callb | rotationMatrix | Array<number> | Yes | Rotation matrix. | | callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation angle around the z, x, and y axes.| -**Return value** +**Example** - ``` + ```js sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { if (err) { - console.error(LABEL + 'SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + err.message); return; } - console.info(LABEL + "SensorJsAPI--->Successed to get getDirection interface get data: " + data.x); + console.info("SensorJsAPI--->Successed to get getDirection interface get data: " + data); for (var i = 1; i < data.length; i++) { - console.info(TAG +"sensor_getDirection_callback" + data[i]); + console.info("sensor_getDirection_callback" + data[i]); } }) ``` @@ -2162,14 +2129,14 @@ Obtains the device direction based on the rotation matrix. This API uses a promi | ---------------------------------- | ------------------ | | Promise<Array<number>> | Promise used to return the rotation angle around the z, x, and y axes.| -**Return value** +**Example** - ``` + ```js const promise = sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1]); promise.then((data) => { - console.info(' sensor_getAltitude_Promise success', data.x); + console.info('sensor_getAltitude_Promise success', data); for (var i = 1; i < data.length; i++) { - console.info(TAG +"sensor_getDirection_promise" + data[i]); + console.info("sensor_getDirection_promise" + data[i]); } }).catch((err) => { console.info('promise failed'); @@ -2193,18 +2160,18 @@ Creates a rotation matrix based on the gravity vector and geomagnetic vector. Th | geomagnetic | Array<number> | Yes | Geomagnetic vector.| | callback | AsyncCallback<[RotationMatrixResponse](#rotationmatrixresponse)> | Yes | Callback used to return the rotation matrix.| -**Return value** +**Example** - ``` + ```js sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444], function(err, data) { if (err) { - console.error(LABEL + 'SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + err.message); return; } console.info("SensorJsAPI--->Successed to get createRotationMatrix interface get data: " + data.x); for (var i=0; i < data.length; i++) { - console.info(LABEL + "data[" + i + "]: " + data[i]) + console.info("data[" + i + "]: " + data[i]) } }) ``` @@ -2231,17 +2198,17 @@ Creates a rotation matrix based on the gravity vector and geomagnetic vector. Th | ---------------------------------------- | ------- | | Promise<[RotationMatrixResponse](#rotationmatrixresponse)> | Promise used to return the rotation matrix.| -**Return value** +**Example** - ``` + ```js const promise = sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444]); promise.then((data) => { - console.info(LABEL + 'createRotationMatrix_promise successed'); + console.info('createRotationMatrix_promise successed'); for (var i=0; i < data.length; i++) { - console.info(LABEL + "data[" + i + "]: " + data[i]); + console.info("data[" + i + "]: " + data[i]); } }).catch((err) => { - console.info(LABEL + 'promise failed'); + console.info('promise failed'); }) ``` @@ -2355,11 +2322,11 @@ Describes the orientation sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----- | ------ | ---- | ---- | ------------------------ | +| Name | Type | Readable | Writable | Description | +| ----- | ------ | ---- | ---- | ----------------- | | alpha | number | Yes | Yes | Rotation angle of the device around the z-axis, in degrees.| -| beta | number | Yes | Yes | Rotation angle of the device around the x-axis, in degrees. | -| gamma | number | Yes | Yes | Rotation angle of the device around the y-axis, in degrees. | +| beta | number | Yes | Yes | Rotation angle of the device around the x-axis, in degrees.| +| gamma | number | Yes | Yes | Rotation angle of the device around the y-axis, in degrees.| ## RotationVectorResponse diff --git a/en/application-dev/reference/apis/js-apis-service-extension-context.md b/en/application-dev/reference/apis/js-apis-service-extension-context.md index a11942cf16b785967a8491e46a06d8ad820359aa..518167d562ba8801223e206ad5b35ea07ea94936 100644 --- a/en/application-dev/reference/apis/js-apis-service-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-service-extension-context.md @@ -1,11 +1,17 @@ # ServiceExtensionContext -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
-> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. - +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. Implements the context that provides the capabilities and APIs of **ServiceExtension**. This class is inherited from **ExtensionContext**. +## Modules to Import + +``` +import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; +``` ## startAbility @@ -25,13 +31,18 @@ Starts an ability. This API uses a callback to return the result. **Example** ```js - let want = { - "bundleName": "com.example.myapp", - "abilityName": "com.example.myapp.MyAbility" - }; - this.context.startAbility(want, (err) => { - console.log('startAbility result:' + JSON.stringfy(err)); - }); + import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; + class MainAbility extends ExtensionContext { + onWindowStageCreate(windowStage) { + let want = { + "bundleName": "com.example.myapp", + "abilityName": "MyAbility"}; + this.context.startAbility(want, (err) => { + console.log('startAbility result:' + JSON.stringify(err)); + }); + } + } + ``` @@ -58,15 +69,22 @@ Starts an ability. This API uses a promise to return the result. **Example** ```js - let want = { - "bundleName": "com.example.myapp", - "abilityName": "com.example.myapp.MyAbility" - }; - this.context.startAbility(want).then((data) => { - console.log('success:' + JSON.stringfy(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringfy(error)); - }); + import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; + class MainAbility extends ExtensionContext { + onWindowStageCreate(windowStage) { + let want = { + "bundleName": "com.example.myapp", + "abilityName": "MyAbility" + }; + this.context.startAbility(want).then((data) => { + console.log('success:' + JSON.stringify(data)); + }).catch((error) => { + console.log('failed:' + JSON.stringify(error)); + }); + } + } + + ``` @@ -87,9 +105,16 @@ Terminates this ability. This API uses a callback to return the result. **Example** ```js - this.context.terminateSelf((err) => { - console.log('terminateSelf result:' + JSON.stringfy(err)); - }); + import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; + class MainAbility extends ExtensionContext { + onWindowStageCreate(windowStage) { + this.context.terminateSelf((err) => { + console.log('terminateSelf result:' + JSON.stringify(err)); + }); + } + } + + ``` @@ -110,11 +135,17 @@ Terminates this ability. This API uses a promise to return the result. **Example** ```js - this.context.terminateSelf(want).then((data) => { - console.log('success:' + JSON.stringfy(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringfy(error)); - }); + import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; + class MainAbility extends ExtensionContext { + onWindowStageCreate(windowStage) { + this.context.terminateSelf().then((data) => { + console.log('success:' + JSON.stringify(data)); + }).catch((error) => { + console.log('failed:' + JSON.stringify(error)); + }); + } +} + ``` @@ -144,7 +175,7 @@ Connects this ability to a Service ability. ```js let want = { "bundleName": "com.example.myapp", - "abilityName": "com.example.myapp.MyAbility" + "abilityName": "MyAbility" }; let options = { onConnect: function(elementName, proxy) {}, @@ -173,9 +204,18 @@ Disconnects this ability from the Service ability. This API uses a callback to r **Example** ```js - this.context.disconnectAbility(connection, (err) => { // connection is the return value of connectAbility. - console.log('terminateSelf result:' + JSON.stringfy(err)); - }); + import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; + class MainAbility extends ExtensionContext { + onWindowStageCreate(windowStage) { + let connection=1 + this.context.disconnectAbility(connection, (err) => { + // connection is the return value of connectAbility. + console.log('terminateSelf result:' + JSON.stringify(err)); + }); + } + } + + ``` @@ -202,11 +242,18 @@ Disconnects this ability from the Service ability. This API uses a promise to re **Example** ```js - this.context.disconnectAbility(connection).then((data) => { // connection is the return value of connectAbility. - console.log('success:' + JSON.stringfy(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringfy(error)); - }); + import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; + class MainAbility extends ExtensionContext { + onWindowStageCreate(windowStage) { + let connection=1 + this.context.disconnectAbility(connection).then((data) => { // connection is the return value of connectAbility. + console.log('success:' + JSON.stringify(data)); + }).catch((error) => { + console.log('failed:' + JSON.stringify(error)); + }); + } + } + ``` diff --git a/en/application-dev/reference/apis/js-apis-settings.md b/en/application-dev/reference/apis/js-apis-settings.md index 83b3ac3920ac5fe6bca78974f664174157da86b0..81444a400e5dc33c2a2b53c489488fea4fe1be58 100644 --- a/en/application-dev/reference/apis/js-apis-settings.md +++ b/en/application-dev/reference/apis/js-apis-settings.md @@ -27,7 +27,7 @@ Obtains the URI of a data item. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the target data item. Data items can be classified as follows:
  • Existing data items in the database, for example:
    • Brightness: 'settings.screen.brightness'
    • Time format: 'settings.time.format'
  • Custom data items
| +| name | string | Yes| Name of the target data item. Data items can be classified as follows:
  • Existing data items in the database, for example:
    • Brightness: settings.display.SCREEN_BRIGHTNESS_STATUS
    • Time format: settings.date.TIME_FORMAT
  • Custom data items
| **Return value** @@ -39,7 +39,7 @@ Obtains the URI of a data item. ```typescript // Obtain the URI of a data item. - let urivar = settings.getUriSync('settings.screen.brightness'); + let urivar = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS); ``` @@ -55,7 +55,7 @@ Obtains the value of a data item. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes| **DataAbilityHelper** class.| -| name | string | Yes| Name of the target data item. Data items can be classified as follows:
  • Existing data items in the database, for example:
    • Brightness: 'settings.screen.brightness'
    • Time format: 'settings.time.format'
  • Custom data items
| +| name | string | Yes| Name of the target data item. Data items can be classified as follows:
  • Existing data items in the database, for example:
    • Brightness: settings.display.SCREEN_BRIGHTNESS_STATUS
    • Time format: settings.date.TIME_FORMAT
  • Custom data items
| | defValue | string | Yes| Default value This parameter is user-defined. If it is not found in the database, the default value is returned.| **Return value** @@ -69,11 +69,10 @@ Obtains the value of a data item. ```typescript import featureAbility from '@ohos.ability.featureAbility'; -// Obtain the value of 'settings.screen.brightness' (this data item already exists in the database). -let brightness = 'settings.screen.brightness'; -let uri = settings.getUriSync(brightness); +// Obtain the value of settings.display.SCREEN_BRIGHTNESS_STATUS (this data item already exists in the database). +let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS); let helper = featureAbility.acquireDataAbilityHelper(uri); -let value = settings.getValueSync(helper, brightness, '10'); +let value = settings.getValueSync(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, '10'); ``` @@ -85,7 +84,7 @@ Sets the value of a data item. If the specified data item exists in the database, the **setValueSync** method updates the value of the data item. If the data item does not exist in the database, the **setValueSync** method inserts the data item into the database. -**Required permissions**: ohos.permission.WRITE_SYSTEM_SETTING +**Required permissions**: ohos.permission.MODIFY_SETTINGS **System capability**: SystemCapability.Applictaions.settings.Core @@ -94,7 +93,7 @@ If the specified data item exists in the database, the **setValueSync** method u | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes| **DataAbilityHelper** class.| -| name | string | Yes| Name of the target data item. Data items can be classified as follows:
  • Existing data items in the database, for example:
    • Brightness: 'settings.screen.brightness'
    • Time format: 'settings.time.format'
  • Custom data items
| +| name | string | Yes| Name of the target data item. Data items can be classified as follows:
  • Existing data items in the database, for example:
    • Brightness: settings.display.SCREEN_BRIGHTNESS_STATUS
    • Time format: settings.date.TIME_FORMAT
  • Custom data items
| | value | string | Yes| Value of the data item.| **Return value** @@ -108,10 +107,9 @@ If the specified data item exists in the database, the **setValueSync** method u ```typescript import featureAbility from '@ohos.ability.featureAbility'; -// Update the value of 'settings.screen.brightness'. (As this data item exists in the database, the setValueSync +// Update the value of settings.display.SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValueSync method will update the value of the data item.) -let brightness = 'settings.screen.brightness'; -let uri = settings.getUriSync(brightness); +let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS); let helper = featureAbility.acquireDataAbilityHelper(uri); -let ret = settings.setValueSync(helper, brightness, '100'); +let ret = settings.setValueSync(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, '100'); ``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index f1f20e8d810c3f3fa648e680d494199e30bc1dfe..3344e47d14f8d615b1f81e75f92251dc4e8c8287 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -521,7 +521,7 @@ Obtains the number of card slots. **Example** ```js -console.log(sim.getMaxSimCount()) +console.log("Result: "+ sim.getMaxSimCount()) ``` diff --git a/en/application-dev/reference/apis/js-apis-storage-statistics.md b/en/application-dev/reference/apis/js-apis-storage-statistics.md index 3cb85add7ff167a0366e7944d5731b70425d6904..a0b973cb896a595e5361d5a441ab184bf0339b3d 100644 --- a/en/application-dev/reference/apis/js-apis-storage-statistics.md +++ b/en/application-dev/reference/apis/js-apis-storage-statistics.md @@ -5,7 +5,7 @@ > - 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. > - API version 9 is a canary version for trial use. The APIs of this version may be unstable. -The APIs of this module can be used to obtain storage space information, including the space of built-in and plug-in memory cards, space occupied by different types of data, and space of application data. +Obtains storage space information, including the space of built-in and plug-in memory cards, space occupied by different types of data, and space of application data. ## Modules to Import @@ -148,7 +148,7 @@ Asynchronously obtains the available space of the specified volume. This API use getBundleStats(packageName: string): Promise<BundleStats> -Asynchronously obtains information about an application. This API uses a promise to return the result. +Asynchronously obtains space information of an application. This API uses a promise to return the result. **Required permissions**: ohos.permission.STORAGE_MANAGER @@ -166,7 +166,7 @@ Asynchronously obtains information about an application. This API uses a promise | Type | Description | | ------------------------------------------ | -------------------------- | - | Promise<[Bundlestats](#bundlestats)> | Promise used to return the application information obtained.| + | Promise<[Bundlestats](#bundlestats)> | Promise used to return the space information obtained.| - Example @@ -183,7 +183,7 @@ Asynchronously obtains information about an application. This API uses a promise getBundleStats(packageName: string, callback: AsyncCallback<BundleStats>): void -Asynchronously obtains information about an application. This API uses a callback to return the result. +Asynchronously obtains space information of an application. This API uses a callback to return the result. **Required permissions**: ohos.permission.STORAGE_MANAGER @@ -196,7 +196,7 @@ Asynchronously obtains information about an application. This API uses a callbac | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------ | | packageName | string | Yes | Bundle name of the application.| - | callback | callback:AsyncCallback<[Bundlestats](#bundlestats)> | Yes | Callback invoked to return the application information obtained.| + | callback | callback:AsyncCallback<[Bundlestats](#bundlestats)> | Yes | Callback invoked to return the space information obtained.| - Example @@ -214,7 +214,7 @@ Asynchronously obtains information about an application. This API uses a callbac getCurrentBundleStats(): Promise -Asynchronously obtains information about the current third-party application. This API uses a promise to return the result. +Asynchronously obtains space information of the current third-party application. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics @@ -222,7 +222,7 @@ Asynchronously obtains information about the current third-party application. Th | Type | Description | | ------------------------------------------ | -------------------------- | - | Promise<[Bundlestats](#bundlestats)> | Promise used to return the application information obtained. | + | Promise<[Bundlestats](#bundlestats)> | Promise used to return the space information obtained. | - Example @@ -235,15 +235,15 @@ Asynchronously obtains information about the current third-party application. Th getCurrentBundleStats(callback: AsyncCallback): void -Asynchronously obtains information about the current third-party application. This API uses a callback to return the result. - +Asynchronously obtains space information of the current third-party application. This API uses a callback to return the result. + **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics - Parameters | Name | Type | Mandatory | Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------ | - | callback | callback:AsyncCallback<[BundleStats](#bundlestats)> | Yes | Callback invoked to return the application information obtained. | + | callback | callback:AsyncCallback<[BundleStats](#bundlestats)> | Yes | Callback invoked to return the space information obtained. | - Example @@ -260,7 +260,7 @@ Asynchronously obtains information about the current third-party application. Th **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -- Attribute +- Attributes | Name | Type | Description | | --------- | ------ | -------------- | @@ -452,7 +452,7 @@ Asynchronously obtains the space occupied by each type of user data. This API us | Name | Type | Mandatory| Description| | ---------- | ------ | ---- | ---- | - | userId | string | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried.| + | userId | string | No | User ID.
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried.| - Return value @@ -487,7 +487,7 @@ Asynchronously obtains the space occupied by each type of user data. This API us | Name | Type | Mandatory| Description | | ---------- | ------------------------------------ | ---- | -------------------------- | - | userId | string | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried. | + | userId | string | No | User ID.
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried. | | callback | callback:AsyncCallback<[StorageStats](#StorageStats)> | Yes | Callback invoked to return the information obtained.| - Example @@ -505,13 +505,13 @@ Asynchronously obtains the space occupied by each type of user data. This API us **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -- Attribute +- Attributes | Name | Type | Description | | --------- | ------ | -------------- | | total | number | Total space of the built-in memory card. | -| audio | number | Space occupied by the audio data. | -| video | number | Space occupied by the video data.| -| image | number | Space occupied by the image data. | +| audio | number | Space occupied by audio data. | +| video | number | Space occupied by video data.| +| image | number | Space occupied by image data. | | file | number | Space occupied by files. | -| app | number | Space occupied by the application data.| +| app | number | Space occupied by application data.| diff --git a/en/application-dev/reference/apis/js-apis-system-cipher.md b/en/application-dev/reference/apis/js-apis-system-cipher.md index b0dc3c5b117f5256020aa0cc5073e662c62cb6c9..2cc2fa8e75d563784bfc31efcb919619b5738994 100644 --- a/en/application-dev/reference/apis/js-apis-system-cipher.md +++ b/en/application-dev/reference/apis/js-apis-system-cipher.md @@ -1,15 +1,14 @@ # Encryption Algorithm -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> **NOTE**
> -> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> - This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR. +> The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```js import cipher from '@system.cipher' ``` @@ -24,27 +23,27 @@ Encrypts or decrypts data using RSA. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| action | string | Yes | Action type. The options are as follows:
1. **encrypt**: Encrypts data.
2. **decrypt**: Decrypts data. | -| text | string | Yes | Text content to be encrypted or decrypted. The text to be encrypted must be a common text and cannot exceed the length calculated based on the formula (keySize/8 - 66). **keySize** indicates the key length. For example, if the key length is 1024 bytes, the text cannot exceed 62 bytes (1024/8 - 66 = 62). The text content to be decrypted must be a binary value encoded using Base64. The default format is used for Base64 encoding. | -| key | string | Yes | Keys encrypted using RSA. During encryption, this parameter is a public key. During decryption, it is a private key. | -| transformation | string | No | RSA algorithm padding. The default value is **RSA/None/OAEPWithSHA256AndMGF1Padding**. | -| success | Function | No | Called when data is encrypted or decrypted successfully. | -| fail | Function | No | Called when data fails to be encrypted or decrypted. | -| complete | Function | No | Called when the execution is complete. | +| action | string | Yes| Action to perform. The options are as follows:
- encrypt
- decrypt| +| text | string | Yes| Text to be encrypted or decrypted.
The text to be encrypted must be common text that meets the following requirement:
Maximum text length = Key length/8 - 66
For example, if the key is of 1024 bytes, the text to be encrypted cannot exceed 62 bytes (1024/8 -66 = 62).
The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.| +| key | string | Yes| RSA key. The key is used as a public key in encryption and a private key in decryption.| +| transformation | string | No| RSA padding. The default value is **RSA/None/OAEPWithSHA256AndMGF1Padding**.| +| success | Function | No| Called when data is encrypted or decrypted successful.| +| fail | Function | No| Called when data fails to be encrypted or decrypted.| +| complete | Function | No| Called when the execution is complete.| **Example** -``` +```js export default { rsa() { cipher.rsa({ - // Encrypt data. + // Encrypt data. action: 'encrypt', - // Text content to be encrypted + // Text to be encrypted. text: 'hello', - // Base64-encoded public key used for encryption + // Base64-encoded public key used for encryption. key: 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDc7GR2MrfAoefES+wrs1ns2afT\n' + 'eJXSfIkEHfPXG9fVFjaws1ho4KcZfsxlA0+SXvc83f2SVGCuzULmM2lxxRCtcUN/\n' + @@ -58,14 +57,14 @@ export default { } }); cipher.rsa({ - // Decrypt data. + // Decrypt data. action: 'decrypt', - // The text to be decrypted is a Base64-encoded binary value, and the decrypted text is "hello". + // Text to be decrypted, which is binary text encoded in Base64. The decrypted text is "hello". text: 'CUg3tTxTIdpCfreIxIBdws3uhd5qXLwcrVl3XDnQzZFVHyjVVCDHS16rjopaZ4C5xU2Tc8mSDzt7\n' + 'gp9vBfSwi7bMtSUvXG18DlncsKJFDkJpS5t0PkpS9YrJXrY80Gpe+ME6+6dN9bjgqMljbitDdBRf\n' + 'S/ZWNI4Q8Q0suNjNkGU=', - // Base64-encoded public key used for encryption + // Base64-encoded private key used for decryption. key: 'MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANzsZHYyt8Ch58RL\n' + '7CuzWezZp9N4ldJ8iQQd89cb19UWNrCzWGjgpxl+zGUDT5Je9zzd/ZJUYK7NQuYz\n' + @@ -103,30 +102,30 @@ Encrypts or decrypts data using AES. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| action | string | Yes | Action type. The options are as follows:
1. **encrypt**: Encrypts data.
2. **decrypt**: Decrypts data. | -| text | string | Yes | Text content to be encrypted or decrypted. The text to be encrypted must be a common text. The text content to be decrypted must be a binary value encoded using Base64. The default format is used for Base64 encoding. | -| key | string | Yes | Key used for encryption or decryption, which is a character string encrypted using Base64. | -| transformation | string | No | Encryption mode and padding of the AES algorithm. The default value is **AES/CBC/PKCS5Padding**. | -| iv | string | No | Initial vector for AES-based encryption and decryption. The value is a character string encoded using Base64. The default value is the key value. | -| ivOffset | string | No | Offset of the initial vector for AES-based encryption and decryption. The default value is **0**. | -| ivLen | string | No | Length of the initial vector for AES-based encryption and decryption. The default value is **16**. | -| success | Function | No | Called when data is encrypted or decrypted successfully. | -| fail | Function | No | Called when data fails to be encrypted or decrypted. | -| complete | Function | No | Called when the execution is complete. | +| action | string | Yes| Action to perform. The options are as follows:
- encrypt
- decrypt| +| text | string | Yes| Text to be encrypted or decrypted.
The text to be encrypted must be common text. The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.| +| key | string | Yes| Key used for encryption or decryption. It is a string encoded in Base64.| +| transformation | string | No| Encryption mode and padding of the AES algorithm. The default value is **AES/CBC/PKCS5Padding**.| +| iv | string | No| Initialization vector (IV) for AES-based encryption and decryption. The value is a string encoded in Base64. The default value is the key value.| +| ivOffset | string | No| Offset of the IV for AES-based encryption and decryption. The default value is **0**.| +| ivLen | string | No| Length of the IV for AES-based encryption and decryption, in bytes. The default value is **16**.| +| success | Function | No| Called when data is encrypted or decrypted successful.| +| fail | Function | No| Called when data fails to be encrypted or decrypted.| +| complete | Function | No| Called when the execution is complete.| **Example** -``` +```js export default { aes() { cipher.aes({ - // Encrypt data. + // Encrypt data. action: 'encrypt', - // Text content to be encrypted + // Text to be encrypted. text: 'hello', - // Base64-encoded key used for encryption + // Base64-encoded key used for encryption. key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=', transformation: 'AES/CBC/PKCS5Padding', ivOffset: 0, @@ -139,13 +138,13 @@ export default { } }); cipher.aes({ - // Decrypt data. + // Decrypt data. action: 'decrypt', - // Text to be decrypted, which is a Base64-encoded binary value + // Text to be decrypted, which is binary text encoded in Base64. text: 'CUg3tTxTIdpCfreIxIBdws3uhd5qXLwcrVl3XDnQzZFVHyjVVCDHS16rjopaZ4C5xU2Tc8mSDzt7\n' + 'gp9vBfSwi7bMtSUvXG18DlncsKJFDkJpS5t0PkpS9YrJXrY80Gpe+ME6+6dN9bjgqMljbitDdBRf\n' + 'S/ZWNI4Q8Q0suNjNkGU=', - // Base64-encoded key used for decryption + // Base64-encoded key used for decryption. key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=', transformation: 'AES/CBC/PKCS5Padding', ivOffset: 0, @@ -162,4 +161,4 @@ export default { } } -``` \ No newline at end of file +``` diff --git a/en/application-dev/reference/apis/js-apis-system-prompt.md b/en/application-dev/reference/apis/js-apis-system-prompt.md index f894715391f015cbd67ecf913a7923c00d4e78e1..e37601dbfa3ec72d13a7722fb4dc56a8b3fe6fef 100644 --- a/en/application-dev/reference/apis/js-apis-system-prompt.md +++ b/en/application-dev/reference/apis/js-apis-system-prompt.md @@ -1,8 +1,8 @@ # Prompt -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** > -> - The APIs of this module are no longer maintained since API version 8. You are advised to use ['@ohos.prompt](js-apis-prompt.md)' instead. +> - The APIs of this module are no longer maintained since API version 8. You are advised to use [`@ohos.prompt`](js-apis-prompt.md) instead. > > > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -11,7 +11,7 @@ ## Modules to Import -``` +```js import prompt from '@system.prompt'; ``` @@ -31,7 +31,7 @@ Shows the toast. **Example** -``` +```js export default { showToast() { prompt.showToast({ @@ -60,7 +60,7 @@ Shows the dialog box. **Example** -``` +```js export default { showDialog() { prompt.showDialog({ @@ -100,7 +100,7 @@ Shows the action menu. **Example** -``` +```js export default { showActionMenu() { prompt.showActionMenu({ @@ -115,11 +115,11 @@ export default { color: '#000000', }, ], - success: function(data) { + success: function(tapIndex) { console.log('dialog success callback, click button : ' + data.tapIndex); }, - fail: function(data) { - console.log('dialog fail callback' + data.errMsg); + fail: function(errMsg) { + console.log('dialog fail callback' + errMsg); }, }); } @@ -135,7 +135,7 @@ Describes the options for showing the toast. | ------------------- | -------------- | ---- | ---------------------------------------- | | message | string | Yes | Text to display. | | duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The recommended value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used.| -| bottom5+ | string\|number | No | Distance between the toast frame and the bottom of the screen. This parameter is available only on phones and tablets. | +| bottom5+ | string\|number | No | Distance between the toast border and the bottom of the screen. | ## Button 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 a93ffdfa68f6406c6290221d4c5fe757fd7c906b..0f1f932efe54af1337ce19354d19343b6f637687 100644 --- a/en/application-dev/reference/apis/js-apis-system-router.md +++ b/en/application-dev/reference/apis/js-apis-system-router.md @@ -1,6 +1,6 @@ # Page Routing -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** > > - The APIs of this module are no longer maintained since API version 8. You are advised to use [`@ohos.router`](js-apis-router.md) instead. > @@ -11,7 +11,7 @@ ## Modules to Import -``` +```js import router from '@system.router'; ``` @@ -31,7 +31,7 @@ Navigates to a specified page in the application. **Example** -``` +```js // Current page export default { pushPage() { @@ -49,7 +49,7 @@ export default { ``` -``` +```js // routerpage2 page export default { data: { @@ -85,7 +85,7 @@ Replaces the current page with another one in the application and destroys the c **Example** -``` +```js // Current page export default { replacePage() { @@ -100,7 +100,7 @@ export default { ``` -``` +```js // detail page export default { data: { @@ -128,7 +128,7 @@ Returns to the previous page or a specified page. **Example** -``` +```js // index page export default { indexPushPage() { @@ -140,7 +140,7 @@ export default { ``` -``` +```js // detail page export default { detailPushPage() { @@ -152,7 +152,7 @@ export default { ``` -``` +```js // Navigate from the mall page to the detail page through router.back(). export default { mallBackPage() { @@ -162,7 +162,7 @@ export default { ``` -``` +```js // Navigate from the detail page to the index page through router.back(). export default { defaultBack() { @@ -172,7 +172,7 @@ export default { ``` -``` +```js // Return to the detail page through router.back(). export default { backToDetail() { @@ -208,7 +208,7 @@ Clears all historical pages in the stack and retains only the current page at th **Example** -``` +```js export default { clearPage() { router.clear(); @@ -232,7 +232,7 @@ Obtains the number of pages in the current stack. **Example** -``` +```js export default { getLength() { var size = router.getLength(); @@ -257,7 +257,7 @@ Obtains state information about the current page. **Example** -``` +```js export default { getState() { var page = router.getState(); @@ -284,7 +284,7 @@ Enables the display of a confirm dialog box before returning to the previous pag **Example** -``` +```js export default { enableAlertBeforeBackPage() { router.enableAlertBeforeBackPage({ @@ -292,8 +292,8 @@ export default { success: function() { console.log('success'); }, - fail: function() { - console.log('fail'); + cancel: function() { + console.log('cancel'); }, }); } @@ -316,15 +316,15 @@ Disables the display of a confirm dialog box before returning to the previous pa **Example** -``` +```js export default { disableAlertBeforeBackPage() { router.disableAlertBeforeBackPage({ success: function() { console.log('success'); }, - fail: function() { - console.log('fail'); + cancel: function() { + console.log('cancel'); }, }); } diff --git a/en/application-dev/reference/apis/js-apis-system-storage.md b/en/application-dev/reference/apis/js-apis-system-storage.md index 37e8dc5de76e930a81a337c9afd3fe0adcd459c4..ffa96a8e8e6f569c7cc2b9413736aff7048d7713 100644 --- a/en/application-dev/reference/apis/js-apis-system-storage.md +++ b/en/application-dev/reference/apis/js-apis-system-storage.md @@ -68,7 +68,7 @@ Sets the value in the cache based on the specified key. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | string | Yes| Key of the data to set.| -| value | string | Yes| New value to set. The maximum length is 128 bytes.| +| value | string | Yes| New value to set. The length must be less than 128 bytes.| | success | Function | No| Called when **storage.set()** is successful.| | fail | Function | No| Called when **storage.set()** fails. In the callback, **data** indicates the error information, and **code** indicates the error code.| | complete | Function | No| Called when **storage.set()** is complete.| diff --git a/en/application-dev/reference/apis/js-apis-system-time.md b/en/application-dev/reference/apis/js-apis-system-time.md index 74beca3c0aacbabd628f99f7987b96caf5988f61..9d8abc5a6a73f95e4a1c674fc1c1a716154f56d8 100644 --- a/en/application-dev/reference/apis/js-apis-system-time.md +++ b/en/application-dev/reference/apis/js-apis-system-time.md @@ -1,7 +1,8 @@ # Setting the System Time -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> +This module provides the time, time zone, and timing services. Use the time and time zone services to set and obtain the system time and time zone, and use the timing service to manage and use the system time and time zone to implement alarms or other timing functions. + +> **NOTE**
The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -199,7 +200,7 @@ Obtains the time elapsed since system start, excluding the deep sleep time. This ## systemTime.getRealTime8+ -getRealTime(callback: AsyncCallback<number>): void +getRealTime(isNano?: boolean, callback: AsyncCallback<number>): void Obtains the time elapsed since system start, including the deep sleep time. This API uses an asynchronous callback to return the result. @@ -227,7 +228,7 @@ Obtains the time elapsed since system start, including the deep sleep time. This ## systemTime.getRealTime8+ -getRealTime(): Promise<number> +getRealTime(isNano?: boolean): Promise<number> Obtains the time elapsed since system start, including the deep sleep time. This API uses a promise to return the result. diff --git a/en/application-dev/reference/apis/js-apis-timer.md b/en/application-dev/reference/apis/js-apis-timer.md index e85037469d3dd0d931ea7de0a37df77d35880bae..d144a95db8f59ca0605fd228b351380afe6feac8 100644 --- a/en/application-dev/reference/apis/js-apis-timer.md +++ b/en/application-dev/reference/apis/js-apis-timer.md @@ -1,50 +1,45 @@ # Timer -> **NOTE:** The initial APIs of this module are supported since API version 4. Newly added APIs will be marked with a superscript to indicate their earliest API version. -## Module to Import - -None +## setTimeout -## Required Permissions +## Modules to Import -None -## setTimeout +``` +import Time from '@ohos.Time'; +``` -setTimeout(handler[,delay[, ...args]]): number +setTimeout(handler[,delay[,…args]]): number Sets a timer for the system to call a function after the timer goes off. -- Parameters +**Parameters** - +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| handler | Function | Yes| Function to be called after the timer goes off.| +| delay | number | No| Number of milliseconds delayed before the execution. If this parameter is left empty, the default value **0** is used, which means that the execution starts immediately or as soon as possible.| +| ...args | Array<any> | No| Additional parameters to pass to the handler after the timer goes off.| - | Name | Type | Mandatory | Description | - | ------- | ----------- | --------- | ------------------------------------------------------------ | - | handler | Function | Yes | Function to be called after the timer goes off. | - | delay | number | No | Number of milliseconds delayed before the execution. If this parameter is left empty, the default value **0** is used, which means that the execution starts immediately or as soon as possible. | - | ...args | Array\ | No | Additional parameter to pass to the handler after the timer goes off. | +**Return value** -- Return Value +| Type| Description| +| -------- | -------- | +| number | Timer ID.| - +**Example** - | Type | Description | - | ------ | ----------- | - | number | Timer ID. | - -- Example - - ``` - export default { - setTimeOut() { - var timeoutID = setTimeout(function() { - console.log('delay 1s'); - }, 1000); - } +```js +export default { + setTimeOut() { + var timeoutID = setTimeout(function() { + console.log('delay 1s'); + }, 1000); } - ``` +} +``` + ## clearTimeout @@ -52,26 +47,25 @@ clearTimeout(timeoutID: number): void Cancels the timer created via **setTimeout()**. -- Parameter +**Parameters** - +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| timeoutID | number | Yes| ID of the timer to cancel, which is returned by **setTimeout()**| - | Name | Type | Mandatory | Description | - | --------- | ------ | --------- | ------------------------------------------------------------ | - | timeoutID | number | Yes | ID of the timer to cancel, which is returned by **setTimeout()** | +**Example** -- Example - - ``` - export default { - clearTimeOut() { - var timeoutID = setTimeout(function() { - console.log('do after 1s delay.'); - }, 1000); - clearTimeout(timeoutID); - } +```js +export default { + clearTimeOut() { + var timeoutID = setTimeout(function() { + console.log('do after 1s delay.'); + }, 1000); + clearTimeout(timeoutID); } - ``` +} +``` + ## setInterval @@ -79,35 +73,32 @@ setInterval(handler[, delay[, ...args]]): number Sets a repeating timer for the system to repeatedly call a function at a fixed interval. -- Parameters - - +**Parameters** - | Name | Type | Mandatory | Description | - | ------- | ----------- | --------- | ------------------------------------------------------------ | - | handler | Function | Yes | Function to be called repeatedly | - | delay | number | No | Number of milliseconds delayed before the execution | - | ...args | Array\ | No | Additional parameter to pass to the handler after the timer goes off | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| handler | Function | Yes| Function to be called repeatedly.| +| delay | number | No| Number of milliseconds delayed before the execution.| +| ...args | Array<any> | No| Additional parameters to pass to the handler after the timer goes off.| -- Return Value +**Return value** - +| Type| Description| +| -------- | -------- | +| number | ID of the repeating timer.| - | Type | Description | - | ------ | ------------------------- | - | number | ID of the repeated timer. | +**Example** -- Example - - ``` - export default { - setInterval() { - var intervalID = setInterval(function() { - console.log('do very 1s.'); - }, 1000); - } +```js +export default { + setInterval() { + var intervalID = setInterval(function() { + console.log('do very 1s.'); + }, 1000); } - ``` +} +``` + ## clearInterval @@ -115,23 +106,21 @@ clearInterval(intervalID: number): void Cancels the repeating timer set via **setInterval()**. -- Parameter - - +**Parameters** - | Name | Type | Mandatory | Description | - | ---------- | ------ | --------- | ------------------------------------------------------------ | - | intervalID | number | Yes | ID of the repeating timer to cancel, which is returned by **setInterval()**. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| intervalID | number | Yes| ID of the repeating timer to cancel, which is returned by **setInterval()**.| -- Example +**Example** - ``` - export default { - clearInterval() { - var intervalID = setInterval(function() { - console.log('do very 1s.'); - }, 1000); - clearInterval(intervalID); - } +```js +export default { + clearInterval() { + var intervalID = setInterval(function() { + console.log('do very 1s.'); + }, 1000); + clearInterval(intervalID); } - ``` \ No newline at end of file +} +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-uitest.md b/en/application-dev/reference/apis/js-apis-uitest.md index b554e47f481696c48dea31a47315e454a01b9efa..6586d6f0a2c7fc5641a5b49411f67390859e3bfe 100644 --- a/en/application-dev/reference/apis/js-apis-uitest.md +++ b/en/application-dev/reference/apis/js-apis-uitest.md @@ -1,8 +1,7 @@ # UiTest ->**NOTE** +>**NOTE**
The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > ->The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -13,46 +12,27 @@ import {UiDriver,BY,MatchPattern} from '@ohos.uitest' ## By -The UiTest framework provides a wide range of UI component feature description APIs in the **By** class to filter and match components. -The API capabilities provided by the **By** class exhibit the following features: +The UiTest framework provides a wide range of UI component feature description APIs in the **By** class to filter and match components.
+The API capabilities provided by the **By** class exhibit the following features:
1. Allow one or more attributes as the match conditions. For example, you can specify both the **text** and **id** attributes to find the target component.
2. Provide multiple match patterns for component attributes.
3. Support absolute positioning and relative positioning for components. APIs such as [By.isBefore](#byisbefore) and [By.isAfter](#byisafter) can be used to specify the features of adjacent components to assist positioning.
All APIs provided in the **By** class are synchronous. You are advised to use the static constructor **BY** to create a **By** object in chain mode. -- Allows one or more attributes as the match conditions. For example, you can specify both the **text** and **id** attributes to find the target component. - -- Provides multiple match patterns for component attributes. - -- Supports absolute positioning and relative positioning for components. APIs such as **isBefore** and **isAfter** can be used to specify the features of adjacent components to assist positioning. - -All APIs provided in the **By** class are synchronous. You are advised to use the static constructor **BY** to create a **By** object in chain mode, for example, **BY.text('123').type('button')**. - -### enum MatchPattern - -Enumerates the match patterns supported for component attributes. - -**System capability**: SystemCapability.Test.UiTest - -| Name | Value | Description | -| ----------- | ---- | ------------ | -| EQUALS | 0 | Equal to the given value. | -| CONTAINS | 1 | Contain the given value. | -| STARTS_WITH | 2 | Start with the given value.| -| ENDS_WITH | 3 | End with the given value.| +```js +BY.text('123').type('button') +``` ### By.text -text(txt:string,pattern?:MatchPattern):By +text(txt: string, pattern?: MatchPattern): By Specifies the text attribute of the target component. Multiple match patterns are supported. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------ | ---- | ---------------------------------- | -| txt | string | Yes | Component text, used to match the target component.| -| pattern | MatchPattern | No | Match pattern. The default value is **EQUALS**. | +| Name | Type | Mandatory| Description | +| ------- | ------------ | ---- | ------------------------------------------------- | +| txt | string | Yes | Component text, used to match the target component. | +| pattern | MatchPattern | No | Match pattern. The default value is [EQUALS](#matchpattern).| **Return value** @@ -62,324 +42,382 @@ Specifies the text attribute of the target component. Multiple match patterns ar **Example** -``` -let by = BY.text('123') // Use the static constructor BY to create a By object and specify the text attribute - of the target component. +```js +let by = BY.text('123') // Use the static constructor BY to create a By object and specify the text attribute of the target component. ``` ### By.key -key(key:string):By; +key(key: string): By Specifies the key attribute of the target component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | --------------- | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------------- | | key | string | Yes | Component key.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.key('123') // Use the static constructor BY to create a By object and specify the key attribute - of the target component. +```js +let by = BY.key('123') // Use the static constructor BY to create a By object and specify the key attribute of the target component. ``` ### By.id -id(id:number):By; - -Specifies the ID property of the target component. +id(id: number): By -**Required permissions**: none +Specifies the ID attribute of the target component. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------ | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | | id | number | Yes | Component ID.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.id(123) // Use the static constructor BY to create a By object and specify the ID attribute - of the target component. +```js +let by = BY.id(123) // Use the static constructor BY to create a By object and specify the id attribute of the target component. ``` ### By.type -type(tp:string):By; +type(tp: string): By -Specifies the type property of the target component. - -**Required permissions**: none +Specifies the type attribute of the target component. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------ | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------- | | tp | string | Yes | Component type.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.type('button') // Use the static constructor BY to create a By object and specify the type attribute - of the target component. +```js +let by = BY.type('button') // Use the static constructor BY to create a By object and specify the type attribute of the target component. ``` ### By.clickable -clickable(b?:bool):By; +clickable(b?: bool): By Specifies the clickable attribute of the target component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ------------------------------ | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------------------------- | | b | bool | No | Clickable status of the target component. The default value is **true**.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** +```js +let by = BY.clickable(true) // Use the static constructor BY to create a By object and specify the clickable status attribute of the target component. ``` -let by = BY.clickable(true) // Use the static constructor BY to create a By object and specify the clickable attribute - of the target component. + +### By.longClickable9+ + +longClickable(b?: bool): By + +Specifies the long-clickable status attribute of the target component. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ------------------------------------ | +| b | bool | No | Long-clickable status of the target component. The default value is **true**.| + +**Return value** + +| Type| Description | +| ---- | ---------------- | +| By | Returns the **By** object itself.| + +**Example** + +```js +let by = BY.longClickable(true) // Use the static constructor BY to create a By object and specify the long-clickable status attribute of the target component. ``` ### By.scrollable -scrollable(b?:bool):By; +scrollable(b?: bool): By -Specifies the scrollable attribute of the target component. - -**Required permissions**: none +Specifies the scrollable status attribute of the target component. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | -------------------------- | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------------------------- | | b | bool | No | Scrollable status of the target component. The default value is **true**.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.scrollable(true) // Use the static constructor BY to create a By object and specify the scrollable attribute - of the target component. +```js +let by = BY.scrollable(true) // Use the static constructor BY to create a By object and specify the scrollable status attribute of the target component. ``` ### By.enabled -enabled(b?:bool):By; - -Specifies the enable attribute of the target component. +enabled(b?: bool): By -**Required permissions**: none +Specifies the enabled status attribute of the target component. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ---------------------------- | -| b | bool | No | Enable status of the target component. The default value is **true**.| +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ------------------------------ | +| b | bool | No | Enabled status of the target component. The default value is **true**.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.enabled(true) // Use the static constructor BY to create a By object and specify the enable attribute - of the target component. +```js +let by = BY.enabled(true) // Use the static constructor BY to create a By object and specify the enabled status attribute of the target component. ``` ### By.focused -focused(b?:bool):By; - -Specifies the focused attribute of the target component. +focused(b?: bool): By -**Required permissions**: none +Specifies the focused status attribute of the target component. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ------------------------ | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------------------- | | b | bool | No | Focused status of the target component. The default value is **true**.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.enabled(true) // Use the static constructor BY to create a By object and specify the focused attribute - of the target component. +```js +let by = BY.focused(true) // Use the static constructor BY to create a By object and specify the focused status attribute of the target component. ``` ### By.selected -selected(b?:bool):By; - -Specifies the selected attribute of the target component. +selected(b?: bool): By -**Required permissions**: none +Specifies the selected status attribute of the target component. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ------------------------------ | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------------------------- | | b | bool | No | Selected status of the target component. The default value is **true**.| **Return value** +| Type| Description | +| ---- | ---------------- | +| By | Returns the **By** object itself.| + +**Example** + +```js +let by = BY.selected(true) // Use the static constructor BY to create a By object and specify the selected status attribute of the target component. +``` + +### By.checked9+ + +checked(b?: bool): By + +Specifies the checked status attribute of the target component. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | --------------------------------- | +| b | bool | No | Checked status of the target component. The default value is **false**.| + +**Return value** + | Type| Description | | ---- | -------------- | | By | Returns the **By** object itself.| **Example** +```js +let by = BY.checked(true) // Use the static constructor BY to create a By object and specify the checked status attribute of the target component. ``` -let by = BY.selected(true) // Use the static constructor BY to create a By object and specify the selected attribute - of the target component. + +### By.checkable9+ + +checkable(b?: bool): By + +Specifies the checkable status attribute of the target component. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ------------------------------------- | +| b | bool | No | Checkable status of the target component. The default value is **false**.| + +**Return value** + +| Type| Description | +| ---- | ---------------- | +| By | Returns the **By** object itself.| + +**Example** + +```js +let by = BY.checkable(true) // Use the static constructor BY to create a By object and specify the checkable status attribute of the target component. ``` ### By.isBefore -isBefore(by:By):By; +isBefore(by: By): By Specifies the attributes of the component before which the target component is located. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | -------------- | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------------- | | by | By | Yes | Attributes of the component before which the target component is located.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.isBefore(BY.text('123')) // Use the static constructor BY to create a By object and specify the attributes - of the component before which the target component is located. +```js +let by = BY.isBefore(BY.text('123')) // Use the static constructor BY to create a By object and specify the attributes of the component before which the target component is located. ``` ### By.isAfter -isAfter(by:By):By; +isAfter(by: By): By Specifies the attributes of the component after which the target component is located. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | -------------- | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------------- | | by | By | Yes | Attributes of the component before which the target component is located.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.isAfter(BY.text('123')) // Use the static constructor BY to create a By object and specify the attributes - of the component after which the target component is located. +```js +let by = BY.isAfter(BY.text('123')) // Use the static constructor BY to create a By object and specify the attributes of the component after which the target component is located. ``` ## UiComponent In **UiTest**, the **UiComponent** class represents a component on the UI and provides APIs for obtaining component attributes, clicking a component, scrolling to search for a component, and text injection. -All APIs provided by this class use a promise to return the result and must be invoked using **await**. +All APIs provided in this class use a promise to return the result and must be invoked using **await**. + +### Rect9+ + +Provides border information of a component. + +**System capability**: SystemCapability.Test.UiTest + +| Name | Type| Readable| Writable| Description | +| ------- | -------- | ---- | ---- | ------------------------- | +| leftX | number | Yes | No | X coordinate of the upper left corner of the component borders.| +| topY | number | Yes | No | Y coordinate of the upper left corner of the component borders.| +| rightX | number | Yes | No | X coordinate of the lower right corner of the component borders.| +| bottomY | number | Yes | No | Y coordinate of the lower right corner of the component borders.| ### UiComponent.click -click():Promise; +click(): Promise\ Clicks this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -389,37 +427,33 @@ async function demo() { ### UiComponent.doubleClick -doubleClick():Promise; +doubleClick(): Promise\ Double-clicks this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) - await buttont.doubleClick() + await button.doubleClick() } ``` ### UiComponent.longClick -longClick():Promise; +longClick(): Promise\ Long-clicks this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -429,23 +463,21 @@ async function demo() { ### UiComponent.getId -getId():Promise; +getId(): Promise\ Obtains the ID of this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| ---------------- | ------------------------- | -| Promise; | Promise used to return the component ID.| +| Type | Description | +| ---------------- | ------------------------------- | +| Promise\ | Promise used to return the ID of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -455,23 +487,21 @@ async function demo() { ### UiComponent.getKey -getKey():Promise; +getKey(): Promise\ Obtains the key of this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| ---------------- | -------------------------- | -| Promise; | Promise used to return the component key.| +| Type | Description | +| ---------------- | ------------------------------ | +| Promise\ | Promise used to return the key of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -481,23 +511,21 @@ async function demo() { ### UiComponent.getText -getText():Promise; +getText(): Promise\ Obtains the text information of this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| ---------------- | ------------------------------- | -| Promise; | Promise used to return the text information of the component.| +| Type | Description | +| ---------------- | --------------------------------- | +| Promise\ | Promise used to return the text information of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -507,23 +535,21 @@ async function demo() { ### UiComponent.getType -getType():Promise; +getType(): Promise\ Obtains the type of this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| ---------------- | ------------------------------- | -| Promise; | Promise used to return the component type.| +| Type | Description | +| ---------------- | ----------------------------- | +| Promise\ | Promise used to return the type of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -531,25 +557,47 @@ async function demo() { } ``` +### UiComponent.getBounds9+ + +getBounds(): Promise\ + +Obtains the bounds of this component. + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| -------------- | ------------------------------------- | +| Promise\ | Promise used to return the bounds of the component.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + let rect = await button.getBounds() +} +``` + ### UiComponent.isClickable -isClickable():Promise; +isClickable(): Promise\ Obtains the clickable status of this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| -------------- | ----------------------------------- | -| Promise; | Promise used to return the clickable status of the component.| +| Type | Description | +| -------------- | ------------------------------------- | +| Promise\ | Promise used to return the clickable status of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -562,25 +610,110 @@ async function demo() { } ``` -### UiComponent.isScrollable +### UiComponent.isLongClickable9+ -isScrollable():Promise; +isLongClickable(): Promise\ -Obtains the scrollable status of this component. +Obtains the long clickable status of this component. + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| -------------- | ------------------------------------------- | +| Promise\ | Promise used to return the long clickable status of the component.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + if(await button.isLongClickable()) { + console.info('This button can longClick') + } + else{ + console.info('This button can not longClick') + } +} +``` + +### UiComponent.isChecked9+ + +isChecked(): Promise\ -**Required permissions**: none +Obtains the checked status of this component. **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| -------------- | ----------------------------------- | -| Promise; | Promise used to return the scrollable status of the component.| +| Type | Description | +| -------------- | ------------------------------------- | +| Promise\ | Promise used to return the checked status of the component.| **Example** +```js +async function demo() { + let driver = UiDriver.create() + let checkBox = await driver.findComponent(BY.type('Checkbox')) + if(await checkBox.isChecked) { + console.info('This checkBox is checked') + } + else{ + console.info('This checkBox is not checked') + } +} ``` + +### UiComponent.isCheckable9+ + +isCheckable(): Promise\ + +Obtains the checked status of this component. + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| -------------- | ------------------------------------------- | +| Promise\ | Promise used to return the checked status of the component.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create() + let checkBox = await driver.findComponent(BY.type('Checkbox')) + if(await checkBox.isCheckable) { + console.info('This checkBox is checkable') + } + else{ + console.info('This checkBox is not checkable') + } +} +``` + +### UiComponent.isScrollable + +isScrollable(): Promise\ + +Obtains the scrollable status of this component. + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| -------------- | ------------------------------------- | +| Promise\ | Promise used to return the scrollable status of the component.| + +**Example** + +```js async function demo() { let driver = UiDriver.create() let scrollBar = await driver.findComponent(BY.scrollable(true)) @@ -596,23 +729,21 @@ async function demo() { ### UiComponent.isEnabled -isEnabled():Promise; +isEnabled(): Promise\ -Obtains the enable status of this component. - -**Required permissions**: none +Obtains the enabled status of this component. **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| -------------- | ----------------------------- | -| Promise; | Promise used to return the enable status of the component.| +| Type | Description | +| -------------- | ------------------------------- | +| Promise\ | Promise used to return the enabled status of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -628,23 +759,21 @@ async function demo() { ### UiComponent.isFocused -isFocused():Promise; +isFocused(): Promise\ Obtains the focused status of this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| -------------- | --------------------------------- | -| Promise; | Promise used to return the focused status of the component.| +| Type | Description | +| -------------- | ----------------------------------- | +| Promise\ | Promise used to return the focused status of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -659,23 +788,21 @@ async function demo() { ### UiComponent.isSelected -isSelected():Promise; +isSelected(): Promise\ Obtains the selected status of this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| -------------- | ----------------------------------- | -| Promise; | Promise used to return the selected status of the component.| +| Type | Description | +| -------------- | -------------------- | +| Promise\ | Promise used to return the selected status of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -690,37 +817,51 @@ async function demo() { ### UiComponent.inputText -inputText(text: string):Promise; +inputText(text: string): Promise\ Enters text into this component (available for text boxes). -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------- | -| text | string | Yes | Text to be entered to the component.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| text | string | Yes | Text to enter.| **Example** +```js +async function demo() { + let driver = UiDriver.create() + let text = await driver.findComponent(BY.text('hello world')) + await text.inputText('123') +} ``` + +### UiComponent.clearText9+ + +clearText(): Promise\ + +Clears text in this component (available for text boxes). + +**System capability**: SystemCapability.Test.UiTest + +**Example** + +```js async function demo() { let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) - await button.inputText('next page') + let text = await driver.findComponent(BY.text('hello world')) + await text.clearText() } ``` ### UiComponent.scrollSearch -scrollSearch(by:By):Promise; - -Scrolls on this component to search for the target component (available for lists). +scrollSearch(by: By): Promise\ -**Required permissions**: none +Scrolls on this component to search for the target component (applicable to component that support scrolling, such as **\**). **System capability**: SystemCapability.Test.UiTest @@ -732,20 +873,81 @@ Scrolls on this component to search for the target component (available for list **Return value** -| Type | Description | -| --------------------- | ----------------------------------- | -| Promise; | Promise used to return the target component.| +| Type | Description | +| --------------------- | ------------------------------------- | +| Promise\ | Promise used to return the target component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() - let scrollBar = await driver.findComponent(BY.scrollable(true)) + let scrollBar = await driver.findComponent(BY.type('Scroll')) let button = await scrollBar.scrollSearch(BY.text('next page')) } ``` +### UiComponent.scrollToTop9+ + +scrollToTop(): Promise\ + +Scrolls to the top of this a component (applicable to component that support scrolling, such as **\**). + +**System capability**: SystemCapability.Test.UiTest + +**Example** + +```js +async function demo() { + let driver = UiDriver.create() + let scrollBar = await driver.findComponent(BY.type('Scroll')) + await scrollBar.scrollToTop() +} +``` + +### UiComponent.scrollToBottom9+ + +scrollToBottom(): Promise\ + +Scrolls to the bottom of this a component (applicable to component that support scrolling, such as **\**). + +**System capability**: SystemCapability.Test.UiTest + +**Example** + +```js +async function demo() { + let driver = UiDriver.create() + let scrollBar = await driver.findComponent(BY.type('Scroll')) + await scrollBar.scrollToBottom() +} +``` + +### UiComponent.dragTo9+ + +dragTo(target: UiComponent): Promise\ + +Drags this component to the target component. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------- | ---- | ---------- | +| target | UiComponent | Yes | Target component.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + let text = await driver.findComponent(BY.text('hello world')) + await button.dragTo(text) + } +``` + ## UiDriver The **UiDriver** class is the main entry to the **uitest** test framework. It provides APIs for features such as component matching/search, key injection, coordinate clicking/sliding, and screenshot. @@ -753,23 +955,21 @@ All APIs provided by this class, except for **UiDriver.create()**, use a promise ### UiDriver.create -static create():UiDriver; +static create(): UiDriver Creates a **UiDriver** object and returns the object created. This API is a static API. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| ------- | ---------------------- | +| Type | Description | +| ------- | ------------------------ | | UiDrive | Returns the **UiDriver** object created.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() } @@ -777,23 +977,21 @@ async function demo() { ### UiDriver.delayMs -delayMs(duration:number):Promise; +delayMs(duration: number): Promise\ Delays this **UiDriver** object within the specified duration. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ---------- | +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------ | | duration | number | Yes | Duration of time.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.delayMs(1000) @@ -802,29 +1000,27 @@ async function demo() { ### UiDriver.findComponent -findComponent(by:By):Promise; - -Searches this **UiDriver** object for the target component that has the given attributes. +findComponent(by: By): Promise\ -**Required permissions**: none +Searches this **UiDriver** object for the target component that matches the given attributes. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ------------------ | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------------- | | by | By | Yes | Attributes of the target component.| **Return value** -| Type | Description | -| --------------------- | ------------------------------- | -| Promise; | Promise used to return the found component.| +| Type | Description | +| --------------------- | --------------------------------- | +| Promise\ | Promise used to return the found component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.text('next page')) @@ -833,54 +1029,80 @@ async function demo() { ### UiDriver.findComponents -findComponents(by:By):Promise>; +findComponents(by: By): Promise\> Searches this **UiDriver** object for all components that match the given attributes. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ------------------ | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------------- | | by | By | Yes | Attributes of the target component.| **Return value** -| Type | Description | -| ---------------------------- | ------------------------------------- | -| Promise>; | Promise used to return a list of found components.| +| Type | Description | +| ----------------------------- | --------------------------------------- | +| Promise\> | Promise used to return a list of found components.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let buttonList = await driver.findComponents(BY.text('next page')) } ``` +### UiDriver.waitForComponent9+ + +waitForComponent(by: By, time: number): Promise\ + +Searches this **UiDriver** object for the target component that matches the given attributes within the specified duration. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------- | +| by | By | Yes | Attributes of the target component. | +| time | number | Yes | Duration for searching for the target component, in ms.| + +**Return value** + +| Type | Description | +| --------------------- | --------------------------------- | +| Promise\ | Promise used to return the found component.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create() + let button = await driver.waitForComponent(BY.text('next page'),500) +} +``` + ### UiDriver.assertComponentExist -assertComponentExist(by:By):Promise; +assertComponentExist(by: By): Promise\ Asserts that a component that matches the given attributes exists on the current page. If the component does not exist, the API throws a JS exception, causing the current test case to fail. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ------------------ | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------------- | | by | By | Yes | Attributes of the target component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.assertComponentExist(BY.text('next page')) @@ -889,17 +1111,15 @@ async function demo() { ### UiDriver.pressBack -pressBack():Promise; +pressBack(): Promise\ Presses the Back button on this **UiDriver** object. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.pressBack() @@ -908,23 +1128,21 @@ async function demo() { ### UiDriver.triggerKey -triggerKey(keyCode:number):Promise; +triggerKey(keyCode: number): Promise\ Triggers the key of this **UiDriver** object that matches the given key code. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | --------- | +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------- | | keyCode | number | Yes | Key code.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.triggerKey(123) @@ -933,23 +1151,22 @@ async function demo() { ### UiDriver.click -click(x:number,y:number):Promise; +click(x: number, y: number): Promise\ Clicks a specific point of this **UiDriver** object based on the given coordinates. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------- | ---- | ------------------------------------------- | -| x,y | number,number | Yes | Coordinate information of a specific point in the (number,number) format.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| x | number | Yes | X coordinate of the target point.| +| y | number | Yes | Y coordinate of the target point.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.click(100,100) @@ -958,23 +1175,22 @@ async function demo() { ### UiDriver.doubleClick -doubleClick(x:number,y:number):Promise; +doubleClick(x: number, y: number): Promise\ Double-clicks a specific point of this **UiDriver** object based on the given coordinates. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------- | ---- | ------------------------------------------- | -| x,y | number,number | Yes | Coordinate information of a specific point in the (number,number) format.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| x | number | Yes | X coordinate of the target point.| +| y | number | Yes | Y coordinate of the target point.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.doubleClick(100,100) @@ -983,23 +1199,22 @@ async function demo() { ### UiDriver.longClick -longClick(x:number,y:number):Promise; +longClick(x: number, y: number): Promise\ Long-clicks a specific point of this **UiDriver** object based on the given coordinates. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------- | ---- | ------------------------------------------- | -| x,y | number,number | Yes | Coordinate information of a specific point in the (number,number) format.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| x | number | Yes | X coordinate of the target point.| +| y | number | Yes | Y coordinate of the target point.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.longClick(100,100) @@ -1008,51 +1223,96 @@ async function demo() { ### UiDriver.swipe -swipe(startx:number,starty:number,endx:number,endy:number):Promise; - -Swipes from the start point to the end point of this **UiDriver** object based on the given coordinates. +swipe(startx: number, starty: number, endx: number, endy: number): Promise\ -**Required permissions**: none +Swipes on this **UiDriver** object from the start point to the end point based on the given coordinates. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | ------------- | ---- | ------------------------------------------- | -| startx,starty | number,number | Yes | Coordinate information of the start point in the (number,number) format.| -| endx,endy | number,number | Yes | Coordinate information of the end point in the (number,number) format.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| startx | number | Yes | X coordinate of the start point.| +| starty | number | Yes | Y coordinate of the start point.| +| endx | number | Yes | X coordinate of the end point.| +| endy | number | Yes | Y coordinate of the end point.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.swipe(100,100,200,200) } ``` +### UiDriver.drag9+ + +drag(startx: number, starty: number, endx: number, endy: number): Promise\ + +Drags this **UiDriver** object from the given start point to the given end point. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| startx | number | Yes | X coordinate of the start point.| +| starty | number | Yes | Y coordinate of the start point.| +| endx | number | Yes | X coordinate of the end point.| +| endy | number | Yes | Y coordinate of the end point.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create() + await driver.drag(100,100,200,200) +} +``` + ### UiDriver.screenCap -screenCap(savePath:string):Promise; +screenCap(savePath: string): Promise\ Captures the current screen of this **UiDriver** object and saves it as a PNG image to the given save path. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ------------ | +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | -------------- | | savePath | string | Yes | File save path.| +**Return value** + +| Type | Description | +| -------------- | -------------------------------------- | +| Promise\ | Promise used to return the operation result. The value **true** means that the operation is successful.| + **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.screenCap('/local/tmp/') } ``` + +## MatchPattern + +Enumerates the match patterns supported for component attributes. + +**System capability**: SystemCapability.Test.UiTest + +| Name | Value | Description | +| ----------- | ---- | -------------- | +| EQUALS | 0 | Equal to the given value. | +| CONTAINS | 1 | Containing the given value. | +| STARTS_WITH | 2 | Starting from the given value.| +| ENDS_WITH | 3 | Ending with the given value.| + +### diff --git a/en/application-dev/reference/apis/js-apis-update.md b/en/application-dev/reference/apis/js-apis-update.md index d84b4bdcd5acbe6169c8172961f935f254f5a7d2..251c1d59b610f4d01372186d0e40d0521cf62ca8 100644 --- a/en/application-dev/reference/apis/js-apis-update.md +++ b/en/application-dev/reference/apis/js-apis-update.md @@ -134,11 +134,11 @@ Obtains the new version information. This function uses an asynchronous callback **Example** ``` -update.getNewVersionInfo(info => { +updater.getNewVersionInfo(info => { console.log("getNewVersionInfo success " + info.status); - console.log(`info versionName = ` + info.result[0].versionName); - console.log(`info versionCode = ` + info.result[0].versionCode); - console.log(`info verifyInfo = ` + info.result[0].verifyInfo); + console.log(`info versionName = ` + info.checkResult[0].versionName); + console.log(`info versionCode = ` + info.checkResult[0].versionCode); + console.log(`info verifyInfo = ` + info.checkResult[0].verifyInfo); }); ``` @@ -160,9 +160,9 @@ Obtains the new version information. This function uses a promise to return the ``` updater.getNewVersionInfo().then(value => { - console.log(`info versionName = ` + value.result[0].versionName); - console.log(`info versionCode = ` + value.result[0].versionCode); - console.log(`info verifyInfo = ` + value.result[0].verifyInfo); + console.log(`info versionName = ` + value.checkResult[0].versionName); + console.log(`info versionCode = ` + value.checkResult[0].versionCode); + console.log(`info verifyInfo = ` + value.checkResult[0].verifyInfo); }).catch(err => { console.log("getNewVersionInfo promise error: " + err.code); }); @@ -185,11 +185,11 @@ Checks whether the current version is the latest. This function uses an asynchro **Example** ``` -update.checkNewVersion(info => { +updater.checkNewVersion(info => { console.log("checkNewVersion success " + info.status); - console.log(`info versionName = ` + info.result[0].versionName); - console.log(`info versionCode = ` + info.result[0].versionCode); - console.log(`info verifyInfo = ` + info.result[0].verifyInfo); + console.log(`info versionName = ` + info.checkResult[0].versionName); + console.log(`info versionCode = ` + info.checkResult[0].versionCode); + console.log(`info verifyInfo = ` + info.checkResult[0].verifyInfo); }); ``` @@ -210,10 +210,10 @@ Checks whether the current version is the latest. This function uses a promise t **Example** ``` -update.checkNewVersion().then(value => { - console.log(`info versionName = ` + value.result[0].versionName); - console.log(`info versionCode = ` + value.result[0].versionCode); - console.log(`info verifyInfo = ` + value.result[0].verifyInfo); +updater.checkNewVersion().then(value => { + console.log(`info versionName = ` + value.checkResult[0].versionName); + console.log(`info versionCode = ` + value.checkResult[0].versionCode); + console.log(`info verifyInfo = ` + value.checkResult[0].verifyInfo); }).catch(err => { console.log("checkNewVersion promise error: " + err.code); }); @@ -237,13 +237,13 @@ Verifies whether the update package is valid. **Example** ``` -update.on("verifyProgress", callback => { +updater.on("verifyProgress", callback => { console.info('on verifyProgress ' + callback.percent); }); update.verifyUpdatePackage("XXX", "XXX"); ``` -### rebootAndCleanUserData +### rebootAndCleanUserData8+ rebootAndCleanUserData(): Promise\ @@ -260,14 +260,14 @@ Reboots the device and clears the user partition data. This function uses a prom **Example** ``` -update.rebootAndCleanUserData().then(result => { +updater.rebootAndCleanUserData().then(result => { console.log("rebootAndCleanUserData " + result); }).catch(err => { console.info("rebootAndCleanUserData promise error: " + err.code); }); ``` -### rebootAndCleanUserData +### rebootAndCleanUserData8+ rebootAndCleanUserData(callback: AsyncCallback\): void @@ -284,7 +284,7 @@ Reboots the device and clears the user partition data. This function uses a prom **Example** ``` -update.rebootAndCleanUserData(result => { +updater.rebootAndCleanUserData(result => { console.log("rebootAndCleanUserData ", result) }); ``` @@ -306,7 +306,7 @@ Installs the update package. This function uses a promise to return the result. **Example** ``` -update.applyNewVersion().then(result => { +updater.applyNewVersion().then(result => { console.log("appVewVersion ", result) }).catch(err => { console.info("applyNewVersion promise error: " + err.code); @@ -330,7 +330,7 @@ Installs the update package. This function uses a promise to return the result. **Example** ``` -update.applyNewVersion(result => { +updater.applyNewVersion(result => { console.log("applyNewVersion ", result) }); ``` @@ -399,7 +399,7 @@ let policy = { autoUpgradeInterval: [ 2, 3 ], autoUpgradeCondition: 2 } -update.setUpdatePolicy(policy, result => { +updater.setUpdatePolicy(policy, result => { console.log("setUpdatePolicy ", result) }); ``` @@ -434,7 +434,7 @@ let policy = { autoUpgradeInterval: [ 2, 3 ], autoUpgradeCondition: 2 } -update.setUpdatePolicy(policy).then(result => +updater.setUpdatePolicy(policy).then(result => console.log("setUpdatePolicy ", result) ).catch(err => { console.log("setUpdatePolicy promise error: " + err.code); @@ -458,7 +458,7 @@ Obtains the update policy. This function uses an asynchronous callback to return **Example** ``` -update.getUpdatePolicy(policy => { +updater.getUpdatePolicy(policy => { console.log("getUpdatePolicy success"); console.log(`policy autoDownload = ` + policy.autoDownload); console.log(`policy autoDownloadNet = ` + policy.autoDownloadNet); @@ -483,7 +483,7 @@ Obtains the update policy. This function uses a promise to return the result. **Example** ``` -update.getUpdatePolicy().then(value => { +updater.getUpdatePolicy().then(value => { console.log(`info autoDownload = ` + value.autoDownload); console.log(`info autoDownloadNet = ` + value.autoDownloadNet); console.log(`info mode = ` + value.mode); diff --git a/en/application-dev/reference/apis/js-apis-uri.md b/en/application-dev/reference/apis/js-apis-uri.md index 4952c227c32677d8bc1f13b3cd07d448ff0d21f0..a6c8823599cfee6dba5288e6555d6c618fd414c8 100644 --- a/en/application-dev/reference/apis/js-apis-uri.md +++ b/en/application-dev/reference/apis/js-apis-uri.md @@ -1,12 +1,13 @@ # URI String Parsing -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```js import uri from '@ohos.uri' ``` @@ -41,7 +42,7 @@ A constructor used to create a URI instance. | Name| Type.| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| url | string | Yes| Yes| Input object.| +| uri | string | Yes| Yes| Input object.| **Example** @@ -60,7 +61,7 @@ toString(): string **System capability**: SystemCapability.Utils.Lang -Obtains the query string applicable to this URL. +Obtains the query string applicable to this URI. **Return value** @@ -71,8 +72,8 @@ Obtains the query string applicable to this URL. **Example** ```js -const url = new uri.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); -url.toString() +const uri = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +uri.toString() ``` diff --git a/en/application-dev/reference/apis/js-apis-useriam-userauth.md b/en/application-dev/reference/apis/js-apis-useriam-userauth.md index 39b0daf04ecbf60d2f4cefbeb4b60416c187ed68..56ac3823f29e6cee7efa13094d4becf5528fa854 100644 --- a/en/application-dev/reference/apis/js-apis-useriam-userauth.md +++ b/en/application-dev/reference/apis/js-apis-useriam-userauth.md @@ -50,7 +50,7 @@ export default { try { console.info("auth onResult result = " + result); console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == 'SUCCESS') { + if (result == userIAM_userAuth.ResultCode.SUCCESS) { // Add the logic to be executed when the authentication is successful. } else { // Add the logic to be executed when the authentication fails. @@ -97,7 +97,7 @@ export default { } }); let cancelCode = this.auth.cancel(contextId); - if (cancelCode == userIAM_userAuth.Result.SUCCESS) { + if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) { console.info("cancel auth success"); } else { console.error("cancel auth fail"); @@ -110,7 +110,7 @@ export default { getAuthenticator(): Authenticator -> **NOTE**
+> **NOTE**
> This API is not longer maintained since API version 8. You are advised to use [constructor](#constructor8). Obtains an **Authenticator** object for user authentication. @@ -122,7 +122,7 @@ Obtains an **Authenticator** object for user authentication. **Return value** | Type | Description | | ----------------------------------------- | ------------ | -| [Authenticator](#authenticatordeprecated) | **Authenticator** object obtained. | +| [Authenticator](#authenticatordeprecated) | **Authenticator** object obtained.| **Example** ```js @@ -131,7 +131,7 @@ Obtains an **Authenticator** object for user authentication. ## Authenticator(deprecated) -> **NOTE**
+> **NOTE**
> This object is not longer maintained since API version 8. You are advised to use [UserAuth](#userauth8). Provides methods to manage an **Authenticator** object. @@ -141,7 +141,7 @@ Provides methods to manage an **Authenticator** object. execute(type: string, level: string, callback: AsyncCallback<number>): void -> **NOTE**
+> **NOTE**
> This API is not longer maintained since API version 8. You are advised to use [auth](#auth8). Performs user authentication. This API uses asynchronous callback to return the result. @@ -154,15 +154,15 @@ Performs user authentication. This API uses asynchronous callback to return the | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version. | -| level | string | Yes | Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication. | +| type | string | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.| +| level | string | Yes | Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.| | callback | AsyncCallback<number> | No | Callback used to return the result. | Parameters returned in callback | Type | Description | | ------ | ------------------------------------------------------------ | -| number | Authentication result. For details, see [AuthenticationResult](#authenticationresultdeprecated). | +| number | Authentication result. For details, see [AuthenticationResult](#authenticationresultdeprecated).| **Example** ```js @@ -180,7 +180,7 @@ Performs user authentication. This API uses asynchronous callback to return the execute(type:string, level:string): Promise<number> -> **NOTE**
+> **NOTE**
> This API is not longer maintained since API version 8. You are advised to use [auth](#auth8). Performs user authentication. This API uses a promise to return the result. @@ -192,13 +192,13 @@ Performs user authentication. This API uses a promise to return the result. **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version. | -| level | string | Yes | Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication. | +| type | string | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.| +| level | string | Yes | Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.| **Return value** | Type | Description | | --------------------- | ------------------------------------------------------------ | -| Promise<number> | Promise used to return the authentication result, which is a number. For details, see [AuthenticationResult](#authenticationresultdeprecated). | +| Promise<number> | Promise used to return the authentication result, which is a number. For details, see [AuthenticationResult](#authenticationresultdeprecated).| **Example** @@ -213,7 +213,7 @@ authenticator.execute("FACE_ONLY", "S2").then((code)=>{ ## AuthenticationResult(deprecated) -> **NOTE**
+> **NOTE**
> This parameter is not longer maintained since API version 8. You are advised to use [ResultCode](#resultcode8). Enumerates the authentication results. @@ -222,7 +222,7 @@ Enumerates the authentication results. | Name | Default Value| Description | | ------------------ | ------ | -------------------------- | -| NO_SUPPORT | -1 | The device does not support the current authentication mode. | +| NO_SUPPORT | -1 | The device does not support the current authentication mode.| | SUCCESS | 0 | The authentication is successful. | | COMPARE_FAILURE | 1 | The feature comparison failed. | | CANCELED | 2 | The authentication was canceled by the user. | @@ -230,7 +230,7 @@ Enumerates the authentication results. | CAMERA_FAIL | 4 | The camera failed to start. | | BUSY | 5 | The authentication service is not available. Try again later. | | INVALID_PARAMETERS | 6 | The authentication parameters are invalid. | -| LOCKED | 7 | The user account is locked because the number of authentication failures has reached the threshold. | +| LOCKED | 7 | The user account is locked because the number of authentication failures has reached the threshold.| | NOT_ENROLLED | 8 | No authentication credential is registered. | | GENERAL_ERROR | 100 | Other errors. | @@ -252,7 +252,7 @@ A constructor used to create an **authenticator** object. | Type | Description | | ---------------------- | -------------------- | -| [UserAuth](#userauth8) | **Authenticator** object obtained. | +| [UserAuth](#userauth8) | **Authenticator** object obtained.| **Example** @@ -276,7 +276,7 @@ Obtains the authentication executor version. | Type | Description | | ------ | ---------------------- | -| number | Authentication executor version obtained. | +| number | Authenticator version obtained.| **Example** @@ -302,14 +302,14 @@ Checks whether the authentication capability of the specified trust level is ava | Name | Type | Mandatory| Description | | -------------- | ---------------------------------- | ---- | -------------------------- | -| authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported. | +| authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported.| | authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level of the authentication result. | **Return value** | Type | Description | | ------ | ------------------------------------------------------------ | -| number | Whether the authentication capability of the specified trust level is available. For details, see [ResultCode](#resultcode8). | +| number | Whether the authentication capability of the specified trust level is available. For details, see [ResultCode](#resultcode8).| **Example** @@ -342,7 +342,7 @@ Performs user authentication. This API uses a callback to return the result. | Name | Type | Mandatory| Description | | -------------- | ---------------------------------------- | ---- | ------------------------ | | challenge | Uint8Array | Yes | Challenge value, which can be null. | -| authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported. | +| authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported.| | authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level. | | callback | [IUserAuthCallback](#iuserauthcallback8) | Yes | Callback used to return the result. | @@ -350,7 +350,7 @@ Performs user authentication. This API uses a callback to return the result. | Type | Description | | ---------- | ------------------------------------------------------------ | -| Uint8Array | ContextId, which is used as the input parameter of [cancelAuth](#cancelauth8). | +| Uint8Array | ContextId, which is used as the input parameter of [cancelAuth](#cancelauth8).| **Example** @@ -389,13 +389,13 @@ Cancels an authentication. | Name | Type | Mandatory| Description | | --------- | ---------- | ---- | ------------------------------------------ | -| contextID | Uint8Array | Yes | Context ID, which is obtained using [auth](#auth8). | +| contextID | Uint8Array | Yes | Context ID, which is obtained using [auth](#auth8).| **Return value** | Type | Description | | ------ | ------------------------ | -| number | Whether the authentication is canceled. | +| number | Whether the authentication is canceled.| **Example** @@ -429,7 +429,7 @@ Obtains the authentication result. | Name | Type | Mandatory| Description | | --------- | -------------------------- | ---- | ------------------------------------------------------------ | | result | number | Yes | Authentication result obtained. For details, see [ResultCode](#resultcode8). | -| extraInfo | [AuthResult](#authresult8) | Yes | Extended information, which varies depending on the authentication result.
If the authentication is successful, the user authentication token will be returned in **extraInfo**.
If the authentication fails, the remaining number of authentication times will be returned in **extraInfo**.
If the authentication executor is locked, the freeze time will be returned in **extraInfo**. | +| extraInfo | [AuthResult](#authresult8) | Yes | Extended information, which varies depending on the authentication result.
If the authentication is successful, the user authentication token will be returned in **extraInfo**.
If the authentication fails, the remaining number of authentication times will be returned in **extraInfo**.
If the authentication executor is locked, the freeze time will be returned in **extraInfo**.| **Example** @@ -443,7 +443,7 @@ Obtains the authentication result. try { console.info("auth onResult result = " + result); console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == SUCCESS) { + if (result == userIAM_userAuth.ResultCode.SUCCESS) { // Add the logic to be executed when the authentication is successful. } else { // Add the logic to be executed when the authentication fails. @@ -478,7 +478,7 @@ Obtains the tip code information during authentication. This function is optiona | Name | Type | Mandatory| Description | | --------- | ------ | ---- | ------------------------------ | | module | number | Yes | Type of the authentication executor. | -| acquire | number | Yes | Interaction information of the authentication executor during the authentication process. | +| acquire | number | Yes | Interaction information of the authentication executor during the authentication process.| | extraInfo | any | Yes | Reserved field. | **Example** @@ -492,7 +492,7 @@ Obtains the tip code information during authentication. This function is optiona try { console.info("auth onResult result = " + result); console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == SUCCESS) { + if (result == userIAM_userAuth.ResultCode.SUCCESS) { // Add the logic to be executed when the authentication is successful. } else { // Add the logic to be executed when the authentication fails. @@ -523,8 +523,8 @@ Represents the authentication result object. | Name | Type | Mandatory| Description | | ------------ | ---------- | ---- | -------------------- | | token | Uint8Array | No | Identity authentication token. | -| remainTimes | number | No | Number of remaining authentication operations. | -| freezingTime | number | No | Time for which the authentication operation is frozen. | +| remainTimes | number | No | Number of remaining authentication operations.| +| freezingTime | number | No | Time for which the authentication operation is frozen.| ## ResultCode8+ @@ -544,7 +544,7 @@ Enumerates the operation results. | BUSY | 7 | Indicates the busy state. | | INVALID_PARAMETERS | 8 | Invalid parameters are detected. | | LOCKED | 9 | The authentication executor is locked. | -| NOT_ENROLLED | 10 | The user has not entered the authentication information. | +| NOT_ENROLLED | 10 | The user has not entered the authentication information.| ## FaceTips8+ @@ -563,7 +563,7 @@ Enumerates the tip codes used during the facial authentication process. | FACE_AUTH_TIP_TOO_LOW | 6 | Only the lower part of the face is captured because the device is angled too low. | | FACE_AUTH_TIP_TOO_RIGHT | 7 | Only the right part of the face is captured because the device is deviated to the right. | | FACE_AUTH_TIP_TOO_LEFT | 8 | Only the left part of the face is captured because the device is deviated to the left. | -| FACE_AUTH_TIP_TOO_MUCH_MOTION | 9 | The face moves too fast during facial information collection. | +| FACE_AUTH_TIP_TOO_MUCH_MOTION | 9 | The face moves too fast during facial information collection.| | FACE_AUTH_TIP_POOR_GAZE | 10 | The face is not facing the camera. | | FACE_AUTH_TIP_NOT_DETECTED | 11 | No face is detected. | @@ -577,7 +577,7 @@ Enumerates the tip codes used during the fingerprint authentication process. | Name | Default Value| Description | | --------------------------------- | ------ | -------------------------------------------------- | | FINGERPRINT_AUTH_TIP_GOOD | 0 | The obtained fingerprint image is in good condition. | -| FINGERPRINT_AUTH_TIP_DIRTY | 1 | Large fingerprint image noise is detected due to suspicious or detected dirt on the sensor. | +| FINGERPRINT_AUTH_TIP_DIRTY | 1 | Large fingerprint image noise is detected due to suspicious or detected dirt on the sensor.| | FINGERPRINT_AUTH_TIP_INSUFFICIENT | 2 | The noise of the fingerprint image is too large to be processed. | | FINGERPRINT_AUTH_TIP_PARTIAL | 3 | Incomplete fingerprint image is detected. | | FINGERPRINT_AUTH_TIP_TOO_FAST | 4 | The fingerprint image is incomplete due to fast movement. | @@ -592,8 +592,8 @@ Enumerates the identity authentication types. | Name | Default Value| Description | | ----------- | ------ | ---------- | -| FACE | 2 | Facial authentication. | -| FINGERPRINT | 4 | Fingerprint authentication. | +| FACE | 2 | Facial authentication.| +| FINGERPRINT | 4 | Fingerprint authentication.| ## AuthTrustLevel8+ @@ -603,7 +603,7 @@ Enumerates the trust levels of the authentication result. | Name| Default Value| Description | | ---- | ------ | ------------------------- | -| ATL1 | 10000 | Trust level 1. | -| ATL2 | 20000 | Trust level 2. | -| ATL3 | 30000 | Trust level 3. | -| ATL4 | 40000 | Trust level 4. | +| ATL1 | 10000 | Trust level 1.| +| ATL2 | 20000 | Trust level 2.| +| ATL3 | 30000 | Trust level 3.| +| ATL4 | 40000 | Trust level 4.| diff --git a/en/application-dev/reference/apis/js-apis-wantAgent.md b/en/application-dev/reference/apis/js-apis-wantAgent.md index f54e0769783406311f1127adc6891d7d997c5b51..dac99ebed30a69168c24d3c168aa27dd98eab0c9 100644 --- a/en/application-dev/reference/apis/js-apis-wantAgent.md +++ b/en/application-dev/reference/apis/js-apis-wantAgent.md @@ -914,7 +914,7 @@ WantAgent.equal(wantAgent1, wantAgent2).then((data) => { }); ``` -## WantAgent.getOperationType +## WantAgent.getOperationType9+ getOperationType(agent: WantAgent, callback: AsyncCallback\): void; @@ -975,7 +975,7 @@ WantAgent.getOperationType(wantAgent, (OperationType) => { }) ``` -## WantAgent.getOperationType +## WantAgent.getOperationType9+ getOperationType(agent: WantAgent): Promise\; diff --git a/en/application-dev/reference/apis/js-apis-webSocket.md b/en/application-dev/reference/apis/js-apis-webSocket.md index edf6be53ac623c5fa4a8f1542bf7222dc42e713c..52f5367110bc35c33075ed291a796a657a468816 100644 --- a/en/application-dev/reference/apis/js-apis-webSocket.md +++ b/en/application-dev/reference/apis/js-apis-webSocket.md @@ -23,7 +23,7 @@ import webSocket from '@ohos.net.webSocket'; var defaultIpAddress = "ws://"; let ws = webSocket.createWebSocket(); ws.on('open', (err, value) => { - console.log("on open, status:" + value.status + ", message:" + value.message); + console.log("on open, status:" + value['status'] + ", message:" + value['message']); // When receiving the on('open') event, the client can use the send() API to communicate with the server. ws.send("Hello, server!", (err, value) => { if (!err) { @@ -47,7 +47,7 @@ ws.on('message', (err, value) => { } }); ws.on('close', (err, value) => { - console.log("on close, code is " + value.code + ", reason is " + value.reason); + console.log("on close, code is " + value['code'] + ", reason is " + value['reason']); }); ws.on('error', (err) => { console.log("on error, error:" + JSON.stringify(err)); @@ -393,7 +393,7 @@ Enables listening for the **open** events of a WebSocket connection. This API us ```js let ws = webSocket.createWebSocket(); ws.on('open', (err, value) => { - console.log("on open, status:" + value.status + ", message:" + value.message); + console.log("on open, status:" + value['status'] + ", message:" + value['message']); }); ``` @@ -421,7 +421,7 @@ Disables listening for the **open** events of a WebSocket connection. This API u ```js let ws = webSocket.createWebSocket(); let callback1 = (err, value) => { - console.log("on open, status:" + value.status + ", message:" + value.message); + console.log("on open, status:" + value['status'] + ", message:" + value['message']); } ws.on('open', callback1); // You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. @@ -505,7 +505,7 @@ Enables listening for the **close** events of a WebSocket connection. This API u ```js let ws = webSocket.createWebSocket(); ws.on('close', (err, value) => { - console.log("on close, code is " + value.code + ", reason is " + value.reason); + console.log("on close, code is " + value['code'] + ", reason is " + value['reason']); }); ``` diff --git a/en/application-dev/reference/arkui-js/js-components-media-video.md b/en/application-dev/reference/arkui-js/js-components-media-video.md index 1e2b132c923351e37d92eafeea3bf71ef34d3fb1..b957ee6d968a2a4b038c4d600d7ea6adef966b40 100644 --- a/en/application-dev/reference/arkui-js/js-components-media-video.md +++ b/en/application-dev/reference/arkui-js/js-components-media-video.md @@ -1,240 +1,134 @@ -# video +# video -The **** component provides a video player. ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->- Configure the following information in the **config.json** file: -> ``` -> "configChanges": ["orientation"] -> ``` +> **NOTE**
+> +> - This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. +> +> - Set **configChanges** under **abilities** in the **config.json** file to **orientation**. +> ``` +> "abilities": [ +> { +> "configChanges": ["orientation"], +> ... +> } +> ] +> ``` -## Required Permissions +The **\