diff --git a/CODEOWNERS b/CODEOWNERS index 3598264d0126154e0a84838f393fb3864f493dd7..9af770d1479e48dd04bb67c28b33f2b39d9b2c68 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -200,9 +200,9 @@ zh-cn/application-dev/reference/apis/js-apis-appmanager.md @littlejerry1 @RayShi zh-cn/application-dev/reference/apis/js-apis-arraylist.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-audio.md @liuyuehua1 @zengyawen @magekkkk @currydavids zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @chenmingJay @ningningW @nan-xiansen @iceice1001 -zh-cn/application-dev/reference/apis/js-apis-battery-info.md @aqxyjay @zengyawen @aqxyjay @alien0208 +zh-cn/application-dev/reference/apis/js-apis-battery-info.md @zengyawen @alien0208 zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @cheng_guohong @RayShih @cheng_guohong @quanli125 -zh-cn/application-dev/reference/apis/js-apis-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208 +zh-cn/application-dev/reference/apis/js-apis-brightness.md @zengyawen @alien0208 zh-cn/application-dev/reference/apis/js-apis-buffer.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md @shuaytao @RayShih @wangzhen107 @inter515 @@ -322,7 +322,7 @@ zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @han-zhengshi @ge-yaf zh-cn/application-dev/reference/apis/js-apis-permissionrequestresult.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-plainarray.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-pointer.md @yuanxinying @ningningW @cococoler @alien0208 -zh-cn/application-dev/reference/apis/js-apis-power.md @aqxyjay @zengyawen @aqxyjay @alien0208 +zh-cn/application-dev/reference/apis/js-apis-power.md @zengyawen @alien0208 zh-cn/application-dev/reference/apis/js-apis-privacyManager.md @nianCode @zengyawen @shuqinglin2 @jinhaihw zh-cn/application-dev/reference/apis/js-apis-process.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-processrunninginfo.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen @@ -335,7 +335,7 @@ zh-cn/application-dev/reference/apis/js-apis-request.md @feng-aiwen @ningningW @ zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @Buda-Liu @ningningW @mengjingzhimo @yangqing3 zh-cn/application-dev/reference/apis/js-apis-router.md @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-rpc.md @xuepianpian @RayShih @zhaopeng_gitee @vagrant_world -zh-cn/application-dev/reference/apis/js-apis-runninglock.md @aqxyjay @zengyawen @aqxyjay @alien0208 +zh-cn/application-dev/reference/apis/js-apis-runninglock.md @zengyawen @alien0208 zh-cn/application-dev/reference/apis/js-apis-screen.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee @nobuggers zh-cn/application-dev/reference/apis/js-apis-screenshot.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee @nobuggers zh-cn/application-dev/reference/apis/js-apis-securityLabel.md @panqinxu @zengyawen @bubble_mao @jinhaihw @@ -350,9 +350,9 @@ zh-cn/application-dev/reference/apis/js-apis-stack.md @gongjunsong @ge-yafang @f zh-cn/application-dev/reference/apis/js-apis-statfs.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-storage-statistics.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-system-app.md @HelloCrease @niulihua @tomatodevboy -zh-cn/application-dev/reference/apis/js-apis-system-battery.md @aqxyjay @zengyawen @aqxyjay @alien0208 +zh-cn/application-dev/reference/apis/js-apis-system-battery.md @zengyawen @alien0208 zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md @cheng_guohong @RayShih @cheng_guohong @quanli125 -zh-cn/application-dev/reference/apis/js-apis-system-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208 +zh-cn/application-dev/reference/apis/js-apis-system-brightness.md @zengyawen @alien0208 zh-cn/application-dev/reference/apis/js-apis-system-cipher.md @gaoyong @zengyawen @niejiteng @jumozhanjiang zh-cn/application-dev/reference/apis/js-apis-system-configuration.md @Buda-Liu @ningningW @budda-wang @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-system-date-time.md @feng-aiwen @ningningW @illybyy @murphy1984 @@ -375,7 +375,7 @@ zh-cn/application-dev/reference/apis/js-apis-system-timer.md @feng-aiwen @ningni zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md @hellohyh001 @ningningW @butterls @star-wind-snow-and-rain zh-cn/application-dev/reference/apis/js-apis-telephony-data.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-testRunner.md @inter515 @littlejerry1 @RayShih @inter515 @jiyong -zh-cn/application-dev/reference/apis/js-apis-thermal.md @aqxyjay @zengyawen @aqxyjay @alien0208 +zh-cn/application-dev/reference/apis/js-apis-thermal.md @zengyawen @alien0208 zh-cn/application-dev/reference/apis/js-apis-timer.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-touchevent.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-shortKey.md @mayunteng_1 @ningningW @cococoler @alien0208 @@ -426,7 +426,7 @@ zh-cn/application-dev/reference/apis/js-apis-application-configuration.md @littl zh-cn/application-dev/reference/apis/js-apis-application-configurationConstant.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-application-quickFixManager.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-avsession.md @liuyuehua1 @zengyawen @saga2020 @currydavids -zh-cn/application-dev/reference/apis/js-apis-batteryStatistics.md @aqxyjay @zengyawen @aqxyjay @alien0208 +zh-cn/application-dev/reference/apis/js-apis-batteryStatistics.md @zengyawen @alien0208 zh-cn/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-bundleManager-abilityInfo.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-bundleManager-applicationInfo.md @shuaytao @RayShih @wangzhen107 @inter515 diff --git a/en/application-dev/ability-deprecated/Readme-EN.md b/en/application-dev/ability-deprecated/Readme-EN.md deleted file mode 100644 index 5c803a47558bbd52765090debe162dbecd996ae6..0000000000000000000000000000000000000000 --- a/en/application-dev/ability-deprecated/Readme-EN.md +++ /dev/null @@ -1,25 +0,0 @@ -# Ability Development - -> **NOTE**
-> This folder is deprecated. Read [Application Models](../application-models/Readme-EN.md) instead. - -- [Ability Framework Overview](ability-brief.md) -- [Context Usage](context-userguide.md) -- FA Model - - [FA Model Overview](fa-brief.md) - - [Page Ability Development](fa-pageability.md) - - [Service Ability Development](fa-serviceability.md) - - [Data Ability Development](fa-dataability.md) - - [FA Widget Development](fa-formability.md) -- Stage Model - - [Stage Model Overview](stage-brief.md) - - [Ability Development](stage-ability.md) - - [Service Extension Ability Development](stage-serviceextension.md) - - [Ability Continuation Development](stage-ability-continuation.md) - - [Ability Call Development](stage-call.md) - - [Stage Widget Development](stage-formextension.md) -- Other - - [WantAgent Development](wantagent.md) - - [Ability Assistant Usage](ability-assistant-guidelines.md) - - [ContinuationManager Development](continuationmanager.md) - - [Test Framework Usage](ability-delegator.md) diff --git a/en/application-dev/ability-deprecated/ability-assistant-guidelines.md b/en/application-dev/ability-deprecated/ability-assistant-guidelines.md deleted file mode 100644 index d2e45f5d5492c23bcce0ec48674427df2cb2b765..0000000000000000000000000000000000000000 --- a/en/application-dev/ability-deprecated/ability-assistant-guidelines.md +++ /dev/null @@ -1,107 +0,0 @@ -# Ability Assistant Usage - -The ability assistant enables you to start applications, atomic services, and test cases and debug applications. By using this tool, you can send commands in the hdc shell to perform various system operations, such as starting abilities, forcibly stopping processes, and printing ability information. - -## Query-related Commands - -- **help** - - Displays help information for the ability assistant. - - **Return value** - - Returns the help information. - - **Method** - - ``` - aa help - ``` - -## Ability-related Commands - -- **start** - - Starts an ability. - - | Name | Description | - | --------- | -------------------------- | - | -h/--help | Help information. | - | -d | Device ID. This parameter is optional. | - | -a | Ability name. This parameter is mandatory.| - | -b | Bundle name. This parameter is mandatory. | - | -D | Debugging mode. This parameter is optional. | - - **Return value** - - Returns "start ability successfully." if the ability is started; returns "error: failed to start ability." otherwise. - - **Method** - - ``` - aa start [-d ] -a -b [-D] - ``` - -- **stop-service** - - Stops a Service ability. - - | Name | Description | - | --------- | ------------------------ | - | -h/--help | Help information. | - | -d | Device ID. This parameter is optional. | - | -a | Ability name. This parameter is mandatory.| - | -b | Bundle name. This parameter is mandatory. | - - **Return value** - - Returns "stop service ability successfully." if the Service ability is stopped; returns "error: failed to stop service ability." otherwise. - - **Method** - - ``` - aa stop-service [-d ] -a -b - ``` - -- **dump** - - Prints ability-related information. - - | Name | Level-2 Parameter | Description | - | ----------------- | -------------------- | ------------------------------------------------------------ | - | -h/--help | - | Prints help information. | - | -a/--all | - | Prints ability information in all missions. | - | -l/--mission-list | type (All logs are printed if this parameter is left unspecified.)| Prints mission stack information.
The following values are available for **type**:
- NORMAL
- DEFAULT_STANDARD
- DEFAULT_SINGLE
- LAUNCHER | - | -e/--extension | elementName | Prints extended component information. | - | -u/--userId | UserId | Prints stack information of a specified user ID. This parameter must be used together with other parameters.
Example commands: aa **dump -a -u 100** and **aa dump -d -u 100**.| - | -d/--data | - | Prints Data ability information. | - | -i/--ability | AbilityRecord ID | Prints detailed information about a specified ability. | - | -c/--client | - | Prints detailed ability information. This parameter must be used together with other parameters.
Example commands: **aa dump -a -c** and **aa dump -i 21 -c**.| - - **Method** - - ``` - aa dump -a - ``` - ![aa-dump-a](figures/aa-dump-a.PNG) - ``` - aa dump -l - ``` - ![aa-dump-l](figures/aa-dump-l.PNG) - ``` - aa dump -i 12 - ``` - ![aa-dump-i](figures/aa-dump-i.PNG) -- **force-stop** - - Forcibly stops a process based on the bundle name. - - **Return value** - - Returns "force stop process successfully." if the process is forcibly stopped; returns "error: failed to force stop process." otherwise. - - **Method** - - ``` - aa force-stop - ``` diff --git a/en/application-dev/ability-deprecated/ability-brief.md b/en/application-dev/ability-deprecated/ability-brief.md deleted file mode 100644 index 867e2c750a7d98b7964b037dcb809954fb5b40fb..0000000000000000000000000000000000000000 --- a/en/application-dev/ability-deprecated/ability-brief.md +++ /dev/null @@ -1,34 +0,0 @@ -# Ability Framework Overview - -Ability is the basic abstraction of applications in OpenHarmony. - -Each ability is an application component that provides an independent service and is the minimum unit for the system to schedule an application. An application can contain one or more **Ability** instances. - -The ability framework model has two forms: - -- FA model, which is available for application development using API version 8 and earlier versions. In the FA model, there are PageAbility, ServiceAbility, DataAbility, and FormAbility. -- Stage model, which is introduced since API version 9. In the stage model, there are two classes: UIAbility and ExtensionAbility. ExtensionAbility is further extended to ServiceExtensionAbility, FormExtensionAbility, DataShareExtensionAbility, and more. - -Starting from API version 9, the stage model is recommended. - -The stage model is designed to make it easier to develop complex applications in the distributed environment. The table below lists the design differences between the two models. - -| Item | FA Model | Stage Model | -| -------------- | ------------------------------------------------------------ | -------------------------------------------------------- | -| Application component development mode | Web-like development | Object-oriented development | -| Engine instance | Each **Ability** instance exclusively occupies a VM instance. | Multiple **Ability** instances share a VM instance. | -| Intra-process object sharing| Not supported | Supported | -| Bundle description file | The **config.json** file is used to describe the HAP and component information. Each component must use a fixed file name.| The **module.json5** file is used to describe the HAP and component information. The entry file name can be specified.| -| Component | Four types of components are provided: PageAbility (used for UI page display), ServiceAbility (used to provide services), DataAbility (used for data sharing), and FormAbility (used to provide widgets).| Two types of components are provided: UIAbility (used for UI page display) and ExtensionAbility (scenario-based service extension). | - -In addition, the following differences exist in the development process: - -* Different ability types - - ![favsstage](figures/favsstage.png) - -* Different ability lifecycles - - ![lifecycle](figures/lifecycle.png) - -For details about the two models, see [FA Model Overview](fa-brief.md) and [Stage Model Overview](stage-brief.md). diff --git a/en/application-dev/ability-deprecated/ability-delegator.md b/en/application-dev/ability-deprecated/ability-delegator.md deleted file mode 100644 index b32d472176a5b6270fece94ae4bd8ae9a7bd73fa..0000000000000000000000000000000000000000 --- a/en/application-dev/ability-deprecated/ability-delegator.md +++ /dev/null @@ -1,181 +0,0 @@ -# Test Framework Usage - -## Overview -The delegator test framework provides a self-test environment for OpenHarmony applications. Using this framework, you can start an ability, schedule its lifecycle, listen for its state changes, run a shell command, and print the test result. - -## Constraints - -The APIs provided by the test framework can be used only in the test HAP. They take effect only after the test framework is started. - - -## Starting the Test Framework - -The test framework can be started in either of the following ways: - -- Method 1: Run the `aa test` command. -- Method 2: Use DevEco Studio. - -### Running aa test - -To start the test framework, specify the **TestRunner** and the package name or module name of the HAP where the **TestRunner** is located. - -An example command in the FA model is as follows: - -```javascript -aa test -b BundleName -p com.example.myapplicationfaets -s unittest OpenHarmonyTestRunner -s class ActsAbilityTest -w 20 -``` - -An example command in the stage model is as follows: -```javascript -aa test -b BundleName -m com.example.myapplicationfaets -s unittest OpenHarmonyTestRunner -s class ActsAbilityTest -w 20 -``` -| Parameter | Mandatory| Description | -| --------------- | -------- | ------------------------------------------------------------ | -| -b | Yes | Bundle name of the HAP where the **TestRunner** is located. | -| -p | Yes | Package name of the HAP where the **TestRunner** is located. This parameter is used by the FA model. | -| -m | Yes | Module name of the HAP where the **TestRunner** is located. This parameter is used by the stage model. | -| -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.| - -### Using DevEco Studio - -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, 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-application-testRunner.md). - -## Introduction to AbilityDelegatorRegistry - -**AbilityDelegatorRegistry** is the **AbilityDelegator** repository class provided by the test framework. You can use **AbilityDelegatorRegistry** to obtain an **AbilityDelegator** instance and the input and generated parameters **AbilityDelegatorArgs** during the test. You can use **AbilityDelegator** to invoke the function set provided by the test framework for testing and verification. For details, see [AbilityDelegatorRegistry](../reference/apis/js-apis-application-abilityDelegatorRegistry.md). - -## Introduction to AbilityDelegatorArgs - -**AbilityDelegatorArgs** is a test parameter class provided by the test framework. You can use **AbilityDelegatorArgs** to obtain the parameters passed and generated during the test. For details, see [AbilityDelegatorArgs](../reference/apis/js-apis-inner-application-abilityDelegatorArgs.md). - -## Introduction to AbilityMonitor - -**AbilityMonitor** is provided by the test framework for binding to and listening for abilities. You can use **AbilityMonitor** to bind to an **Ability** instance and add **AbilityMonitor** to the listening list. When **AbilityMonitor** is bound to an ability, the creation and lifecycle changes of the ability will trigger the related callback in **AbilityMonitor**. You can test and verify the ability in these callbacks. For details, see [AbilityMonitor](../reference/apis/js-apis-inner-application-abilityMonitor.md). - -**Example** - -```javascript -import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' - -function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); -} - -var monitor = { - abilityName: "abilityname", - onAbilityCreate: onAbilityCreateCallback -} - -var abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); -abilityDelegator.addAbilityMonitor(monitor).then(() => { - console.info("addAbilityMonitor promise"); -}); -``` - -## Introduction to AbilityDelegator - -**AbilityDelegator** is a main function class of the test framework. It provides the functions of starting an ability, obtaining an **Ability** instance, scheduling the ability lifecycle, listening for the ability state, and printing test results. - -**Modules to Import** - -```javascript -import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' -``` - -```javascript -var abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator() -``` - -### Starting an Ability and Listening for the Ability State - -Use **AbilityDelegator** and **AbilityMonitor** to start an ability, obtain an **Ability** instance, and listen for the ability state. - -**Example** - -```javascript -var abilityDelegator; -var ability; -var timeout = 100; - -function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); -} - -var monitor = { - abilityName: "abilityname", - onAbilityCreate: onAbilityCreateCallback -} - -abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); -abilityDelegator.waitAbilityMonitor(monitor, timeout, (err, data) => { - ability = data; - console.info("waitAbilityMonitor callback"); -}); - -var want = { - bundleName: "bundleName", - abilityName: "abilityName" -}; -abilityDelegator.startAbility(want, (err, data) => { - console.info("startAbility callback"); -}); -``` - -### Scheduling the Ability Lifecycle - -**AbilityDelegator** provides APIs to display and schedule the ability lifecycle and supports the foreground and background. It works with **AbilityMonitor** to listen for the ability lifecycle. For details, see [AbilityDelegator](../reference/apis/js-apis-inner-application-abilityDelegator.md). - -### Running a Shell Command - -**AbilityDelegator** provides APIs to run shell commands in the test environment. - -**Example** - -```javascript -var abilityDelegator; -var cmd = "cmd"; -abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); -abilityDelegator.executeShellCommand(cmd, (err, data) => { - console.info("executeShellCommand callback"); -}); -``` - -### 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 -var abilityDelegator; -var msg = "msg"; - -abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); -abilityDelegator.print(msg, (err) => { - console.info("print callback"); -}); -``` - -### 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 -var abilityDelegator; -var msg = "msg"; - -abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); -abilityDelegator.finishTest(msg, 0, (err) => { - console.info("finishTest callback"); -}); -``` diff --git a/en/application-dev/ability-deprecated/context-userguide.md b/en/application-dev/ability-deprecated/context-userguide.md deleted file mode 100644 index 79cae1da5611b0736f7d11a5bb0cfb9b48df3f0a..0000000000000000000000000000000000000000 --- a/en/application-dev/ability-deprecated/context-userguide.md +++ /dev/null @@ -1,319 +0,0 @@ -# Context Usage - -## Context Overview - -**Context** provides the capability of obtaining contextual information of an application. - -The OpenHarmony application framework has two models: Feature Ability (FA) model and stage model. Correspondingly, there are two sets of context mechanisms. **application/BaseContext** is a common context base class. It uses the **stageMode** attribute to specify whether the context is used for the stage model. - -- FA model - - Only the methods in **app/Context** can be used for the context in the FA model. Both the application-level context and ability-level context are instances of this type. If an ability-level method is invoked in the application-level context, an error occurs. Therefore, you must pay attention to the actual meaning of the **Context** instance. - -- Stage model - - The stage model has the following types of contexts: **application/Context**, **application/ApplicationContext**, **application/AbilityStageContext**, **application/ExtensionContext**, **application/AbilityContext**, and **application/FormExtensionContext**. For details about these contexts and how to use them, see [Context in the Stage Model](#context-in-the-stage-model). - -![contextIntroduction](figures/contextIntroduction.png) - -## Context in the FA Model - -Only the methods in **app/Context** can be used for the context in the FA model. - -The FA model has only one context definition. All capabilities in the context are provided through methods. The context uses these methods to extend the capabilities of the FA. - -**d.ts statement** - -https://gitee.com/openharmony/interface_sdk-js/blob/master/api/app/context.d.ts - -**Example** - -```javascript -import featureAbility from '@ohos.ability.featureAbility' -export default { - onCreate() { - // Obtain the context and call related APIs. - let context = featureAbility.getContext(); - context.getBundleName((data, bundleName)=>{ - console.info("ability bundleName:" + bundleName) - }); - console.info('Application onCreate') - }, - onDestroy() { - console.info('Application onDestroy') - }, -} -``` - -### Common Context-related Methods in the FA Model -The following context-related methods are available in the FA model: -```javascript -setDisplayOrientation(orientation: bundle.DisplayOrientation, callback: AsyncCallback): void -setDisplayOrientation(orientation: bundle.DisplayOrientation): Promise; -``` -The methods are used to set the display orientation of the current ability. - -**Example** - -```javascript -import featureAbility from '@ohos.ability.featureAbility' -import bundle from '@ohos.bundle'; - -export default { - onCreate() { - // Obtain the context and call related APIs. - let context = featureAbility.getContext(); - context.setDisplayOrientation(bundle.DisplayOrientation.LANDSCAPE).then(() => { - console.log("Set display orientation.") - }) - console.info('Application onCreate') - }, - onDestroy() { - console.info('Application onDestroy') - }, -} -``` - -## Context in the Stage Model - -The following describes the contexts provided by the stage model in detail. - -### application/Context - -**application/Context** is the base class context. It provides basic application information, such as **resourceManager**, **applicationInfo**, **cacheDir**, and **area**. It also provides basic application methods such as **createModuleContext**. - -**d.ts statement** - -https://gitee.com/openharmony/interface_sdk-js/blob/master/api/application/Context.d.ts - -### application/ApplicationContext - -**application/ApplicationContext** is an application-level context. In addition to the capabilities provided by the base class context, the application-level context provides **registerAbilityLifecycleCallback** and **unregisterAbilityLifecycleCallback** to monitor the ability lifecycle in a process. - -**How to Obtain** - -Obtain the context by calling **context.getApplicationContext()** in **Ability**. - -**Example** - -```javascript -import UIAbility from '@ohos.app.ability.UIAbility'; - -var lifecycleid; - -export default class EntryAbility extends UIAbility { - onCreate() { - console.log("EntryAbility onCreate") - let AbilityLifecycleCallback = { - onAbilityCreate(ability){ - console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability)); - }, - onWindowStageCreate(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageCreate ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); - }, - onWindowStageActive(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageActive ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageActive windowStage:" + JSON.stringify(windowStage)); - }, - onWindowStageInactive(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageInactive ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageInactive windowStage:" + JSON.stringify(windowStage)); - }, - onWindowStageDestroy(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageDestroy ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageDestroy windowStage:" + JSON.stringify(windowStage)); - }, - 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 and listen 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)); - }); - } -} -``` - -**d.ts statement** - -https://gitee.com/openharmony/interface_sdk-js/blob/master/api/application/ApplicationContext.d.ts - -### application/AbilityStageContext - -**application/AbilityStageContext** is the context for the HAP file. In addition to those provided by the base class **application/Context**, this context contains **HapModuleInfo** and **Configuration**. - -**How to Obtain** - -Obtain the context from the **context** attribute in **AbilityStage**. - -**Example** - -```javascript -export default class MyAbilityStage extends AbilityStage { - onCreate() { - // The context attribute is of the AbilityStageContext type. - console.log('HapModuleInfo is ' + this.context.currentHapModuleInfo); - } -} -``` - -**d.ts statement** - -https://gitee.com/openharmony/interface_sdk-js/blob/master/api/application/AbilityStageContext.d.ts - -### application/AbilityContext - -In the stage model, each ability has a context attribute. - -**Ability** provides methods to manage the ability lifecycle, and **AbilityContext** provides methods to operate abilities (such as **startAbility** and **connectAbility**). - -**How to Obtain** - -Obtain the context from the **context** attribute in **Ability**. - -**Example** - -```javascript -import UIAbility from '@ohos.app.ability.UIAbility'; - -export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - console.log("[Demo] EntryAbility onCreate") - globalThis.abilityWant = want; - } - - onDestroy() { - console.log("[Demo] EntryAbility onDestroy") - } - - onWindowStageCreate(windowStage) { - // Set the main page for this ability when the main window is created. - console.log("[Demo] EntryAbility onWindowStageCreate") - - // Obtain AbilityContext and print the ability information. - let context = this.context; - console.log("[Demo] EntryAbility bundleName " + context.abilityInfo.bundleName) - - windowStage.loadContent("pages/index", (err, data) => { - if (err.code) { - console.error('Failed to load the content. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)) - }); - } - - onWindowStageDestroy() { - // Release the UI related resources when the main window is destroyed. - console.log("[Demo] EntryAbility onWindowStageDestroy") - } - - onForeground() { - // The ability is switched to run in the foreground. - console.log("[Demo] EntryAbility onForeground") - } - - onBackground() { - // The ability is switched to run in the background. - console.log("[Demo] EntryAbility onBackground") - } -}; -``` - -### application/FormExtensionContext - -For details, see [FormExtensionContext](../reference/apis/js-apis-inner-application-formExtensionContext.md). - -### Obtaining the Context on an ArkTS Page - -In the stage model, in the onWindowStageCreate lifecycle of an ability, you can call **SetUIContent** of **WindowStage** to load an ArkTS page. In some scenarios, you need to obtain the context on the page to call related APIs. - -**How to Obtain** - -Use the API described in the table below to obtain the context associated with an ArkTS page. - -| API | Description | -| :------------------------------------ | :----------------------------------------------------------- | -| getContext(component: Object): Object | Obtains the **Context** object associated with a component on the page.
Since API version 9, this API is supported in ArkTS widgets.| - -**Example** - -```ts -// EntryAbility.ts -import UIAbility from '@ohos.app.ability.UIAbility'; - -export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - console.log("[Demo] EntryAbility onCreate") - } - - onDestroy() { - console.log("[Demo] EntryAbility onDestroy") - } - - onWindowStageCreate(windowStage) { - // Load the index page and pass the current Context object. - windowStage.setUIContent(this.context, "pages/index", null) - } - - onWindowStageDestroy() {} - - onForeground() {} - - onBackground() {} -}; -``` - -```ts -// pages/index.ets -import context from '@ohos.app.ability.context' - -type Context = context.Context - -@Entry -@Component -struct Index { - build() { - Row() { - Column() { - Text('GetContext') - .fontSize(50) - .fontWeight(FontWeight.Bold) - .onClick(() => { - // Obtain the Context object associated with the current component. - var context : Context = getContext(this) as Context - console.info("CacheDir:" + context.cacheDir) - }) - } - .width('100%') - } - .height('100%') - } -} -``` - -## Common Incorrect Usage - -**Error 1: Use globalThis to obtain the context in the stage model.** - -**Reason** - -In the FA model, each ability instance has a JS VM instance. Therefore, a global ability instance can be obtained from the **global** object of the JS engine. In the stage model, where all the processes of an application share a JS VM instance, there is no global ability instance, and using **globalThis** may cause an error or crash. diff --git a/en/application-dev/ability-deprecated/continuationmanager.md b/en/application-dev/ability-deprecated/continuationmanager.md deleted file mode 100644 index 12db9781c5a5f6548be98f27a426e8a3be354ae9..0000000000000000000000000000000000000000 --- a/en/application-dev/ability-deprecated/continuationmanager.md +++ /dev/null @@ -1,277 +0,0 @@ -# ContinuationManager Development - -> **NOTE** -> -> Currently, the **ContinuationManager** module is not available for application development. Its APIs are mainly used to start the device selection module. - -## When to Use -Users are using two or more devices to experience an all-scenario, multi-device lifestyle. Each type of device has its unique advantages and disadvantages specific to scenarios. The ability continuation capability breaks boundaries of devices and enables multi-device collaboration, achieving precise control, universal coordination, and seamless hops of user applications. - -As the entry of the ability continuation capability, **continuationManager** is used to start the device selection module for the user to select the target device. After a device is selected, information about the selected device is returned to the user. The user can then initiate cross-device continuation or collaboration based on the device information. - -![continuationManager](figures/continuationManager.png) - -## Available APIs -| API | Description| -| ---------------------------------------------------------------------------------------------- | ----------- | -| registerContinuation(callback: AsyncCallback\): void | Registers the continuation management service and obtains a token. This API does not involve any filter parameters and uses an asynchronous callback to return the result.| -| registerContinuation(options: ContinuationExtraParams, callback: AsyncCallback\): void | Registers the continuation management service and obtains a token. This API uses an asynchronous callback to return the result.| -| registerContinuation(options?: ContinuationExtraParams): Promise\ | Registers the continuation management service and obtains a token. This API uses a promise to return the result.| -| on(type: "deviceSelected", token: number, callback: Callback\>): void | Subscribes to device connection events. This API uses an asynchronous callback to return the result.| -| on(type: "deviceUnselected", token: number, callback: Callback\>): void | Subscribes to device disconnection events. This API uses an asynchronous callback to return the result.| -| off(type: "deviceSelected", token: number): void | Unsubscribes from device connection events.| -| off(type: "deviceUnselected", token: number): void | Unsubscribes from device disconnection events.| -| startContinuationDeviceManager(token: number, callback: AsyncCallback\): void | Starts the device selection module to show the list of available devices. This API does not involve any filter parameters and uses an asynchronous callback to return the result.| -| startContinuationDeviceManager(token: number, options: ContinuationExtraParams, callback: AsyncCallback\): void | Starts the device selection module to show the list of available devices. This API uses an asynchronous callback to return the result.| -| startContinuationDeviceManager(token: number, options?: ContinuationExtraParams): Promise\ | Starts the device selection module to show the list of available devices. This API uses a promise to return the result.| -| updateContinuationState(token: number, deviceId: string, status: DeviceConnectState, callback: AsyncCallback\): void | Instructs the device selection module to update the device connection state. This API uses an asynchronous callback to return the result.| -| updateContinuationState(token: number, deviceId: string, status: DeviceConnectState): Promise\ | Instructs the device selection module to update the device connection state. This API uses a promise to return the result.| -| unregisterContinuation(token: number, callback: AsyncCallback\): void | Deregisters the continuation management service. This API uses an asynchronous callback to return the result.| -| unregisterContinuation(token: number): Promise\ | Deregisters the continuation management service. This API uses a promise to return the result.| - -## How to Develop -1. Import the **continuationManager** module. - - ```ts - import continuationManager from '@ohos.continuation.continuationManager'; - ``` - -2. Apply for the **DISTRIBUTED_DATASYNC** permission. - - The permission application operation varies according to the ability model in use. In the FA mode, add the required permission in the `config.json` file, as follows: - - ```json - { - "module": { - "reqPermissions": [ - { - "name": "ohos.permission.DISTRIBUTED_DATASYNC" - } - ] - } - } - ``` - - This permission must also be granted by the user through a dialog box when the application is started for the first time. The sample code is as follows: - - ```ts - import abilityAccessCtrl from "@ohos.abilityAccessCtrl"; - import bundle from '@ohos.bundle'; - import featureAbility from '@ohos.ability.featureAbility'; - - async function requestPermission() { - let permissions: Array = [ - "ohos.permission.DISTRIBUTED_DATASYNC" - ]; - let needGrantPermission: boolean = false; - let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); - let applicationInfo = await bundle.getApplicationInfo('ohos.samples.etsDemo', 0, 100); - for (let i = 0; i < permissions.length; i++) { - let result = await atManager.verifyAccessToken(applicationInfo.accessTokenId, permissions[i]); - // Check whether the permission is granted. - if (result == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { - needGrantPermission = true; - break; - } - } - // If the permission is not granted, call requestPermissionsFromUser to apply for the permission. - if (needGrantPermission) { - await featureAbility.getContext().requestPermissionsFromUser(permissions, 1); - } else { - console.info('app permission already granted'); - } - } - ``` - - In the stage model, add the required permission in the `module.json5` file. The sample code is as follows: - - ```json - { - "module": { - "requestPermissions": [ - { - "name": "ohos.permission.DISTRIBUTED_DATASYNC" - } - ] - } - } - ``` - - ```ts - import abilityAccessCtrl from "@ohos.abilityAccessCtrl"; - import bundle from '@ohos.bundle'; - - async function requestPermission() { - let permissions: Array = [ - "ohos.permission.DISTRIBUTED_DATASYNC" - ]; - let needGrantPermission: boolean = false; - let atManger: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); - let applicationInfo = await bundle.getApplicationInfo('ohos.samples.continuationmanager', 0, 100); - for (const permission of permissions) { - try { - let grantStatus = await atManger.verifyAccessToken(applicationInfo.accessTokenId, permission); - // Check whether the permission is granted. - if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_DENIED) { - needGrantPermission = true; - break; - } - } catch (err) { - console.error('app permission query grant status error' + JSON.stringify(err)); - needGrantPermission = true; - break; - } - } - // If the permission is not granted, call requestPermissionsFromUser to apply for the permission. - if (needGrantPermission) { - try { - // globalThis.context is Ability.context, which must be assigned a value in the MainAbility.ts file in advance. - await atManger.requestPermissionsFromUser(globalThis.context, permissions); - } catch (err) { - console.error('app permission request permissions error' + JSON.stringify(err)); - } - } else { - console.info('app permission already granted'); - } - } - ``` - -3. Register the continuation management service and obtain a token. - - The sample code is as follows: - - ```ts - let token: number = -1; // Used to save the token returned after the registration. The token will be used when listening for device connection/disconnection events, starting the device selection module, and updating the device connection state. - try { - continuationManager.registerContinuation().then((data) => { - console.info('registerContinuation finished, ' + JSON.stringify(data)); - token = data; // Obtain a token and assign a value to the token variable. - }).catch((err) => { - console.error('registerContinuation failed, cause: ' + JSON.stringify(err)); - }); - } catch (err) { - console.error('registerContinuation failed, cause: ' + JSON.stringify(err)); - } - ``` - -4. Listen for the device connection/disconnection state. - - The sample code is as follows: - - ```ts - let remoteDeviceId: string = ""; // Used to save the information about the remote device selected by the user, which will be used for cross-device continuation or collaboration. - - try { - // The token parameter is the token obtained during the registration. - continuationManager.on("deviceSelected", token, (continuationResults) => { - console.info('registerDeviceSelectedCallback len: ' + continuationResults.length); - if (continuationResults.length <= 0) { - console.info('no selected device'); - return; - } - remoteDeviceId = continuationResults[0].id; // Assign the deviceId of the first selected remote device to the remoteDeviceId variable. - - // Pass the remoteDeviceId parameter to want. - let want = { - deviceId: remoteDeviceId, - bundleName: 'ohos.samples.continuationmanager', - abilityName: 'EntryAbility' - }; - globalThis.abilityContext.startAbility(want).then((data) => { - console.info('StartRemoteAbility finished, ' + JSON.stringify(data)); - }).catch((err) => { - console.error('StartRemoteAbility failed, cause: ' + JSON.stringify(err)); - }); - }); - } catch (err) { - console.error('on failed, cause: ' + JSON.stringify(err)); - } - ``` - - The preceding multi-device collaboration operation is performed across devices in the stage model. For details about this operation in the FA model, see [Page Ability Development](fa-pageability.md). - - You can also instruct the device selection module to update the device connection state. The sample code is as follows: - - ```ts - // Set the device connection state. - let deviceConnectStatus: continuationManager.DeviceConnectState = continuationManager.DeviceConnectState.CONNECTED; - - // The token parameter is the token obtained during the registration, and the remoteDeviceId parameter is the remoteDeviceId obtained. - try { - continuationManager.updateContinuationState(token, remoteDeviceId, deviceConnectStatus).then((data) => { - console.info('updateContinuationState finished, ' + JSON.stringify(data)); - }).catch((err) => { - console.error('updateContinuationState failed, cause: ' + JSON.stringify(err)); - }); - } catch (err) { - console.error('updateContinuationState failed, cause: ' + JSON.stringify(err)); - } - ``` - - Listen for the device disconnection state so that the user can stop cross-device continuation or collaboration in time. The sample code is as follows: - - ```ts - try { - // The token parameter is the token obtained during the registration. - continuationManager.on("deviceUnselected", token, (continuationResults) => { - console.info('onDeviceUnselected len: ' + continuationResults.length); - if (continuationResults.length <= 0) { - console.info('no unselected device'); - return; - } - - // Update the device connection state. - let unselectedDeviceId: string = continuationResults[0].id; // Assign the deviceId of the first deselected remote device to the unselectedDeviceId variable. - let deviceConnectStatus: continuationManager.DeviceConnectState = continuationManager.DeviceConnectState.DISCONNECTING; // Device disconnected. - - // The token parameter is the token obtained during the registration, and the unselectedDeviceId parameter is the unselectedDeviceId obtained. - continuationManager.updateContinuationState(token, unselectedDeviceId, deviceConnectStatus).then((data) => { - console.info('updateContinuationState finished, ' + JSON.stringify(data)); - }).catch((err) => { - console.error('updateContinuationState failed, cause: ' + JSON.stringify(err)); - }); - }); - } catch (err) { - console.error('updateContinuationState failed, cause: ' + JSON.stringify(err)); - } - ``` - -5. Start the device selection module to show the list of available devices on the network. - - The sample code is as follows: - - ```ts - // Filter parameters. - let continuationExtraParams = { - deviceType: ["00E"], // Device type. - continuationMode: continuationManager.ContinuationMode.COLLABORATION_SINGLE // Single-choice mode of the device selection module. - }; - - try { - // The token parameter is the token obtained during the registration. - continuationManager.startContinuationDeviceManager(token, continuationExtraParams).then((data) => { - console.info('startContinuationDeviceManager finished, ' + JSON.stringify(data)); - }).catch((err) => { - console.error('startContinuationDeviceManager failed, cause: ' + JSON.stringify(err)); - }); - } catch (err) { - console.error('startContinuationDeviceManager failed, cause: ' + JSON.stringify(err)); - } - ``` - -6. If you do not need to perform cross-device migration or collaboration operations, you can deregister the continuation management service, by passing the token obtained during the registration. - - The sample code is as follows: - - ```ts - try { - // The token parameter is the token obtained during the registration. - continuationManager.unregisterContinuation(token).then((data) => { - console.info('unregisterContinuation finished, ' + JSON.stringify(data)); - }).catch((err) => { - console.error('unregisterContinuation failed, cause: ' + JSON.stringify(err)); - }); - } catch (err) { - console.error('unregisterContinuation failed, cause: ' + JSON.stringify(err)); - } - ``` diff --git a/en/application-dev/ability-deprecated/fa-brief.md b/en/application-dev/ability-deprecated/fa-brief.md deleted file mode 100644 index 4bdbfa4d7f3c96663cad5e90b9cd0d187a1e8709..0000000000000000000000000000000000000000 --- a/en/application-dev/ability-deprecated/fa-brief.md +++ /dev/null @@ -1,43 +0,0 @@ -# FA Model Overview - -## Overall Architecture - -Ability is the entry for application development in OpenHarmony. - -The core of ability development is the processing on ability lifecycle callbacks. - -The Feature Ability (FA) model can be used only for application development using API version 8 and earlier versions. In this model, there are PageAbility, ServiceAbility, DataAbility, and FormAbility. -- PageAbility implements the ArkUI and provides the capability for interacting with users. -- ServiceAbility does not have a UI. It runs in the background and provides custom services for other abilities to invoke. -- DataAbility does not have a UI. It runs in the background and enables other abilities to insert, delete, and query data. -- FormAbility is used to implement widgets, a new UI display form available on OpenHarmony devices. - -> Note: Starting from API version 9, the stage model is recommended for application development. - -## Lifecycle - -Among all abilities, PageAbility has the most complex lifecycle, because it has a UI and acts as a touchpoint for interacting with users. -**The following figure shows the lifecycle of PageAbility.** - -![fa-pageAbility-lifecycle](figures/fa-pageAbility-lifecycle.png) - -The other abilities do not involve foreground and background switch or the **onShow** and **onHide** callbacks. -You can override the lifecycle callbacks in **app.js** or **app.ets** to process application logic. - -The **app.js** file provides only the **onCreate** and **onDestroy** callbacks, and the **app.ets** file provides the callbacks covering the entire lifecycle. - -## Process and Thread Model - -Each application runs in a process. In the FA model, each ability runs in an independent VM. - -When an ability is started, an application process as well as a thread for this ability is created. For an application that has multiple abilities, each ability runs in an independent thread. In the FA model, each ability is bound to an independent VM instance. In this way, abilities are isolated from each other. - -![fa-threading-model](figures/fa-threading-model.png) - -## Application Package Structure - -For details about the project directory structure of the FA model, see [OpenHarmony Project Overview](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-project-overview-0000001218440650#section4154183910141). - -For details about how to configure the application package structure of the FA model, see [Application Package Structure Configuration File](../quick-start/application-configuration-file-overview-fa.md). - - diff --git a/en/application-dev/ability-deprecated/fa-dataability.md b/en/application-dev/ability-deprecated/fa-dataability.md deleted file mode 100644 index 217f617db77ff329eb1d0fa0eef7dcb6172cf45a..0000000000000000000000000000000000000000 --- a/en/application-dev/ability-deprecated/fa-dataability.md +++ /dev/null @@ -1,310 +0,0 @@ -# Data Ability Development - -## When to Use - -A Data ability helps applications manage access to data stored by themselves and other applications. It also provides APIs for sharing data with other applications either on the same device or across devices. - -Data ability providers can customize data access-related APIs such as data inserting, deleting, updating, and querying, as well as file opening, and share data with other applications through these open APIs. - -## URI Introduction - -A Uniform Resource Identifier (URI) is used to identify a specific data item, such as a table in the database or a file on the disk. URIs used in OpenHarmony comply with the commonly used URI standard. A URI consists of the components: - -![fa-dataability-uri](figures/fa-dataability-uri.png) - -- **scheme**: name of the scheme used by the Data ability. The value is fixed at **dataability**. -- **authority**: device ID. To access data on a remote device, set this component to the ID of the remote device. To access data on the local device, leave this component empty. -- **path**: location of the specific resource to access. -- **query**: query parameters. -- **fragment**: subordinate resources to access. - -Example URIs: - -- Cross-device communication: **dataability://***device_id***/***com.domainname.dataability.persondata***/***person***/***10* -- Local-device communication: **dataability:///***com.domainname.dataability.persondata***/***person***/***10* - -> **NOTE** -> -> In the case of local-device communication, **device_id** is empty, and therefore, there are three slashes (/) after **dataability:**. - -## Available APIs - -**Table 1** Data ability lifecycle APIs -|API|Description| -|:------|:------| -|onInitialized(info: AbilityInfo): void|Called during ability initialization to initialize the relational database (RDB).| -|update(uri: string, valueBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\): void|Updates data in the database.| -|query(uri: string, columns: Array\, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\): void|Queries data in the database.| -|delete(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\): void|Deletes one or more data records from the database.| -|normalizeUri(uri: string, callback: AsyncCallback\): void|Normalizes the URI. A normalized URI applies to cross-device use, persistence, backup, and restore. When the context changes, it ensures that the same data item can be referenced.| -|batchInsert(uri: string, valueBuckets: Array\, callback: AsyncCallback\): void|Inserts multiple data records into the database.| -|denormalizeUri(uri: string, callback: AsyncCallback\): void|Converts a normalized URI generated by **normalizeUri** into a denormalized URI.| -|insert(uri: string, valueBucket: rdb.ValuesBucket, callback: AsyncCallback\): void|Inserts a data record into the database.| -|openFile(uri: string, mode: string, callback: AsyncCallback\): void|Opens a file.| -|getFileTypes(uri: string, mimeTypeFilter: string, callback: AsyncCallback\>): void|Obtains the MIME type of a file.| -|getType(uri: string, callback: AsyncCallback\): void|Obtains the MIME type matching the data specified by the URI.| -|executeBatch(ops: Array\, callback: AsyncCallback\>): void|Operates data in the database in batches.| -|call(method: string, arg: string, extras: PacMap, callback: AsyncCallback\): void|Calls a custom API.| - - -## How to Develop -### Creating a Data Ability - -1. To meet the basic requirements of the database storage service, implement the **Insert**, **Query**, **Update**, and **Delete** APIs in the **Data** class. The **BatchInsert** and **ExecuteBatch** APIs have already implemented the traversal logic, but not batch data processing. - - The following code snippet shows how to create a Data ability: - - ```javascript - import featureAbility from '@ohos.ability.featureAbility' - import dataAbility from '@ohos.data.dataAbility' - import dataRdb from '@ohos.data.rdb' - - const TABLE_NAME = 'book' - const STORE_CONFIG = { name: 'book.db' } - const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS book(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, introduction TEXT NOT NULL)' - let rdbStore: dataRdb.RdbStore = undefined - - export default { - onInitialized(abilityInfo) { - console.info('DataAbility onInitialized, abilityInfo:' + abilityInfo.bundleName) - let context = featureAbility.getContext() - dataRdb.getRdbStore(context, STORE_CONFIG, 1, (err, store) => { - console.info('DataAbility getRdbStore callback') - store.executeSql(SQL_CREATE_TABLE, []) - rdbStore = store - }); - }, - insert(uri, valueBucket, callback) { - console.info('DataAbility insert start') - rdbStore.insert(TABLE_NAME, valueBucket, callback) - }, - batchInsert(uri, valueBuckets, callback) { - console.info('DataAbility batch insert start') - for (let i = 0;i < valueBuckets.length; i++) { - console.info('DataAbility batch insert i=' + i) - if (i < valueBuckets.length - 1) { - rdbStore.insert(TABLE_NAME, valueBuckets[i], (err: any, num: number) => { - console.info('DataAbility batch insert ret=' + num) - }) - } else { - rdbStore.insert(TABLE_NAME, valueBuckets[i], callback) - } - } - }, - query(uri, columns, predicates, callback) { - console.info('DataAbility query start') - let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates) - rdbStore.query(rdbPredicates, columns, callback) - }, - update(uri, valueBucket, predicates, callback) { - console.info('DataAbilityupdate start') - let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates) - rdbStore.update(valueBucket, rdbPredicates, callback) - }, - delete(uri, predicates, callback) { - console.info('DataAbilitydelete start') - let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates) - rdbStore.delete(rdbPredicates, callback) - } - }; - ``` - -2. Configure the submodule. - - | JSON Field| Description | - | ------------ | ------------------------------------------------------------ | - | "name" | Ability name, corresponding to the **Data** class name derived from **Ability**. | - | "type" | Ability type, which is **Data** for a Data ability. | - | "uri" | URI used for communication. | - | "visible" | Whether the Data ability is visible to other applications. When this parameter is set to **true**, the Data ability can communicate with other applications.| - - **config.json configuration example** - - ```json - "abilities":[{ - "srcPath": "DataAbility", - "name": ".DataAbility", - "icon": "$media:icon", - "srcLanguage": "ets", - "description": "$string:description_dataability", - "type": "data", - "visible": true, - "uri": "dataability://ohos.samples.etsdataability.DataAbility" - }] - ``` - -### Accessing a Data ability -#### Development Preparations - -Import the basic dependency packages and obtain the URI string for communicating with the Data submodule. - -The basic dependency packages include: -- @ohos.ability.featureAbility -- @ohos.data.dataAbility -- @ohos.data.rdb - -#### Data Ability API Development - - -1. Create a Data ability helper. - - For details about the APIs provided by **DataAbilityHelper**, see [DataAbilityHelper Module](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md). - ```js - // Different from the URI defined in the config.json file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/). - import featureAbility from '@ohos.ability.featureAbility' - import ohos_data_ability from '@ohos.data.dataAbility' - import ohos_data_rdb from '@ohos.data.rdb' - - var urivar = "dataability:///com.ix.DataAbility" - var DAHelper = featureAbility.acquireDataAbilityHelper( - urivar - ); - ``` -2. Construct RDB data. - ```js - var valuesBucket = {"name": "gaolu"} - var da = new ohos_data_ability.DataAbilityPredicates() - var valArray =new Array("value1"); - var cars = new Array({"batchInsert1" : "value1",}); - ``` -3. Use **insert** to insert data to the Data submodule. - ```js - // Callback mode: - DAHelper.insert( - urivar, - valuesBucket, - (error, data) => { - console.log("DAHelper insert result: " + data) - } - ); - ``` - - ```js - // Promise mode: - var datainsert = await DAHelper.insert( - urivar, - valuesBucket - ); - ``` -4. Use **delete** to delete data from the Data submodule. - ```js - // Callback mode: - DAHelper.delete( - urivar, - da, - (error, data) => { - console.log("DAHelper delete result: " + data) - } - ); - ``` - - ```js - // Promise mode: - var datadelete = await DAHelper.delete( - urivar, - da, - ); - ``` -5. Use **update** to update data in the Data submodule. - ```js - // Callback mode: - DAHelper.update( - urivar - valuesBucket, - da, - (error, data) => { - console.log("DAHelper update result: " + data) - } - ); - ``` - - ```js - // Promise mode: - var dataupdate = await DAHelper.update( - urivar, - valuesBucket, - da, - ); - ``` -6. Use **query** to query data in the Data submodule. - ```js - // Callback mode: - DAHelper.query( - urivar, - valArray, - da, - (error, data) => { - console.log("DAHelper query result: " + data) - } - ); - ``` - - ```js - // Promise mode: - var dataquery = await DAHelper.query( - urivar, - valArray, - da - ); - ``` -7. Use **batchInsert** to insert data in batches to the Data submodule. - ```js - // Callback mode: - DAHelper.batchInsert( - urivar, - cars, - (error, data) => { - console.log("DAHelper batchInsert result: " + data) - } - ); - ``` - - ```js - // Promise mode: - var databatchInsert = await DAHelper.batchInsert( - urivar, - cars - ); - ``` -8. Use **executeBatch** to process data in batches in the Data submodule. - ```js - // Callback mode: - DAHelper.executeBatch( - urivar, - [ - { - uri: urivar, - type: featureAbility.DataAbilityOperationType.TYPE_INSERT, - valuesBucket: {"executeBatch" : "value1",}, - predicates: da, - expectedCount:0, - predicatesBackReferences: null, - interrupted:true, - } - ], - (error, data) => { - console.log("DAHelper executeBatch result: " + data) - } - ); - ``` - - ```js - // Promise mode: - var dataexecuteBatch = await DAHelper.executeBatch( - urivar, - [ - { - uri: urivar, - type: featureAbility.DataAbilityOperationType.TYPE_INSERT, - valuesBucket: - { - "executeBatch" : "value1", - }, - predicates: da, - expectedCount:0, - predicatesBackReferences: null, - interrupted:true, - } - ] - ); - ``` diff --git a/en/application-dev/ability-deprecated/fa-formability.md b/en/application-dev/ability-deprecated/fa-formability.md deleted file mode 100644 index 96ed58d8ef2206d6c66e413d0a6fc34423651974..0000000000000000000000000000000000000000 --- a/en/application-dev/ability-deprecated/fa-formability.md +++ /dev/null @@ -1,406 +0,0 @@ -# FA Widget Development - -## Widget Overview -A widget is a set of UI components that display important information or operations specific to an application. It provides users with direct access to a desired application service, without the need to open the application first. - -A widget usually appears as a part of the UI of another application (which currently can only be a system application) and provides basic interactive features such as opening a UI page or sending a message. - -Before you get started, it would be helpful if you have a basic understanding of the following concepts: -- Widget provider: an atomic service that provides the widget content to display and controls how widget components are laid out and how they interact with users. -- Widget host: an application that displays the widget content and controls the widget location. -- Widget Manager: a resident agent that provides widget management features such as periodic widget updates. - -> **NOTE** -> -> The widget host and provider do not need to be running all the time. The Widget Manager will start the widget provider to obtain widget information when a widget is added, deleted, or updated. - -You only need to develop the widget provider. The system automatically handles the work of the widget host and Widget Manager. - -The widget provider controls the widget content to display, the layout of components used in the widget, and click events bound to the components. - -## Development Overview - -Carry out the following operations to develop the widget provider based on the [FA model](fa-brief.md): - -1. Implement lifecycle callbacks by using the **LifecycleForm** APIs. -2. Create a **FormBindingData** instance. -3. Update a widget by using the **FormProvider** APIs. -4. Develop the widget UI page. - -## Available APIs - -The table below describes the **LifecycleForm** APIs, which represent the lifecycle callbacks of a widget (known as a **Form** instance). - -**Table 1** LifecycleForm APIs - -| API | Description | -| :----------------------------------------------------------- | :------------------------------------------- | -| onCreate(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a 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 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 widget has been destroyed. | -| onAcquireFormState?(want: Want): formInfo.FormState | Called to instruct the widget provider to receive the status query result of a widget. | - -The table below describes the **FormProvider** APIs. For details, see [FormProvider](../reference/apis/js-apis-application-formProvider.md). - -**Table 2** FormProvider APIs - -| API | Description | -| :----------------------------------------------------------- | :------------------------------------------------ | -| setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback<void>): void; | Sets the next refresh time for a widget. This API uses an asynchronous callback to return the result. | -| setFormNextRefreshTime(formId: string, minute: number): Promise<void>; | Sets the next refresh time for a widget. This API uses a promise to return the result.| -| updateForm(formId: string, formBindingData: FormBindingData, callback: AsyncCallback<void>): void; | Updates a widget. This API uses an asynchronous callback to return the result. | -| updateForm(formId: string, formBindingData: FormBindingData): Promise<void>; | Updates a widget. This API uses a promise to return the result. | - -## How to Develop - -### Implementing Lifecycle Callbacks - -To create an FA widget, you need to implement lifecycle callbacks using the **LifecycleForm** APIs. The sample code is as follows: - -1. Import the required modules. - - ```javascript - import formBindingData from '@ohos.app.form.formBindingData'; - import formInfo from '@ohos.app.form.formInfo'; - import formProvider from '@ohos.app.form.formProvider'; - ``` - -2. Implement lifecycle callbacks for the widget. - - ```javascript - export default { - onCreate(want) { - console.log('FormAbility onCreate'); - // Persistently store widget information for subsequent use, such as widget instance retrieval or update. - let obj = { - "title": "titleOnCreate", - "detail": "detailOnCreate" - }; - let formData = formBindingData.createFormBindingData(obj); - return formData; - }, - onCastToNormal(formId) { - // Called when the widget host converts the temporary widget into a normal one. The widget provider should do something to respond to the conversion. - console.log('FormAbility onCastToNormal'); - }, - onUpdate(formId) { - // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. - console.log('FormAbility onUpdate'); - let obj = { - "title": "titleOnUpdate", - "detail": "detailOnUpdate" - }; - let formData = formBindingData.createFormBindingData(obj); - formProvider.updateForm(formId, formData).catch((error) => { - console.log('FormAbility updateForm, error:' + JSON.stringify(error)); - }); - }, - onVisibilityChange(newStatus) { - // Called when the widget host initiates an event about visibility changes. The widget provider should do something to respond to the notification. - console.log('FormAbility onVisibilityChange'); - }, - onEvent(formId, message) { - // If the widget supports event triggering, override this method and implement the trigger. - console.log('FormAbility onEvent'); - }, - onDestroy(formId) { - // Delete widget data. - console.log('FormAbility onDestroy'); - }, - onAcquireFormState(want) { - console.log('FormAbility onAcquireFormState'); - return formInfo.FormState.READY; - }, - } - ``` - -### Configuring the Widget Configuration File - -The widget configuration file is named **config.json**. Find the **config.json** file for the widget and edit the file depending on your need. - -- The **js** module in the **config.json** file provides JavaScript resources of the widget. The internal structure is described as follows: - - | Field| Description | Data Type| Default | - | -------- | ------------------------------------------------------------ | -------- | ------------------------ | - | name | Name of a JavaScript component. The default value is **default**. | String | No | - | pages | Route information about all pages in the JavaScript component, including the page path and page name. The value is an array, in which each element represents a page. The first element in the array represents the home page of the JavaScript FA.| Array | No | - | window | Window-related configurations. | Object | Yes | - | type | Type of the JavaScript component.
**normal**: indicates an application instance.
**form**: indicates a widget instance.| String | Yes (initial value: **normal**)| - | mode | Development mode of the JavaScript component. | Object | Yes (initial value: left empty) | - - Example configuration: - - ```json - "js": [{ - "name": "widget", - "pages": ["pages/index/index"], - "window": { - "designWidth": 720, - "autoDesignWidth": true - }, - "type": "form" - }] - ``` - -- The **abilities** module in the **config.json** file corresponds to **LifecycleForm** of the widget. The internal 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 | - | 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) | - | 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.
**JS**: indicates a JavaScript-programmed widget. | String | No | - | colorMode | Color mode of the widget.
**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.
**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.
**true**: The widget can be updated at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** takes precedence over **scheduledUpdateTime**.
**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.
**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| 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.
**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| 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) | - | 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) | - | customizeData | Custom information about the widget. | Object array | Yes (initial value: left empty) | - - Example configuration: - - ```json - "abilities": [{ - "name": "FormAbility", - "description": "This is a FormAbility", - "formsEnabled": true, - "icon": "$media:icon", - "label": "$string:form_FormAbility_label", - "srcPath": "FormAbility", - "type": "service", - "srcLanguage": "ets", - "formsEnabled": true, - "forms": [{ - "colorMode": "auto", - "defaultDimension": "2*2", - "description": "This is a widget.", - "formVisibleNotify": true, - "isDefault": true, - "jsComponentName": "widget", - "name": "widget", - "scheduledUpdateTime": "10:30", - "supportDimensions": ["2*2"], - "type": "JS", - "updateEnabled": true - }] - }] - ``` - - -### Persistently Storing Widget Data - -A widget provider is usually started when it is needed to provide 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. - -```javascript - onCreate(want) { - console.log('FormAbility onCreate'); - - 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 data for subsequent use, such as widget instance retrieval or update. - // The storeFormInfo API is not implemented here. - storeFormInfo(formId, formName, tempFlag, want); - - let obj = { - "title": "titleOnCreate", - "detail": "detailOnCreate" - }; - let formData = formBindingData.createFormBindingData(obj); - return formData; - } -``` - -You should override **onDestroy** to implement widget data deletion. - -```javascript - onDestroy(formId) { - console.log('FormAbility onDestroy'); - - // You need to implement the code for deleting the persistent widget data. - // The deleteFormInfo API is not implemented here. - deleteFormInfo(formId); - } -``` - -For details about how to implement persistent data storage, see [Data Persistence by User Preferences](../database/data-persistence-by-preferences.md). - -The **Want** object passed in by the widget host to the widget provider contains a flag that specifies whether the requested widget is normal or temporary. - -- Normal widget: a widget persistently used by the widget host - -- Temporary widget: a widget temporarily used by the widget host - -Data of a temporary widget will be deleted on the Widget Manager if the widget framework is killed and restarted. The widget provider, however, is not notified of the deletion and still keeps the data. Therefore, the widget provider needs to clear the data of temporary widgets proactively if the data has been kept for a long period of time. If the widget host has converted a temporary widget into a normal one, the widget provider should change the widget data from temporary storage to persistent storage. Otherwise, the widget data may be deleted by mistake. - -### Updating Widget Data - -When an application initiates a scheduled or periodic update, the application obtains the latest data and calls **updateForm** to update the widget. The code snippet is as follows: - -```javascript -onUpdate(formId) { - // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. - console.log('FormAbility onUpdate'); - let obj = { - "title": "titleOnUpdate", - "detail": "detailOnUpdate" - }; - let formData = formBindingData.createFormBindingData(obj); - // Call the updateForm() method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged. - formProvider.updateForm(formId, formData).catch((error) => { - console.log('FormAbility updateForm, error:' + JSON.stringify(error)); - }); -} -``` - -### Developing the Widget UI Page - -You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget. - -> **NOTE** -> -> Only the JavaScript-based web-like development paradigm is supported when developing the widget UI. - - - HML file: - ```html -
- -
- -
-
- {{title}} - {{detail}} -
-
-
- ``` - - - CSS file: - - ```css -.container { - flex-direction: column; - justify-content: center; - align-items: center; -} - -.bg-img { - flex-shrink: 0; - height: 100%; -} - -.container-inner { - flex-direction: column; - justify-content: flex-end; - align-items: flex-start; - height: 100%; - width: 100%; - padding: 12px; -} - -.title { - font-size: 19px; - font-weight: bold; - color: white; - text-overflow: ellipsis; - max-lines: 1; -} - -.detail_text { - font-size: 16px; - color: white; - opacity: 0.66; - text-overflow: ellipsis; - max-lines: 1; - margin-top: 6px; -} - ``` - - - JSON file: - ```json - { - "data": { - "title": "TitleDefault", - "detail": "TextDefault" - }, - "actions": { - "routerEvent": { - "action": "router", - "abilityName": "com.example.entry.EntryAbility", - "params": { - "message": "add detail" - } - } - } - } - ``` - -Now you've got a widget shown below. - -![fa-form-example](figures/fa-form-example.png) - -### Developing Widget Events - -You can set router and message events for components on a widget. The router event applies to ability redirection, and the message event applies to custom click events. The key steps are as follows: - -1. Set the **onclick** field in the HML file to **routerEvent** or **messageEvent**, depending on the **actions** settings in the JSON file. -2. Set the router event. - - **action**: **"router"**, which indicates a router event. - - **abilityName**: target ability name, for example, **com.example.entry.EntryAbility**, which is the default UIAbility name in DevEco Studio for the FA model. - - **params**: custom parameters of the target ability. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target ability. For example, in the lifecycle function **onCreate** of the EntryAbility in the FA model, **featureAbility.getWant()** can be used to obtain **want** and its **parameters** field. -3. Set the message event. - - **action**: **"message"**, which indicates a message event. - - **params**: custom parameters of the message event. Set them as required. The value can be obtained from **message** in the widget lifecycle function **onEvent**. - -The code snippet is as follows: - - - HML file: - ```html -
- -
- -
-
- {{title}} - {{detail}} -
-
-
- ``` - - - JSON file: - ```json - { - "data": { - "title": "TitleDefault", - "detail": "TextDefault" - }, - "actions": { - "routerEvent": { - "action": "router", - "abilityName": "com.example.entry.EntryAbility", - "params": { - "message": "add detail" - } - }, - "messageEvent": { - "action": "message", - "params": { - "message": "add detail" - } - } - } - } - ``` - - \ No newline at end of file diff --git a/en/application-dev/ability-deprecated/fa-pageability.md b/en/application-dev/ability-deprecated/fa-pageability.md deleted file mode 100644 index e28c0f2823ff61f6c60f469eaaf9d197184e8f50..0000000000000000000000000000000000000000 --- a/en/application-dev/ability-deprecated/fa-pageability.md +++ /dev/null @@ -1,224 +0,0 @@ -# Page Ability Development - -## Overview - -### Concepts - -The Page ability implements the ArkUI and provides the capability of interacting with developers. When you create an ability in DevEco Studio, DevEco Studio automatically creates template code. - -The capabilities related to the Page ability are implemented through the **featureAbility**, and the lifecycle callbacks are implemented through the callbacks in **app.js** or **app.ets**. - -### Page Ability Lifecycle - -Introduction to the Page ability lifecycle: - -The Page ability lifecycle defines all states of a Page ability, such as **INACTIVE**, **ACTIVE**, and **BACKGROUND**. - -The following figure shows the lifecycle state transition of the Page ability. - -![PageAbility-Lifecycle](figures/page-ability-lifecycle.png) - - -Description of ability lifecycle states: - - - **UNINITIALIZED**: The Page ability is not initialized. This is a temporary state, from which a Page ability changes directly to the **INITIAL** state upon its creation. - - - **INITIAL**: The Page ability is initialized but not running. The Page ability enters the **INACTIVE** state after it is started. - - - **INACTIVE**: The Page ability is visible but does not gain focus. - - - **ACTIVE**: The Page ability runs in the foreground and has focus. - - - **BACKGROUND**: The Page ability runs in the background. After being re-activated, the Page ability enters the **ACTIVE** state. After being destroyed, the Page ability enters the **INITIAL** state. - -The following figure shows the relationship between lifecycle callbacks and lifecycle states of the Page ability. - -![fa-pageAbility-lifecycle](figures/fa-pageAbility-lifecycle.png) - -You can override the lifecycle callbacks provided by the Page ability in the **app.js** or **app.ets** file. Currently, the **app.js** file provides only the **onCreate** and **onDestroy** callbacks, and the **app.ets** file provides the full lifecycle callbacks. - -### Launch Type - -The ability supports two launch types: singleton and multi-instance. - -You can specify the launch type by setting **launchType** in the **config.json** file. - -**Table 1** Startup modes - -| Launch Type | Description |Description | -| ----------- | ------- |---------------- | -| standard | Multi-instance | A new instance is started each time an ability starts.| -| singleton | Singleton | The ability has only one instance in the system. If an instance already exists when an ability is started, that instance is reused.| - -By default, **singleton** is used. - - -## Development Guidelines - -### Available APIs - -**Table 2** APIs provided by featureAbility - -| API | Description | -| --------------------------------------------------- | --------------- | -| void startAbility(parameter: StartAbilityParameter) | Starts an ability. | -| Context getContext(): | Obtains the application context.| -| void terminateSelf() | Terminates the ability. | -| bool hasWindowFocus() | Checks whether the ability has focus. | - - -### Starting a Local Page Ability - -**Modules to Import** - -```js - import featureAbility from '@ohos.ability.featureAbility' -``` - -**Example** - -```javascript - import featureAbility from '@ohos.ability.featureAbility' - featureAbility.startAbility({ - want: { - action: "", - entities: [""], - type: "", - deviceId: "", - bundleName: "com.example.myapplication", - /* In the FA model, abilityName consists of package and ability name. */ - abilityName: "com.example.entry.secondAbility", - uri: "" - } - }); -``` - -### Starting a Remote Page Ability ->NOTE -> ->This feature applies only to system applications, since the **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications. - -**Modules to Import** - -``` - import featureAbility from '@ohos.ability.featureAbility' - import deviceManager from '@ohos.distributedHardware.deviceManager'; -``` - -**Example** -```ts - function onStartRemoteAbility() { - console.info('onStartRemoteAbility begin'); - let params; - let wantValue = { - bundleName: 'ohos.samples.etsDemo', - abilityName: 'ohos.samples.etsDemo.RemoteAbility', - deviceId: getRemoteDeviceId(), - parameters: params - }; - console.info('onStartRemoteAbility want=' + JSON.stringify(wantValue)); - featureAbility.startAbility({ - want: wantValue - }).then((data) => { - console.info('onStartRemoteAbility finished, ' + JSON.stringify(data)); - }); - console.info('onStartRemoteAbility end'); - } -``` - -Obtain **deviceId** from **DeviceManager**. The sample code is as follows: - -```ts - import deviceManager from '@ohos.distributedHardware.deviceManager'; - let dmClass; - function getRemoteDeviceId() { - if (typeof dmClass === 'object' && dmClass != null) { - let list = dmClass.getTrustedDeviceListSync(); - if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { - console.log("EntryAbility onButtonClick getRemoteDeviceId err: list is null"); - return; - } - console.log("EntryAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); - return list[0].deviceId; - } else { - console.log("EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null"); - } - } -``` - -In the cross-device scenario, the application must also apply for the data synchronization permission from end users. The sample code is as follows: - -```ts - import abilityAccessCtrl from "@ohos.abilityAccessCtrl"; - import bundle from '@ohos.bundle'; - async function RequestPermission() { - console.info('RequestPermission begin'); - let array: Array = ["ohos.permission.DISTRIBUTED_DATASYNC"]; - let bundleFlag = 0; - let tokenID = undefined; - let userID = 100; - let appInfo = await bundle.getApplicationInfo('ohos.samples.etsDemo', bundleFlag, userID); - tokenID = appInfo.accessTokenId; - let atManager = abilityAccessCtrl.createAtManager(); - let requestPermissions: Array = []; - for (let i = 0;i < array.length; i++) { - let result = await atManager.verifyAccessToken(tokenID, array[i]); - console.info("verifyAccessToken result:" + JSON.stringify(result)); - if (result != abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { - requestPermissions.push(array[i]); - } - } - console.info("requestPermissions:" + JSON.stringify(requestPermissions)); - if (requestPermissions.length == 0 || requestPermissions == []) { - return; - } - let context = featureAbility.getContext(); - context.requestPermissionsFromUser(requestPermissions, 1, (data)=>{ - console.info("data:" + JSON.stringify(data)); - console.info("data requestCode:" + data.requestCode); - console.info("data permissions:" + data.permissions); - console.info("data authResults:" + data.authResults); - }); - console.info('RequestPermission end'); - } -``` - -### Lifecycle APIs - -**Table 3** Lifecycle callbacks - -| API | Description | -| ------------ | ------------------------------------------------------------ | -| onShow() | Called when the ability is switched from the background to the foreground. In this case, the ability is visible to users.| -| onHide() | Called when the ability is switched from the foreground to the background. In this case, the ability is invisible to users.| -| onDestroy() | Called when the ability is destroyed. In this callback, you can make preparations for application exit, such as recycling resources and clearing the cache.| -| onCreate() | Called when the ability is created for the first time. You can initialize the application in this callback.| -| onInactive() | Called when the ability loses focus. An ability loses focus when it is about to enter the background state.| -| onActive() | Called when the ability is switched to the foreground and gains focus. | - -**Example** - -You need to override the lifecycle callbacks except **onCreate()** and **onDestroy()** in **app.js** or **app.ets**. The **onCreate()** and **onDestroy()** callbacks are automatically generated in the template code provided by DevEco Studio. - -```javascript -export default { - onCreate() { - console.info('Application onCreate') - }, - onDestroy() { - console.info('Application onDestroy') - }, - onShow(){ - console.info('Application onShow') - }, - onHide(){ - console.info('Application onHide') - }, - onInactive(){ - console.info('Application onInactive') - }, - onActive(){ - console.info('Application onActive') - }, -} -``` diff --git a/en/application-dev/ability-deprecated/fa-serviceability.md b/en/application-dev/ability-deprecated/fa-serviceability.md deleted file mode 100644 index 0c2a65aebf1076e739009101980633e41f77e8a7..0000000000000000000000000000000000000000 --- a/en/application-dev/ability-deprecated/fa-serviceability.md +++ /dev/null @@ -1,333 +0,0 @@ -# Service Ability Development - -## When to Use -A Service ability is used to run tasks in the background, such as playing music or downloading files. It does not provide a UI for user interaction. Service abilities can be started by other applications or abilities and can keep running in the background even after the user switches to another application. - -## Lifecycle APIs - -**Table 1** Service ability lifecycle APIs -|API|Description| -|:------|:------| -|onStart?(): void|Called to initialize a Service ability when the Service ability is being created. This callback is invoked only once in the entire lifecycle of a Service ability.| -|onCommand?(want: Want, startId: number): void|Called every time a Service ability is created on the client. You can collect calling statistics and perform initialization operations in this callback.| -|onConnect?(want: Want): rpc.RemoteObject|Called when another ability is connected to the Service ability.| -|onDisconnect?(want: Want): void|Called when another ability is disconnected from the Service ability.| -|onStop?(): void|Called when the Service ability is being destroyed. You should override this callback for your Service ability to clear its resources, such as threads and registered listeners.| - -The differences between **onCommand()** and **onConnect()** are as follows: - - The **onCommand()** callback is triggered each time the client starts the Service ability by calling **startAbility** or **startAbilityForResult**. - - The **onConnect()** callback is triggered each time the client establishes a new connection with the Service ability by calling **connectAbility**. - -## How to Develop - -### Creating and Registering a Service Ability - -1. Override the Service ability-related lifecycle callbacks to implement your own logic for processing interaction requests. - - ```ts - export default { - onStart() { - console.log('ServiceAbility onStart'); - }, - onCommand(want, startId) { - console.log('ServiceAbility onCommand'); - }, - onConnect(want) { - console.log('ServiceAbility OnConnect'); - // Below lists the implementation of ServiceAbilityStub. - return new ServiceAbilityStub('test'); - }, - onDisconnect(want) { - console.log('ServiceAbility OnDisConnect'); - }, - onStop() { - console.log('ServiceAbility onStop'); - } - } - ``` - -2. Register a Service ability. - - Declare the Service ability in the **config.json** file by setting its **type** attribute to **service**. - - ```json - { - "module": { - "abilities": [ - { - "name": ".ServiceAbility", - "type": "service", - "visible": true - ... - } - ] - ... - } - ... - } - ``` - - - -### Starting a Service Ability - -The **Ability** class provides the **startAbility()** API for you to start another Service ability by passing a **Want** object. - -To set information about the target Service ability, you can first construct a **Want** object with the **bundleName** and **abilityName** parameters specified. - -- **bundleName** specifies the bundle name of the target application. -- **abilityName** specifies the target ability name. - -The following code snippet shows how to start a Service ability running on the local device: - -```ts -import featureAbility from '@ohos.ability.featureAbility' - -featureAbility.startAbility( - { - want: - { - bundleName: "com.jstest.service", - abilityName: "com.jstest.service.ServiceAbility" - } - } -).then((err) => { - console.log("startService success"); -}).catch (err => { - console.log("startService FAILED"); -}); -``` - -In the preceding code, the **startAbility()** API is used to start the Service ability. -- If the Service ability is not running, the system initializes the Service ability, and calls **onStart()** and **onCommand()** on the Service ability in sequence. -- If the Service ability is running, the system directly calls **onCommand()** on the Service ability. - -The following code snippet shows how to start a Service ability running on the remote device. For details, see [Connecting to a Remote Service Ability](#connecting-to-a-remote-service-ability). - -```ts -import featureAbility from '@ohos.ability.featureAbility' - -featureAbility.startAbility( - { - want: - { - deviceId: remoteDeviceId, // Remote device ID. - bundleName: "com.jstest.service", - abilityName: "com.jstest.service.ServiceAbility" - } - } -).then((err) => { - console.log("startService success"); -}).catch (err => { - console.log("startService FAILED"); -}); -``` - - -### Stopping a Service Ability - - In normal cases, a Service ability can be stopped by itself or by the system. - - The Service ability can call **particleAbility.terminateSelf()** to stop itself. - - If the application process where the Service ability is located exits, the Service ability is reclaimed along with the process. - - If the Service ability is only accessed through **connectAbility()** (the **onCommand()** callback has never been triggered), the system stops the Service ability when the last connection to the Service ability is disconnected. - -### Connecting to a Local Service Ability - -If a Service ability wants to interact with a Page ability or a Service ability in another application, you must first create a connection. A Service ability allows other abilities to connect to it through **connectAbility()**. - - -You can use either of the following methods to connect to a Service ability: - -1. Using the IDL to automatically generate code - - Use OpenHarmony Interface Definition Language (IDL) to automatically generate the corresponding client, server, and **IRemoteObject** code. For details, see [Development Using TS](../IDL/idl-guidelines.md#development-using-ts). - -2. Writing code in the corresponding file - - When using **connectAbility()**, pass the **Want** and **ConnectOptions** objects of the target Service ability, where **ConnectOptions** encapsulates the following three callbacks that need to be implemented. - - **onConnect()**: callback used for processing when the Service ability is connected. - - **onDisconnect()**: callback used for processing when the Service ability is disconnected. - - **onFailed()**: callback used for processing when the connection to the Service ability fails. - - The following code snippet shows how to implement the callbacks: - - ```ts - import prompt from '@system.prompt' - - var option = { - onConnect: function onConnectCallback(element, proxy) { - console.log(`onConnectLocalService onConnectDone`); - if (proxy === null) { - prompt.showToast({ - message: "Connect service failed" - }); - return; - } - // After obtaining the proxy of the Service ability, the calling ability can communicate with the Service ability. - let data = rpc.MessageParcel.create(); - let reply = rpc.MessageParcel.create(); - let option = new rpc.MessageOption(); - data.writeString("InuptString"); - proxy.sendRequest(0, data, reply, option); - prompt.showToast({ - message: "Connect service success" - }); - }, - onDisconnect: function onDisconnectCallback(element) { - console.log(`onConnectLocalService onDisconnectDone element:${element}`); - prompt.showToast({ - message: "Disconnect service success" - }); - }, - onFailed: function onFailedCallback(code) { - console.log(`onConnectLocalService onFailed errCode:${code}`); - prompt.showToast({ - message: "Connect local service onFailed" - }); - } - }; - ``` - - The following code snippet shows how to connect to a local Service ability: - - ```ts - import featureAbility from '@ohos.ability.featureAbility' - - let want = { - bundleName: "com.jstest.service", - abilityName: "com.jstest.service.ServiceAbility" - }; - let connectId = featureAbility.connectAbility(want, option); - ``` - - When a Service ability is connected, the **onConnect()** callback is invoked and returns an **IRemoteObject** defining the proxy used for communicating with the Service ability. OpenHarmony provides the default implementation of **IRemoteObject**. You can inherit **rpc.RemoteObject** to create a custom implementation class for interaction with the Service ability. For details, see the [RPC API Reference](..\reference\apis\js-apis-rpc.md). - - The following code snippet shows how the Service ability returns itself to the calling ability: - - ```ts - import rpc from "@ohos.rpc" - - class ServiceAbilityStub extends rpc.RemoteObject { - constructor(des: any) { - if (typeof des === 'string') { - super(des); - } else { - console.log("Error, the input param is not string"); - return; - } - } - - onRemoteRequest(code: number, data: any, reply: any, option: any) { - console.log("onRemoteRequest called"); - // Execute the service logic. - if (code === 1) { - // Sort the input strings. - let string = data.readString(); - console.log(`Input string = ${string}`); - let result = Array.from(string).sort().join(''); - console.log(`Output result = ${result}`); - reply.writeString(result); - } else { - console.log(`Unknown request code`); - } - return true; - } - } - - export default { - onStart() { - console.log('ServiceAbility onStart'); - }, - onCommand(want, startId) { - console.log('ServiceAbility onCommand'); - }, - onConnect(want) { - console.log('ServiceAbility OnConnect'); - return new ServiceAbilityStub('ServiceAbilityRemoteObject'); - }, - onDisconnect(want) { - console.log('ServiceAbility OnDisConnect'); - }, - onStop() { - console.log('ServiceAbility onStop'); - } - } - ``` - -### Connecting to a Remote Service Ability - -This feature applies only to system applications. The method of creating a **ConnectOptions** object for connecting to a remote Service ability is similar to that for connecting to a local Service ability. The differences are as follows: - - The application must apply for the data synchronization permission from the user. - - **Want** of the target Service ability must contain the remote device ID. - -> **NOTE** -> -> The **getTrustedDeviceList** API of **DeviceManager** is open only to system applications. Currently, only system applications can connect to a remote Service ability. -> -> For details about the API definition, see [Device Management](..\reference\apis\js-apis-device-manager.md). - -The data synchronization permission is required in the cross-device scenario. Configure the permission in the **config.json** file. - -```json -{ - ... - "module": { - ... - "reqPermissions": [{ - "name": "ohos.permission.DISTRIBUTED_DATASYNC" - }] - } -} -``` - -The **DISTRIBUTED_DATASYNC** permission is user granted. Therefore, your application, when being started, must display a dialog box to request the permission. The sample code is as follows: - -```ts -import abilityAccessCtrl from "@ohos.abilityAccessCtrl" -import bundle from '@ohos.bundle' - -async function RequestPermission() { - console.info('RequestPermission begin'); - let array: Array = ["ohos.permission.DISTRIBUTED_DATASYNC"]; - let bundleFlag = 0; - let tokenID = undefined; - let userID = 100; - let appInfo = await bundle.getApplicationInfo('ohos.samples.etsDemo', bundleFlag, userID); - tokenID = appInfo.accessTokenId; - let atManager = abilityAccessCtrl.createAtManager(); - let requestPermissions: Array = []; - for (let i = 0;i < array.length; i++) { - let result = await atManager.verifyAccessToken(tokenID, array[i]); - console.info("verifyAccessToken result:" + JSON.stringify(result)); - if (result != abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { - requestPermissions.push(array[i]); - } - } - console.info("requestPermissions:" + JSON.stringify(requestPermissions)); - if (requestPermissions.length == 0 || requestPermissions == []) { - return; - } - let context = featureAbility.getContext(); - context.requestPermissionsFromUser(requestPermissions, 1, (data)=>{ - console.info("data:" + JSON.stringify(data)); - }); - console.info('RequestPermission end'); -} -``` - -To obtain the device ID, import the **@ohos.distributedHardware.deviceManager** module, which provides **getTrustedDeviceList** to obtain the remote device ID. For details about how to use the API, see [Device Management](..\reference\apis\js-apis-device-manager.md). - -To connect to a remote Service ability, you only need to define **deviceId** in **Want**. The sample code is as follows: - -```ts -import featureAbility from '@ohos.ability.featureAbility' - -let want = { - deviceId: remoteDeviceId, - bundleName: "com.jstest.service", - abilityName: "com.jstest.service.ServiceAbility" -}; -let connectId = featureAbility.connectAbility(want, option); -``` - -The other implementations are the same as those for the connection to a local Service ability. For details, see the sample code provided under [Connecting to a Local Service Ability](#connecting-to-a-local-service-ability). diff --git a/en/application-dev/ability-deprecated/figures/AbilityComponentInstanceMission.png b/en/application-dev/ability-deprecated/figures/AbilityComponentInstanceMission.png deleted file mode 100644 index ce349b7a3544739dd2d3314d35f5b8e3ee68357c..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/figures/AbilityComponentInstanceMission.png and /dev/null differ diff --git a/en/application-dev/ability-deprecated/figures/ExtensionAbility.png b/en/application-dev/ability-deprecated/figures/ExtensionAbility.png deleted file mode 100644 index eeba9d61b27b3a506d18b2e3cc59a7a4f2036841..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/figures/ExtensionAbility.png and /dev/null differ diff --git a/en/application-dev/ability-deprecated/figures/aa-dump-a.PNG b/en/application-dev/ability-deprecated/figures/aa-dump-a.PNG deleted file mode 100644 index ae8d41f65f68d73895be5bbbb539c0d220b2a9a5..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/figures/aa-dump-a.PNG and /dev/null differ diff --git a/en/application-dev/ability-deprecated/figures/aa-dump-i.PNG b/en/application-dev/ability-deprecated/figures/aa-dump-i.PNG deleted file mode 100644 index 12998c5ba3e7d667d1147b6e825f8d110d5c5c5e..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/figures/aa-dump-i.PNG and /dev/null differ diff --git a/en/application-dev/ability-deprecated/figures/aa-dump-l.PNG b/en/application-dev/ability-deprecated/figures/aa-dump-l.PNG deleted file mode 100644 index a6797eef284990e3fa25e71562ac8afbddf0821d..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/figures/aa-dump-l.PNG and /dev/null differ diff --git a/en/application-dev/ability-deprecated/figures/contextIntroduction.png b/en/application-dev/ability-deprecated/figures/contextIntroduction.png deleted file mode 100644 index 50ec4d39f722431513051be8f6674f15307117f4..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/figures/contextIntroduction.png and /dev/null differ diff --git a/en/application-dev/ability-deprecated/figures/continuation-info.png b/en/application-dev/ability-deprecated/figures/continuation-info.png deleted file mode 100644 index e6335847a8025bf8b9c1ee2bc67dc9ed733f7b5a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/figures/continuation-info.png and /dev/null differ diff --git a/en/application-dev/ability-deprecated/figures/continuationManager.png b/en/application-dev/ability-deprecated/figures/continuationManager.png deleted file mode 100644 index 8447f339a8fc2e911aaf7d3f86557c980eecac44..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/figures/continuationManager.png and /dev/null differ diff --git a/en/application-dev/ability-deprecated/figures/fa-dataability-uri.png b/en/application-dev/ability-deprecated/figures/fa-dataability-uri.png deleted file mode 100644 index d89ada0ee9b2f9f655a6c3d8b0df17d6b1ca9326..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/figures/fa-dataability-uri.png and /dev/null differ diff --git a/en/application-dev/ability-deprecated/figures/fa-form-example.png b/en/application-dev/ability-deprecated/figures/fa-form-example.png deleted file mode 100644 index 795e96171e6d890e72a09382906302dd0fa45fab..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/figures/fa-form-example.png and /dev/null differ diff --git a/en/application-dev/ability-deprecated/figures/fa-pageAbility-lifecycle.png b/en/application-dev/ability-deprecated/figures/fa-pageAbility-lifecycle.png deleted file mode 100644 index 59a06741053c85cab6ea90b41bd16a6f2e1ff508..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/figures/fa-pageAbility-lifecycle.png and /dev/null differ diff --git a/en/application-dev/ability-deprecated/figures/fa-threading-model.png b/en/application-dev/ability-deprecated/figures/fa-threading-model.png deleted file mode 100644 index c155caf9a39e95cf7b8128090edb5013d2d956c4..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/figures/fa-threading-model.png and /dev/null differ diff --git a/en/application-dev/ability-deprecated/figures/favsstage.png b/en/application-dev/ability-deprecated/figures/favsstage.png deleted file mode 100644 index 4e5980fc1df4634d4ea1ff23158e79d62637f8ba..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/figures/favsstage.png and /dev/null differ diff --git a/en/application-dev/ability-deprecated/figures/lifecycle.png b/en/application-dev/ability-deprecated/figures/lifecycle.png deleted file mode 100644 index 345dd474c68069251a2c4ce8c9e8d792dbe029ef..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/figures/lifecycle.png and /dev/null differ diff --git a/en/application-dev/ability-deprecated/figures/page-ability-lifecycle.png b/en/application-dev/ability-deprecated/figures/page-ability-lifecycle.png deleted file mode 100644 index b35954967bb9c733725da2f0700481932619ae45..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/figures/page-ability-lifecycle.png and /dev/null differ diff --git a/en/application-dev/ability-deprecated/figures/stage-call.png b/en/application-dev/ability-deprecated/figures/stage-call.png deleted file mode 100644 index 4c0c0770a4dce6f275b0fc355f70c5dfca2adb17..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/figures/stage-call.png and /dev/null differ diff --git a/en/application-dev/ability-deprecated/figures/stageabilitylifecyclecallback.png b/en/application-dev/ability-deprecated/figures/stageabilitylifecyclecallback.png deleted file mode 100644 index 8dbfac680bc9ce6e0509ebc19bfc0ca035187c90..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/figures/stageabilitylifecyclecallback.png and /dev/null differ diff --git a/en/application-dev/ability-deprecated/figures/stageconcept.png b/en/application-dev/ability-deprecated/figures/stageconcept.png deleted file mode 100644 index 5f7c1776ddd207c14b60e9eef22ba22a1c77ad2a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/figures/stageconcept.png and /dev/null differ diff --git a/en/application-dev/ability-deprecated/figures/stagedesign.png b/en/application-dev/ability-deprecated/figures/stagedesign.png deleted file mode 100644 index c901b5196aeb255905b6add4fdfb960e66a4d904..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/figures/stagedesign.png and /dev/null differ diff --git a/en/application-dev/ability-deprecated/figures/stageprocessmodel.png b/en/application-dev/ability-deprecated/figures/stageprocessmodel.png deleted file mode 100644 index 18745767786674c496d6a41afe2e8df937745a4d..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/figures/stageprocessmodel.png and /dev/null differ diff --git a/en/application-dev/ability-deprecated/public_sys-resources/icon-caution.gif b/en/application-dev/ability-deprecated/public_sys-resources/icon-caution.gif deleted file mode 100644 index 6e90d7cfc2193e39e10bb58c38d01a23f045d571..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/public_sys-resources/icon-caution.gif and /dev/null differ diff --git a/en/application-dev/ability-deprecated/public_sys-resources/icon-danger.gif b/en/application-dev/ability-deprecated/public_sys-resources/icon-danger.gif deleted file mode 100644 index 6e90d7cfc2193e39e10bb58c38d01a23f045d571..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/public_sys-resources/icon-danger.gif and /dev/null differ diff --git a/en/application-dev/ability-deprecated/public_sys-resources/icon-note.gif b/en/application-dev/ability-deprecated/public_sys-resources/icon-note.gif deleted file mode 100644 index 6314297e45c1de184204098efd4814d6dc8b1cda..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/public_sys-resources/icon-note.gif and /dev/null differ diff --git a/en/application-dev/ability-deprecated/public_sys-resources/icon-notice.gif b/en/application-dev/ability-deprecated/public_sys-resources/icon-notice.gif deleted file mode 100644 index 86024f61b691400bea99e5b1f506d9d9aef36e27..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/public_sys-resources/icon-notice.gif and /dev/null differ diff --git a/en/application-dev/ability-deprecated/public_sys-resources/icon-tip.gif b/en/application-dev/ability-deprecated/public_sys-resources/icon-tip.gif deleted file mode 100644 index 93aa72053b510e456b149f36a0972703ea9999b7..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/public_sys-resources/icon-tip.gif and /dev/null differ diff --git a/en/application-dev/ability-deprecated/public_sys-resources/icon-warning.gif b/en/application-dev/ability-deprecated/public_sys-resources/icon-warning.gif deleted file mode 100644 index 6e90d7cfc2193e39e10bb58c38d01a23f045d571..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ability-deprecated/public_sys-resources/icon-warning.gif and /dev/null differ diff --git a/en/application-dev/ability-deprecated/stage-ability-continuation.md b/en/application-dev/ability-deprecated/stage-ability-continuation.md deleted file mode 100644 index f99966aff24d9b465627ba475cda018671820809..0000000000000000000000000000000000000000 --- a/en/application-dev/ability-deprecated/stage-ability-continuation.md +++ /dev/null @@ -1,290 +0,0 @@ -# Ability Continuation Development - -## When to Use - -Ability continuation is to continue the current mission of an application, including the UI component state variables and distributed objects, on another device. The UI component state variables are used to synchronize UI data, and the distributed objects are used to synchronize memory data. - -## Available APIs - -The following table lists the APIs used for ability continuation. For details about the APIs, see [UIAbility](../reference/apis/js-apis-app-ability-uiAbility.md). - -**Table 1** Ability continuation APIs - -|API| Description| -|:------ | :------| -| onContinue(wantParam : {[key: string]: any}): OnContinueResult | Called by the initiator to store the data required for continuation. The return value indicates whether the continuation request is accepted. The value **AGREE** means that the continuation request is accepted, **REJECT** means that the continuation request is rejected, and **MISMATCH** means a version mismatch.| -| onCreate(want: Want, param: AbilityConstant.LaunchParam): void; | Called by the target to restore the data and UI page in the multi-instance ability scenario.| -| onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; | Called by the target to restore the data and UI page in the singleton ability scenario.| - - - -**Figure 1** Ability continuation development - -![continuation_dev](figures/continuation-info.png) - -In effect, ability continuation is a cross-device ability startup that carries data. When a continuation action is initiated, the system on device A calls back **onContinue()** of the application. You must implement storage of the current data in this API. Then, the system initiates a cross-device ability startup on device B and transmits the data to device B. The system on device B calls back **onCreate()** or **onNewWant()**. You must implement restoration of the transmitted data in this API. - -## How to Develop - -The code snippets provided below are all from [Sample](https://gitee.com/openharmony/ability_dmsfwk/tree/master/services/dtbschedmgr/test/samples/continuationManualTestSuite). - -### Application Continuation - -1. Modify the configuration file. - - - Configure the application to support ability continuation. - - Set the **continuable** field in the **module.json5** file to **true**. The default value is **false**. If this parameter is set to **false**, the application cannot be continued on another device. - - ```javascript - { - "module": { - "abilities": [ - { - "continuable": true - } - ] - } - } - ``` - - - Configure the application startup type. - - If **launchType** is set to **multiton** in the **module.json5** file, the application is of the multi-instance launch type. During ability continuation, regardless of whether the application is already open, the target starts the application and restores the UI page. If **launchType** is set to **singleton**, the application is of the singleton launch type. If the application is already open, the target clears the existing page stack and restores the UI page. For more information, see "Launch Type" in [Ability Development](./stage-ability.md). - - Configure a multi-instance application as follows: - - ```javascript - { - "module": { - "abilities": [ - { - "launchType": "multiton" - } - ] - } - } - ``` - - Configure a singleton application as follows or retain the default settings of **launchType**: - - ```javascript - { - "module": { - "abilities": [ - { - "launchType": "singleton" - } - ] - } - } - ``` - - - Apply for the distributed permissions. - - Declare the **DISTRIBUTED_DATASYNC** permission in the **module.json5** file for the application. - - ```javascript - "requestPermissions": [ - { - "name": "ohos.permission.DISTRIBUTED_DATASYNC" - }, - ``` - - This permission must be granted by the user in a dialog box when the application is started for the first time. To enable the application to display a dialog box to ask for the permission, add the following code to **onWindowStageCreate** of the **Ability** class: - - ```javascript - requestPermissions = async () => { - let permissions: Array = [ - "ohos.permission.DISTRIBUTED_DATASYNC" - ]; - let needGrantPermission = false - let accessManger = accessControl.createAtManager() - Logger.info("app permission get bundle info") - let bundleInfo = await bundle.getApplicationInfo(BUNDLE_NAME, 0, 100) - Logger.info(`app permission query permission ${bundleInfo.accessTokenId.toString()}`) - for (const permission of permissions) { - Logger.info(`app permission query grant status ${permission}`) - try { - let grantStatus = await accessManger.verifyAccessToken(bundleInfo.accessTokenId, permission) - if (grantStatus === PERMISSION_REJECT) { - needGrantPermission = true - break; - } - } catch (err) { - Logger.error(`app permission query grant status error ${permission} ${JSON.stringify(err)}`) - needGrantPermission = true - break; - } - } - if (needGrantPermission) { - Logger.info("app permission needGrantPermission") - try { - await accessManger.requestPermissionsFromUser(this.context, permissions) - } catch (err) { - Logger.error(`app permission ${JSON.stringify(err)}`) - } - } else { - Logger.info("app permission already granted") - } - } - ``` - - - -2. Implement the **onContinue()** API. - - The **onContinue()** API is called by the initiator to save the UI component state variables and memory data and prepare for continuation. After the application completes the continuation preparation, the system must return either **OnContinueResult.AGREE(0)** to accept the continuation request or an error code to reject the request. If this API is not implemented, the system rejects the continuation request by default. - - Modules to import: - - ```javascript - import UIAbility from '@ohos.app.ability.UIAbility'; - import AbilityConstant from '@ohos.app.ability.AbilityConstant'; - ``` - - To implement ability continuation, you must implement this API and have the value **AGREE** returned. - - You can obtain the target device ID (identified by the key **targetDevice**) and the version number (identified by the key **version**) of the application installed on the target device from the **wantParam** parameter of this API. The version number can be used for compatibility check. If the current application version is incompatible with that on the target device, **OnContinueResult.MISMATCH** can be returned to reject the continuation request. - - Example: - - ```javascript - onContinue(wantParam : {[key: string]: any}) { - Logger.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) - let workInput = AppStorage.Get('ContinueWork'); - // Set the user input data into wantParam. - wantParam["work"] = workInput // set user input data into want params - Logger.info(`onContinue input = ${wantParam["input"]}`); - return AbilityConstant.OnContinueResult.AGREE - } - ``` - -3. Implement the continuation logic in the **onCreate()** or **onNewWant()** API. - - The **onCreate()** API is called by the target. When the ability is started on the target device, this API is called to instruct the application to synchronize the memory data and UI component state, and triggers page restoration after the synchronization is complete. If the continuation logic is not implemented, the ability will be started in common startup mode and the page cannot be restored. - - The target device determines whether the startup is **LaunchReason.CONTINUATION** based on **launchReason** in **onCreate()**. - - After data restore is complete, call **restoreWindowStage** to trigger page restoration. - - You can also use **want.parameters.version** in the **want** parameter to obtain the application version number of the initiator. - - Example: - - ```javascript - import UIAbility from '@ohos.app.ability.UIAbility'; - import distributedObject from '@ohos.data.distributedDataObject'; - - export default class EntryAbility extends UIAbility { - storage : LocalStorag; - - onCreate(want, launchParam) { - Logger.info(`EntryAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) - if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { - // Obtain the user data from the want parameter. - let workInput = want.parameters.work - Logger.info(`work input ${workInput}`) - AppStorage.SetOrCreate('ContinueWork', workInput) - - this.storage = new LocalStorage(); - this.context.restoreWindowStage(this.storage); - } - } - } - ``` -For a singleton ability, use **onNewWant()** to achieve the same implementation. - -### Data Continuation - -Use distributed objects. - -Distributed objects allow cross-device data synchronization like local variables. For two devices that form a Super Device, when data in the distributed data object of an application is added, deleted, or modified on a device, the data for the same application is also updated on the other device. Both devices can listen for the data changes and online and offline states of the other. For details, see [Sharing Distributed Data Objects](../database/data-sync-of-distributed-data-object.md). - -In the ability continuation scenario, the distributed data object is used to synchronize the memory data from the local device to the target device. - -- In **onContinue()**, the initiator saves the data to be migrated to the distributed object, calls the **save()** API to save the data and synchronize the data to the target device, sets the session ID, and sends the session ID to the target device through **wantParam**. - - ```javascript - import UIAbility from '@ohos.app.ability.UIAbility'; - import distributedObject from '@ohos.data.distributedDataObject'; - - var g_object = distributedObject.createDistributedObject({data:undefined}); - - export default class EntryAbility extends UIAbility { - sessionId : string; - - onContinue(wantParam : {[key: string]: any}) { - Logger.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) - - if (g_object.__sessionId === undefined) { - this.sessionId = distributedObject.genSessionId() - Logger.info(`onContinue generate new sessionId`) - } - else { - this.sessionId = g_object.__sessionId; - } - - wantParam["session"] = this.sessionId - g_object.data = AppStorage.Get('ContinueStudy'); - Logger.info(`onContinue sessionId = ${this.sessionId}, name = ${g_object.data}`) - g_object.setSessionId(this.sessionId); - g_object.save(wantParam.targetDevice, (result, data)=>{ - Logger.info("save callback"); - Logger.info("save sessionId " + data.sessionId); - Logger.info("save version " + data.version); - Logger.info("save deviceId " + data.deviceId); - }); - ``` - -- The target device obtains the session ID from **onCreate()**, creates a distributed object, and associates the distributed object with the session ID. In this way, the distributed object can be synchronized. Before calling **restoreWindowStage**, ensure that all distributed objects required for continuation have been associated. - - ```javascript - import UIAbility from '@ohos.app.ability.UIAbility'; - import distributedObject from '@ohos.data.distributedDataObject'; - - var g_object = distributedObject.createDistributedObject({data:undefined}); - - export default class EntryAbility extends UIAbility { - storage : LocalStorag; - - onCreate(want, launchParam) { - Logger.info(`EntryAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) - if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { - // Obtain the session ID of the distributed data object from the want parameter. - this.sessionId = want.parameters.session - Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`) - - // Before fetching data from the remote device, reset g_object.data to undefined. - g_object.data = undefined; - // Set the session ID, so the target will fetch data from the remote device. - g_object.setSessionId(this.sessionId); - - AppStorage.SetOrCreate('ContinueStudy', g_object.data) - this.storage = new LocalStorage(); - this.context.restoreWindowStage(this.storage); - } - - } - } - ``` - -### More Information - -1. Timeout - - - If the application to be continued is not installed on the target device, the system checks whether the application can be installed on it and waits for a response for 4 seconds. If no response is received within 4 seconds, the caller receives a timeout error code, which means that the application cannot be installed on the target device. If the application can be installed, the system prompts the consumer to install the application on the target device. The consumer can initiate the continuation again after the installation. - - If the application to be continued has been installed on the target device, the system waits for a response to the continuation request for 20 seconds. If no response is received within 20 seconds, the caller receives a timeout error code, which means that the continuation fails. - -2. By default, the system supports page stack information migration, which means that the page stack of the initiator will be automatically migrated to the target device. No adaptation is required. - -### Restrictions - -1. The continuation must be performed between the same ability, which means the same bundle name, module name, and ability name. For details, see [Application Package Structure Configuration File](../quick-start/module-configuration-file.md). -2. Currently, the application can only implement the continuation capability. The continuation action must be initiated by the system. - -### Best Practice - -For better user experience, you are advised to use the **wantParam** parameter to transmit data smaller than 100 KB and use distributed objects to transmit data larger than 100 KB. - - \ No newline at end of file diff --git a/en/application-dev/ability-deprecated/stage-ability.md b/en/application-dev/ability-deprecated/stage-ability.md deleted file mode 100644 index 2cd18f7aa3052cee86785d55bc81d68cfdece802..0000000000000000000000000000000000000000 --- a/en/application-dev/ability-deprecated/stage-ability.md +++ /dev/null @@ -1,304 +0,0 @@ -# Ability Development -## When to Use -Ability development in the [stage model](stage-brief.md) is significantly different from that in the FA model. The stage model requires you to declare the application package structure in the **module.json5** and **app.json5** files during application development. For details about the configuration file, see [Application Package Structure Configuration File](../quick-start/application-package-structure-stage.md). To develop an ability based on the stage model, implement the following logic: -- Create an ability that supports screen viewing and human-machine interaction. You must implement the following scenarios: ability lifecycle callbacks, obtaining ability configuration, requesting permissions, and notifying environment changes. -- Start an ability. You need to implement ability startup on the same device, on a remote device, or with a specified UI page. -- Call abilities. For details, see [Call Development](stage-call.md). -- Connect to and disconnect from a Service Extension ability. For details, see [Service Extension Ability Development](stage-serviceextension.md). -- Continue the ability on another device. For details, see [Ability Continuation Development](stage-ability-continuation.md). - -### Launch Type -An ability can be launched in the **standard**, **singleton**, or **specified** mode, as configured by **launchType** in the **module.json5** file. Depending on the launch type, the action performed when the ability is started differs, as described below. - -| Launch Type | Description |Action | -| ----------- | ------- |---------------- | -| multiton | Multi-instance mode| A new instance is started each time an ability starts.| -| singleton | Singleton mode | Default type. The ability has only one instance in the system. If an instance already exists when an ability is started, that instance is reused.| -| specified | Instance-specific| The internal service of an ability determines whether to create multiple instances during running.| - -By default, the singleton mode is used. The following is an example of the **module.json5** file: -```json -{ - "module": { - "abilities": [ - { - "launchType": "singleton", - } - ] - } -} -``` -## Creating an Ability -### Available APIs -The table below describes the APIs provided by the **AbilityStage** class, which has the **context** attribute. For details about the APIs, see [AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md). - -**Table 1** AbilityStage APIs -|API|Description| -|:------|:------| -|onCreate(): void|Called when an ability stage is created.| -|onAcceptWant(want: Want): string|Called when a specified ability is started.| -|onConfigurationUpdated(config: Configuration): void|Called when the global configuration is updated.| - -The table below describes the APIs provided by the **Ability** class. For details about the APIs, see [UIAbility](../reference/apis/js-apis-app-ability-uiAbility.md). - -**Table 2** Ability APIs - -|API|Description| -|:------|:------| -|onCreate(want: Want, param: AbilityConstant.LaunchParam): void|Called when an ability is created.| -|onDestroy(): void|Called when the ability is destroyed.| -|onWindowStageCreate(windowStage: window.WindowStage): void|Called when a **WindowStage** is created for the ability. You can use the **window.WindowStage** APIs to implement operations such as page loading.| -|onWindowStageDestroy(): void|Called when the **WindowStage** is destroyed for the ability.| -|onForeground(): void|Called when the ability is switched to the foreground.| -|onBackground(): void|Called when the ability is switched to the background.| -|onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void|Called when the ability launch type is set to **singleton**.| -|onConfigurationUpdated(config: Configuration): void|Called when the configuration of the environment where the ability is running is updated.| -### Implementing AbilityStage and Ability Lifecycle Callbacks -To create Page abilities for an application in the stage model, you must implement the **AbilityStage** class and ability lifecycle callbacks, and use the **Window** class to set the pages. The sample code is as follows: -1. Import the **AbilityStage** module. - ```ts - import AbilityStage from "@ohos.app.ability.AbilityStage"; - ``` -2. Implement the **AbilityStage** class. The default relative path generated by the APIs is **entry\src\main\ets\Application\AbilityStage.ts**. - ```ts - export default class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage onCreate") - } - } - ``` -3. Import the **Ability** module. - ```js - import UIAbility from '@ohos.app.ability.UIAbility'; - ``` -4. Implement the lifecycle callbacks of the **UIAbility** class. The default relative path generated by the APIs is **entry\src\main\ets\entryability\EntryAbility.ts**. - - In the **onWindowStageCreate(windowStage)** API, use **loadContent** to set the application page to be loaded. For details about how to use the **Window** APIs, see [Window Development](../windowmanager/application-window-stage.md). - ```ts - export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - console.log("EntryAbility onCreate") - } - - onDestroy() { - console.log("EntryAbility onDestroy") - } - - onWindowStageCreate(windowStage) { - console.log("EntryAbility onWindowStageCreate") - - windowStage.loadContent("pages/index").then(() => { - console.log("EntryAbility load content succeed") - }).catch((error) => { - console.error("EntryAbility load content failed with error: " + JSON.stringify(error)) - }) - } - - onWindowStageDestroy() { - console.log("EntryAbility onWindowStageDestroy") - } - - onForeground() { - console.log("EntryAbility onForeground") - } - - onBackground() { - console.log("EntryAbility onBackground") - } - } - ``` -### Obtaining AbilityStage and Ability Configurations -Both the **AbilityStage** and **Ability** classes have the **context** attribute. An application can obtain the context of an **Ability** instance through **this.context** to obtain the configuration details. - -The following example shows how an application obtains the bundle code directory, HAP file name, ability name, and system language through the **context** attribute in the **AbilityStage** class. The sample code is as follows: - -```ts -import AbilityStage from "@ohos.app.ability.AbilityStage"; - -export default class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage onCreate") - let context = this.context - console.log("MyAbilityStage bundleCodeDir" + context.bundleCodeDir) - - let currentHapModuleInfo = context.currentHapModuleInfo - console.log("MyAbilityStage hap module name" + currentHapModuleInfo.name) - console.log("MyAbilityStage hap module mainAbilityName" + currentHapModuleInfo.mainAbilityName) - - let config = this.context.config - console.log("MyAbilityStage config language" + config.language) - } -} -``` - -The following example shows how an application obtains the bundle code directory, HAP file name, ability name, and system language through the **context** attribute in the **Ability** class. The sample code is as follows: -```ts -import UIAbility from '@ohos.app.ability.UIAbility'; - -export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - console.log("EntryAbility onCreate") - let context = this.context - console.log("EntryAbility bundleCodeDir" + context.bundleCodeDir) - - let abilityInfo = this.context.abilityInfo; - console.log("EntryAbility ability bundleName" + abilityInfo.bundleName) - console.log("EntryAbility ability name" + abilityInfo.name) - - let config = this.context.config - console.log("EntryAbility config language" + config.language) - } -} -``` -### Notifying of Environment Changes -Environment changes include changes of global configurations and ability configurations. Currently, the global configurations include the system language and color mode. The change of global configurations is generally triggered by configuration items in **Settings** or icons in **Control Panel**. The ability configuration is specific to a single **Ability** instance, including the display ID, screen resolution, and screen orientation. The configuration is related to the display where the ability is located, and the change is generally triggered by the window. Before configuring a project, define the project in the [Configuration](../reference/apis/js-apis-application-configuration.md) class. - -For an application in the stage model, when the configuration changes, its abilities are not restarted, but the **onConfigurationUpdated(config: Configuration)** callback is triggered. If the application needs to perform processing based on the change, you can override **onConfigurationUpdated**. Note that the **Configuration** object in the callback contains all the configurations of the current ability, not only the changed configurations. - -The following example shows the implementation of the **onConfigurationUpdated** callback in the **AbilityStage** class. The callback is triggered when the system language and color mode are changed. -```ts -import AbilityStage from '@ohos.app.ability.AbilityStage'; -import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant'; - -export default class MyAbilityStage extends AbilityStage { - onConfigurationUpdated(config) { - if (config.colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK) { - console.log('colorMode changed to dark') - } - } -} -``` - -The following example shows the implementation of the **onConfigurationUpdated** callback in the **Ability** class. The callback is triggered when the system language, color mode, or display parameters (such as the direction and density) change. -```ts -import UIAbility from '@ohos.app.ability.UIAbility'; -import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant'; - -export default class EntryAbility extends UIAbility { - direction : number; - - onCreate(want, launchParam) { - this.direction = this.context.config.direction - } - - onConfigurationUpdated(config) { - if (this.direction !== config.direction) { - console.log(`direction changed to ${config.direction}`) - } - } -} -``` -## Starting an Ability -### Available APIs -The **Ability** class has the **context** attribute, which belongs to the **AbilityContext** class. The **AbilityContext** class has the **abilityInfo**, **currentHapModuleInfo**, and other attributes as well as the APIs used for starting abilities. For details, see [AbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md). - -**Table 3** AbilityContext APIs -|API|Description| -|:------|:------| -|startAbility(want: Want, callback: AsyncCallback\): void|Starts an ability.| -|startAbility(want: Want, options?: StartOptions): Promise\|Starts an ability.| -|startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void|Starts an ability with the account ID.| -|startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\|Starts an ability with the account ID.| -|startAbilityForResult(want: Want, callback: AsyncCallback\): void|Starts an ability with the returned result.| -|startAbilityForResult(want: Want, options?: StartOptions): Promise\|Starts an ability with the returned result.| -|startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void|Starts an ability with the execution result and account ID.| -|startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\|Starts an ability with the execution result and account ID.| -### Starting an Ability on the Same Device -An application can obtain the context of an **Ability** instance through **this.context** and then use the **startAbility** API in the **AbilityContext** class to start the ability. The ability can be started by specifying **Want**, **StartOptions**, and **accountId**, and the operation result can be returned using a callback or **Promise** instance. The sample code is as follows: -```ts -let context = this.context -let want = { - "deviceId": "", - "bundleName": "com.example.MyApplication", - "abilityName": "EntryAbility" -}; -context.startAbility(want).then(() => { - console.log("Succeed to start ability") -}).catch((error) => { - console.error("Failed to start ability with error: "+ JSON.stringify(error)) -}) -``` - -### Starting an Ability on a Remote Device ->This feature applies only to system applications, since the **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications. -In the cross-device scenario, you must specify the ID of the remote device. The sample code is as follows: -```ts -let context = this.context -let want = { - "deviceId": getRemoteDeviceId(), - "bundleName": "com.example.MyApplication", - "abilityName": "EntryAbility" -}; -context.startAbility(want).then(() => { - console.log("Succeed to start remote ability") -}).catch((error) => { - console.error("Failed to start remote ability with error: " + JSON.stringify(error)) -}) -``` -Obtain the ID of a specified device from **DeviceManager**. The sample code is as follows: -```ts -import deviceManager from '@ohos.distributedHardware.deviceManager'; -function getRemoteDeviceId() { - if (typeof dmClass === 'object' && dmClass !== null) { - let list = dmClass.getTrustedDeviceListSync(); - if (typeof (list) === 'undefined' || typeof (list.length) === 'undefined') { - console.log("EntryAbility onButtonClick getRemoteDeviceId err: list is null"); - return; - } - console.log("EntryAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); - return list[0].deviceId; - } else { - console.log("EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null"); - } -} -``` -Request the permission **ohos.permission.DISTRIBUTED_DATASYNC** from consumers. This permission is used for data synchronization. For details about the sample code for requesting permissions, see [abilityAccessCtrl.requestPermissionsFromUse](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9). -### Starting an Ability with the Specified Page -If the launch type of an ability is set to **singleton** and the ability has been started, the **onNewWant** callback is triggered when the ability is started again. You can pass start options through the **want**. For example, to start an ability with the specified page, use the **uri** or **parameters** parameter in the **want** to pass the page information. Currently, the ability in the stage model cannot directly use the **router** capability. You must pass the start options to the custom component and invoke the **router** method to display the specified page during the custom component lifecycle management. The sample code is as follows: - -When using **startAbility** to start an ability again, use the **uri** parameter in the **want** to pass the page information. -```ts -async function reStartAbility() { - try { - await this.context.startAbility({ - bundleName: "com.sample.MyApplication", - abilityName: "EntryAbility", - uri: "pages/second" - }) - console.log('start ability succeed') - } catch (error) { - console.error(`start ability failed with ${error.code}`) - } -} -``` - -Obtain the **want** parameter that contains the page information from the **onNewWant** callback of the ability. -```ts -import UIAbility from '@ohos.app.ability.UIAbility'; - -export default class EntryAbility extends UIAbility { - onNewWant(want, launchParams) { - globalThis.newWant = want - } -} -``` - -Obtain the **want** parameter that contains the page information from the custom component and process the route based on the URI. -```ts -import router from '@ohos.router' - -@Entry -@Component -struct Index { - newWant = undefined - - onPageShow() { - console.info('Index onPageShow') - let newWant = globalThis.newWant - if (newWant.hasOwnProperty("uri")) { - router.push({ url: newWant.uri }); - globalThis.newWant = undefined - } - } -} -``` diff --git a/en/application-dev/ability-deprecated/stage-brief.md b/en/application-dev/ability-deprecated/stage-brief.md deleted file mode 100644 index 190644c2c0d7e114d0e898de1a8837695bdf049e..0000000000000000000000000000000000000000 --- a/en/application-dev/ability-deprecated/stage-brief.md +++ /dev/null @@ -1,114 +0,0 @@ -# Stage Model Overview - -## Design Ideas - -The stage model is designed to provide a better application development mode in the distributed environment. - -The following figure shows the design ideas of the stage model. - -![stagedesign](figures/stagedesign.png) - -The stage model is designed based on the following considerations: - -- Efficient management of application processes - -As the device memory becomes larger, the number of processes concurrently running in the system increases. If the number of concurrent processes reaches several hundreds, the overall power consumption and performance of the system will be adversely affected without effective management measures. To restrict the behavior of background processes, the stage model uses four measures: transient task, continuous task, agent task, and Work Scheduler task. With these measures, foreground processes will obtain guaranteed resources, thereby delivering a better user experience. - -- Native support for cross-device migration and multi-device collaboration - -OpenHarmony is a native distributed OS. Its application framework must be designed for easier component migration and collaboration across devices. The stage model achieves this design objective by providing features such as separation between ability and UI as well as integration of UI display and service capabilities. - -- Different window forms for various device types - -The stage model redefines the ability lifecycle. In terms of architecture, the component manager and window manager are decoupled. This facilitates adaptation between window forms and device types. - -## Basic Concepts - -The following figure shows the basic concepts in the stage model. - -![stageconcept](figures/stageconcept.png) - -- **HAP**: basic unit for building, distributing, and loading OpenHarmony applications. Each HAP corresponds to a module in the development state. In an application, **moduleName** uniquely identifies a module. -- **Bundle**: an OpenHarmony application identified by **appid**. A bundle can contain multiple HAP files. Each application has a **bundleName**. However, **bundleName** must be used together with **appid** and other information to uniquely identify an application. -- **AbilityStage**: runtime object of an HAP. It is created when the HAP is loaded to the process for the first time and is visible to developers in the runtime. -- **Application**: runtime object of a bundle. It is invisible to developers in the runtime. -- **Context**: base class that provides APIs in the runtime to obtain information such as the bundle name, module name, and path. The **Context** classes of the Ability and ExtensionAbility components inherit from this class. -- **Ability**: provides lifecycle callbacks, holds the ability context, and supports cross-device component migration and multi-device collaboration. -- **ExtensionAbility**: general name of scenario-based Extension abilities. The system defines multiple scenario-based **ExtensionAbility** classes, each of which has its own **ExtensionContext**. -- **WindowStage**: local window manager. -- **Window**: application window, which holds an ArkUI engine instance. -- **ArkUI Page**: UI developed based on ArkUI. - - -## Lifecycle - -The ability and ability stage are key objects in the application lifecycle. - -For details about the lifecycle differences between the stage model and FA model, see [Ability Framework Overview](ability-brief.md). This section focuses on the ability lifecycle transition and the scheduling relationships between the ability, ability stage, and window stage. - -![stageabilitylifecyclecallback](figures/stageabilitylifecyclecallback.png) - -To implement device adaptation and multi-window scalability, OpenHarmony decouples the component manager from the window manager. - -The ability lifecycle defined in the stage model includes only the creation, destruction, foreground, and background states. The gain focus and lose focus states that are closely related to UI are defined in the window stage. This implements weak coupling between the abilities and windows. On the service side, the window manager notifies the component manager of the foreground and background state changes, so the component manager only senses the foreground and background state changes but not the focus changes. - -There are two lifecycle states related to the window stage in **Ability**: **onWindowStageCreate** and **onWindowStageDestroy**. They are valid only for devices with the display capability. **onWindowStageCreate** is invoked when a window stage is created, where you can call **loadContent** to set pages to be loaded for the ability. **onWindowStageDestroy** is invoked when the window stage is destroyed, where you can release resources. - - -## Ability Instances and Missions - -Abilities can be started in any of the following modes: - -* **Singleton**: For each type of ability, only one instance exists in the application process. **Ability1** in the figure below is started in singleton mode. -* **Standard**: Each time **startAbility** is called, an instance of the specified ability type is created in the application process. **Ability2** in the figure below is started in standard mode. -* **Specified**: Before creating an **Ability** instance, you can create a key for the instance. Each time **startAbility** is called, the system asks the application which ability instance (corresponding to a key) will be used. **Ability3** in the figure below is started in specified mode. - -Each **Ability** instance corresponds to a mission in **Recents**. - -The mission corresponding to an ability instance has a snapshot of the ability instance. After the ability instance is destroyed, the ability class information and snapshot are retained in the mission until the user deletes the information or the storage space reaches the upper limit. - - ![AbilityComponentInstanceMission](figures/AbilityComponentInstanceMission.png) - -## ExtensionAbility Mechanism - -Different from the ability used for UI display, ExtensionAbility provides a restricted running environment. - -ExtensionAbility has the following features: - -- Its process runs independently from the main process but shares the same storage sandbox with the main process. There is no inter-process communication (IPC) between the ExtensionAbility process and the main process. - -- It has an independent context that provides scenario-specific APIs. - -- It is created by the system, rather than by applications. - -- The lifecycles of the ExtensionAbility component and process are managed by the system. - -The following figure uses the widget an example. **FormExtensionAbility** is the base class. You can inherit from this class to provide widget information. The lifecycle of the **FormExtensionAbility** instance and that of the ExtensionAbility process where the instance is located are managed by a system service named **FormManagerService**. - -![ExtensionAbility](figures/ExtensionAbility.png) - -## Process Model - -OpenHarmony forces strong control policies on application processes. No APIs are provided to configure multiple processes. All application processes are created and managed by the system. - -The processes of an application can be classified into three types: - -- Main process: runs the **UIAbility** component, UI, and service logic. - -- Extension process: runs classes derived from **ExtensionAbility** in the application. The lifecycle of this process is managed by a scenario-specific system service. - -- Render process: created for the WebView and used to load the WebView rendering library. - - The following figure shows the process model of an application. - - ![stageprocessmodel](figures/stageprocessmodel.png) - - - -## Application Package Structure - -For details about the project directory structure of the stage model, see [OpenHarmony Project Overview](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-project-overview-0000001218440650#section56487581904). - -For details about how to configure the application package structure of the stage model, see [Application Package Structure Configuration File](../quick-start/application-configuration-file-overview-stage.md). - - diff --git a/en/application-dev/ability-deprecated/stage-call.md b/en/application-dev/ability-deprecated/stage-call.md deleted file mode 100644 index d9269295e06633fa0f55bdebad51eb1c354f2934..0000000000000000000000000000000000000000 --- a/en/application-dev/ability-deprecated/stage-call.md +++ /dev/null @@ -1,309 +0,0 @@ -# Ability Call Development -## When to Use -Ability call is an extension of the ability capability. It enables an ability to be invoked by and communicate with external systems. The ability invoked can be either started in the foreground or created and run in the background. You can use the ability call to implement data sharing between two abilities (caller ability and callee ability) through inter-process communication (IPC). - -The core API used for the ability call is **startAbilityByCall**, which differs from **startAbility** in the following ways: - - **startAbilityByCall** supports ability startup in the foreground and background, whereas **startAbility** supports ability startup in the foreground only. - - The caller ability can use the **Caller** object returned by **startAbilityByCall** to communicate with the callee ability, but **startAbility** does not provide the communication capability. - -Ability call is usually used in the following scenarios: -- Communicating with the callee ability -- Starting the callee ability in the background - -**Table 1** Terms used in the ability call -|Term|Description| -|:------|:------| -|Caller ability|Ability that triggers the ability call.| -|Callee ability|Ability invoked by the ability call.| -|Caller |Object returned by **startAbilityByCall** and used by the caller ability to communicate with the callee ability.| -|Callee |Object held by the callee ability to communicate with the caller ability.| -|IPC |Inter-process communication.| - -The ability call process is as follows: - - The caller ability uses **startAbilityByCall** to obtain a **Caller** object and uses **call()** of the **Caller** object to send data to the callee ability. - - The callee ability, which holds a **Callee** object, uses **on()** of the **Callee** object to register a callback. This callback is invoked when the callee ability receives data from the caller ability. -![stage-call](figures/stage-call.png) - -> **NOTE** -> -> The launch type of the callee ability must be **singleton**. -> -> Currently, only system applications can use the ability call. - -## Available APIs -The table below describes the ability call APIs. For details, see [UIAbility](../reference/apis/js-apis-app-ability-uiAbility.md#caller). - -**Table 2** Ability call APIs -|API|Description| -|:------|:------| -|startAbilityByCall(want: Want): Promise\|Starts an ability in the foreground (through the **want** configuration) or background (default) and obtains the **Caller** object for communication with the ability. For details, see [AbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartabilitybycall) or **ServiceExtensionContext**.| -|on(method: string, callback: CalleeCallBack): void|Callback invoked when the callee ability registers a method.| -|off(method: string): void|Callback invoked when the callee ability deregisters a method.| -|call(method: string, data: rpc.Sequenceable): Promise\|Sends agreed sequenceable data to the callee ability.| -|callWithResult(method: string, data: rpc.Sequenceable): Promise\|Sends agreed sequenceable data to the callee ability and obtains the agreed sequenceable data returned by the callee ability.| -|release(): void|Releases the **Caller** object.| -|on(type: "release", callback: OnReleaseCallback): void|Callback invoked when the **Caller** object is released.| - -## How to Develop -The procedure for developing the ability call is as follows: -1. Create a callee ability. -2. Access the callee ability. - -### Creating a Callee Ability -For the callee ability, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use **on()** to register a listener. When data does not need to be received, use **off()** to deregister the listener. - -1. **Configure the ability launch type.** - - Set **launchType** of the callee ability to **singleton** in the **module.json5** file. - - |JSON Field|Description| - |:------|:------| - |"launchType"|Ability launch type. Set this parameter to **singleton**.| - - An example of the ability configuration is as follows: - - ```json - "abilities":[{ - "name": ".CalleeAbility", - "srcEntry": "./ets/CalleeAbility/CalleeAbility.ts", - "launchType": "singleton", - "description": "$string:CalleeAbility_desc", - "icon": "$media:icon", - "label": "$string:CalleeAbility_label", - "exported": true - }] - ``` - -2. **Import the UIAbility module.** - - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - ``` - -3. **Define the agreed sequenceable data.** - - The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string. The code snippet is as follows: - - ```ts - export default class MySequenceable { - num: number = 0 - str: string = "" - - constructor(num, string) { - this.num = num - this.str = string - } - - marshalling(messageParcel) { - messageParcel.writeInt(this.num) - messageParcel.writeString(this.str) - return true - } - - unmarshalling(messageParcel) { - this.num = messageParcel.readInt() - this.str = messageParcel.readString() - return true - } - } - ``` - -4. **Implement Callee.on and Callee.off.** - - The time to register a listener for the callee ability 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 code snippet is as follows: - - ```ts - const TAG: string = '[CalleeAbility]' - const MSG_SEND_METHOD: string = 'CallSendMsg' - - function sendMsgCallback(data) { - console.log('CalleeSortFunc called') - - // Obtain the sequenceable data sent by the caller ability. - let receivedData = new MySequenceable(0, '') - data.readSequenceable(receivedData) - console.log(`receiveData[${receivedData.num}, ${receivedData.str}]`) - - // Process the data. - // Return the sequenceable data result to the caller ability. - return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`) - } - - export default class CalleeAbility extends Ability { - onCreate(want, launchParam) { - try { - this.callee.on(MSG_SEND_METHOD, sendMsgCallback) - } catch (error) { - console.log(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`) - } - } - - onDestroy() { - try { - this.callee.off(MSG_SEND_METHOD) - } catch (error) { - console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`) - } - } - } - ``` - -### Accessing the Callee Ability -1. **Import the Ability module.** - - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - ``` - -2. **Obtain the Caller object.** - - The **context** attribute of the ability implements **startAbilityByCall** to obtain the **Caller** object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the **Caller** object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements. The code snippet is as follows: - - ```ts - // Register the onRelease listener of the caller ability. - private regOnRelease(caller) { - try { - caller.on("release", (msg) => { - console.log(`caller onRelease is called ${msg}`) - }) - console.log('caller register OnRelease succeed') - } catch (error) { - console.log(`caller register OnRelease failed with ${error}`) - } - } - - async onButtonGetCaller() { - try { - this.caller = await context.startAbilityByCall({ - bundleName: 'com.samples.CallApplication', - abilityName: 'CalleeAbility' - }) - if (this.caller === undefined) { - console.log('get caller failed') - return - } - console.log('get caller success') - this.regOnRelease(this.caller) - } catch (error) { - console.log(`get caller failed with ${error}`) - } - } - ``` - - In the cross-device scenario, you need to specify the ID of the peer device. The code snippet is as follows: - - ```ts - async onButtonGetRemoteCaller() { - var caller = undefined - var context = this.context - - context.startAbilityByCall({ - deviceId: getRemoteDeviceId(), - bundleName: 'com.samples.CallApplication', - abilityName: 'CalleeAbility' - }).then((data) => { - if (data != null) { - caller = data - console.log('get remote caller success') - // Register the onRelease listener of the caller ability. - caller.on("release", (msg) => { - console.log(`remote caller onRelease is called ${msg}`) - }) - console.log('remote caller register OnRelease succeed') - } - }).catch((error) => { - console.error(`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 code snippet is as follows: - - ```ts - import deviceManager from '@ohos.distributedHardware.deviceManager'; - var dmClass; - function getRemoteDeviceId() { - if (typeof dmClass === 'object' && dmClass != null) { - var list = dmClass.getTrustedDeviceListSync() - if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { - console.log("EntryAbility onButtonClick getRemoteDeviceId err: list is null") - return - } - console.log("EntryAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId) - return list[0].deviceId - } else { - console.log("EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null") - } - } - ``` - - In the cross-device scenario, your application must also apply for the data synchronization permission from end users. The code snippet is as follows: - - ```ts - import abilityAccessCtrl from '@ohos.abilityAccessCtrl.d.ts'; - - requestPermission() { - let context = this.context - let permissions: Array = ['ohos.permission.DISTRIBUTED_DATASYNC'] - let atManager = abilityAccessCtrl.createAtManager(); - atManager.requestPermissionsFromUser(context, permissions).then((data) => { - console.log("Succeed to request permission from user with data: "+ JSON.stringify(data)) - }).catch((error) => { - console.log("Failed to request permission from user with error: "+ JSON.stringify(error)) - }) - } - ``` - -3. **Send agreed sequenceable data.** - - The sequenceable data can be sent to the callee ability with or without a return value. The method and sequenceable data must be consistent with those of the callee ability. The following example describes how to send data to the callee ability. The code snippet is as follows: - - ```ts - const MSG_SEND_METHOD: string = 'CallSendMsg' - async onButtonCall() { - try { - let msg = new MySequenceable(1, 'origin_Msg') - await this.caller.call(MSG_SEND_METHOD, msg) - } catch (error) { - console.log(`caller call failed with ${error}`) - } - } - ``` - - In the following, **CallWithResult** is used to send data **originMsg** to the callee ability and assign the data processed by the **CallSendMsg** method to **backMsg**. The code snippet is as follows: - - ```ts - const MSG_SEND_METHOD: string = 'CallSendMsg' - originMsg: string = '' - backMsg: string = '' - async onButtonCallWithResult(originMsg, backMsg) { - try { - let msg = new MySequenceable(1, originMsg) - const data = await this.caller.callWithResult(MSG_SEND_METHOD, msg) - console.log('caller callWithResult succeed') - - let result = new MySequenceable(0, '') - data.readSequenceable(result) - backMsg(result.str) - console.log(`caller result is [${result.num}, ${result.str}]`) - } catch (error) { - console.log(`caller callWithResult failed with ${error}`) - } - } - ``` - -4. **Release the Caller object.** - - When the **Caller** object is no longer required, use **release()** to release it. The code snippet is as follows: - - ```ts - releaseCall() { - try { - this.caller.release() - this.caller = undefined - console.log('caller release succeed') - } catch (error) { - console.log(`caller release failed with ${error}`) - } - } - ``` \ No newline at end of file diff --git a/en/application-dev/ability-deprecated/stage-formextension.md b/en/application-dev/ability-deprecated/stage-formextension.md deleted file mode 100644 index 8a0425f4fab41b97cd15ecb9986f77b4a108ae7a..0000000000000000000000000000000000000000 --- a/en/application-dev/ability-deprecated/stage-formextension.md +++ /dev/null @@ -1,417 +0,0 @@ -# Stage Widget Development - -## Widget Overview - -A widget is a set of UI components that display important information or operations specific to an application. It provides users with direct access to a desired application service, without the need to open the application first. - -A widget usually appears as a part of the UI of another application (which currently can only be a system application) and provides basic interactive features such as opening a UI page or sending a message. - -Before you get started, it would be helpful if you have a basic understanding of the following concepts: - -- Widget provider: an atomic service that provides the widget content to display and controls how widget components are laid out and how they interact with users. -- Widget host: an application that displays the widget content and controls the widget location. -- Widget Manager: a resident agent that provides widget management features such as periodic widget updates. - -> **NOTE** -> -> The widget host and provider do not need to be running all the time. The Widget Manager will start the widget provider to obtain widget information when a widget is added, deleted, or updated. - -You only need to develop the widget provider. The system automatically handles the work of the widget host and Widget Manager. - -The widget provider controls the widget content to display, the layout of components used in the widget, and click events bound to the components. - -## When to Use - -Carry out the following operations to develop the widget provider based on the [stage model](stage-brief.md): - -1. Implement lifecycle callbacks by using the **FormExtension** APIs. -2. Create a **FormBindingData** instance. -3. Update a widget by using the **FormProvider** APIs. -4. Develop the widget UI page. - -## Available APIs - -The **FormExtension** class has the following APIs. For details, see [FormExtension](../reference/apis/js-apis-app-form-formExtensionAbility.md). - -**Table 1** FormExtension APIs - -| API | Description | -| :----------------------------------------------------------- | :------------------------------------------- | -| onCreate(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a 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 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 widget has been destroyed. | -| onConfigurationUpdated(config: Configuration): void; | Called when the configuration of the environment where the widget is running is updated. | - -The **FormExtension** class also has a member context, that is, the **FormExtensionContext** class. For details, see [FormExtensionContext](../reference/apis/js-apis-inner-application-formExtensionContext.md). - -**Table 2** FormExtensionContext APIs - -| API | Description | -| :----------------------------------------------------------- | :----------------------------------------------------------- | -| startAbility(want: Want, callback: AsyncCallback<void>): void | Starts an ability. This API uses an asynchronous callback to return the result. (This is a system API and cannot be called by third-party applications.)| -| startAbility(want: Want): Promise<void> | Starts an ability. This API uses a promise to return the result. (This is a system API and cannot be called by third-party applications.)| - -The table below describes the **FormProvider** APIs. For details, see [FormProvider](../reference/apis/js-apis-application-formProvider.md). - -**Table 3** FormProvider APIs - -| API | Description | -| :----------------------------------------------------------- | :------------------------------------------------ | -| setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback<void>): void; | Sets the next refresh time for a widget. This API uses an asynchronous callback to return the result. | -| setFormNextRefreshTime(formId: string, minute: number): Promise<void>; | Sets the next refresh time for a widget. This API uses a promise to return the result.| -| updateForm(formId: string, formBindingData: FormBindingData, callback: AsyncCallback<void>): void; | Updates a widget. This API uses an asynchronous callback to return the result. | -| updateForm(formId: string, formBindingData: FormBindingData): Promise<void>; | Updates a widget. This API uses a promise to return the result. | - -## How to Develop - -### Creating a FormExtension Instance - -To create a widget in the stage model, you need to implement lifecycle callbacks using the **FormExtension** APIs. The code snippet is as follows: - -1. Import the required modules. - - ```javascript - import FormExtension from '@ohos.app.ability.FormExtension'; - import formBindingData from '@ohos.app.form.formBindingData'; - import formInfo from '@ohos.app.form.formInfo'; - import formProvider from '@ohos.app.form.formProvider'; - ``` - -2. Implement lifecycle callbacks for the widget. - - ```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 or update. - let obj = { - "title": "titleOnCreate", - "detail": "detailOnCreate" - }; - let formData = formBindingData.createFormBindingData(obj); - return formData; - } - onCastToNormal(formId) { - // Called when the widget host converts the temporary widget into a normal one. The widget provider should do something to respond to the conversion. - console.log('FormAbility onCastToNormal'); - } - onUpdate(formId) { - // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. - console.log('FormAbility onUpdate'); - let obj = { - "title": "titleOnUpdate", - "detail": "detailOnUpdate" - }; - let formData = formBindingData.createFormBindingData(obj); - formProvider.updateForm(formId, formData).catch((error) => { - console.log('FormAbility updateForm, error:' + JSON.stringify(error)); - }); - } - onVisibilityChange(newStatus) { - // Called when the widget host initiates an event about visibility changes. The widget provider should do something to respond to the notification. - console.log('FormAbility onVisibilityChange'); - } - onEvent(formId, message) { - // If the widget supports event triggering, override this method and implement the trigger. - console.log('FormAbility onEvent'); - } - onDestroy(formId) { - // Delete widget data. - console.log('FormAbility onDestroy'); - } - onConfigurationUpdated(config) { - console.log('FormAbility onConfigurationUpdated, config:' + JSON.stringify(config)); - } - } - ``` - -### Configuring the Widget Configuration File - -- Configure Extension ability information under **extensionAbilities** in the **module.json5** file. The internal field structure is described as follows: - - | Name | Description | Data Type | Default Value Allowed | - | ----------- | ------------------------------------------------------------ | ---------- | -------------------- | - | name | Name of the Extension ability. This field must be specified. | String | No | - | srcEntry | 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 (configuration information) of the Extension ability.| Object | Yes (initial value: left empty) | - - 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. - - Example configuration: - - ```json - "extensionAbilities": [{ - "name": "FormAbility", - "srcEntry": "./ets/FormAbility/FormAbility.ts", - "label": "$string:form_FormAbility_label", - "description": "$string:form_FormAbility_desc", - "type": "form", - "metadata": [{ - "name": "ohos.extension.form", - "resource": "$profile:form_config" - }] - }] - ``` - -- 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: - - | Name | Description | Data Type | Default Value Allowed | - | ------------------- | ------------------------------------------------------------ | ---------- | ------------------------ | - | name | Class name of the 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.
**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.
**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.
**true**: The widget can be updated at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** takes precedence over **scheduledUpdateTime**.
**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.
**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| 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.
**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| 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) | - | metaData | Metadata of the widget. This field contains the array of the **customizeData** field. | Object | Yes (initial value: left empty) | - - Example configuration: - - ```json - { - "forms": [{ - "name": "widget", - "description": "This is a widget.", - "src": "./js/widget/pages/index/index", - "window": { - "autoDesignWidth": true, - "designWidth": 720 - }, - "isDefault": true, - "colorMode": "auto", - "supportDimensions": ["2*2"], - "defaultDimension": "2*2", - "updateEnabled": true, - "scheduledUpdateTime": "10:30", - "formConfigAbility": "ability://ohos.samples.FormApplication.EntryAbility" - }] - } - ``` - - -### Persistently Storing Widget Data - -A widget provider is usually started when it is needed to provide 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. - -```javascript - onCreate(want) { - console.log('FormAbility onCreate'); - - 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 data for subsequent use, such as widget instance retrieval or update. - // The storeFormInfo API is not implemented here. - storeFormInfo(formId, formName, tempFlag, want); - - let obj = { - "title": "titleOnCreate", - "detail": "detailOnCreate" - }; - let formData = formBindingData.createFormBindingData(obj); - return formData; - } -``` - -You should override **onDestroy** to implement widget data deletion. - -```javascript - onDestroy(formId) { - console.log('FormAbility onDestroy'); - - // You need to implement the code for deleting the persistent widget data. - // The deleteFormInfo API is not implemented here. - deleteFormInfo(formId); - } -``` - -For details about how to implement persistent data storage, see [Application Data Persistence Overview](../database/app-data-persistence-overview.md). - -The **Want** object passed in by the widget host to the widget provider contains a flag that specifies whether the requested widget is normal or temporary. - -- Normal widget: a widget persistently used by the widget host - -- Temporary widget: a widget temporarily used by the widget host - -Data of a temporary widget will be deleted on the Widget Manager if the widget framework is killed and restarted. The widget provider, however, is not notified of the deletion and still keeps the data. Therefore, the widget provider needs to clear the data of temporary widgets proactively if the data has been kept for a long period of time. If the widget host has converted a temporary widget into a normal one, the widget provider should change the widget data from temporary storage to persistent storage. Otherwise, the widget data may be deleted by mistake. - -### Updating Widget Data - -When an application initiates a scheduled or periodic update, the application obtains the latest data and calls **updateForm** to update the widget. The code snippet is as follows: - -```javascript -onUpdate(formId) { - // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. - console.log('FormAbility onUpdate'); - let obj = { - "title": "titleOnUpdate", - "detail": "detailOnUpdate" - }; - let formData = formBindingData.createFormBindingData(obj); - // Call the updateForm() method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged. - formProvider.updateForm(formId, formData).catch((error) => { - console.log('FormAbility updateForm, error:' + JSON.stringify(error)); - }); -} -``` - -### Developing the Widget UI Page - -You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget. - -> **NOTE** -> -> Only the JavaScript-based web-like development paradigm is supported when developing the widget UI. - - - HML file: - ```html -
- -
- -
-
- {{title}} - {{detail}} -
-
-
- ``` - - - CSS file: - - ```css -.container { - flex-direction: column; - justify-content: center; - align-items: center; -} - -.bg-img { - flex-shrink: 0; - height: 100%; -} - -.container-inner { - flex-direction: column; - justify-content: flex-end; - align-items: flex-start; - height: 100%; - width: 100%; - padding: 12px; -} - -.title { - font-size: 19px; - font-weight: bold; - color: white; - text-overflow: ellipsis; - max-lines: 1; -} - -.detail_text { - font-size: 16px; - color: white; - opacity: 0.66; - text-overflow: ellipsis; - max-lines: 1; - margin-top: 6px; -} - ``` - - - JSON file: - ```json - { - "data": { - "title": "TitleDefault", - "detail": "TextDefault" - }, - "actions": { - "routerEvent": { - "action": "router", - "abilityName": "EntryAbility", - "params": { - "message": "add detail" - } - } - } - } - ``` - -Now you've got a widget shown below. - -![fa-form-example](figures/fa-form-example.png) - -### Developing Widget Events - -You can set router and message events for components on a widget. The router event applies to ability redirection, and the message event applies to custom click events. The key steps are as follows: - -1. Set the **onclick** field in the HML file to **routerEvent** or **messageEvent**, depending on the **actions** settings in the JSON file. -2. Set the router event. - - **action**: **"router"**, which indicates a router event. - - **abilityName**: target ability name, for example, **EntryAbility**, which is the default main ability name in DevEco Studio for the stage model. - - **params**: custom parameters of the target ability. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target ability. For example, in the lifecycle function **onCreate** of the EntryAbility in the stage model, you can obtain **want** and its **parameters** field. -3. Set the message event. - - **action**: **"message"**, which indicates a message event. - - **params**: custom parameters of the message event. Set them as required. The value can be obtained from **message** in the widget lifecycle function **onEvent**. - -The code snippet is as follows: - - - HML file: - ```html -
- -
- -
-
- {{title}} - {{detail}} -
-
-
- ``` - - - JSON file: - ```json - { - "data": { - "title": "TitleDefault", - "detail": "TextDefault" - }, - "actions": { - "routerEvent": { - "action": "router", - "abilityName": "EntryAbility", - "params": { - "message": "add detail" - } - }, - "messageEvent": { - "action": "message", - "params": { - "message": "add detail" - } - } - } - } - ``` - - \ No newline at end of file diff --git a/en/application-dev/ability-deprecated/stage-serviceextension.md b/en/application-dev/ability-deprecated/stage-serviceextension.md deleted file mode 100644 index 8f77e3251d56ff8023d8215546a38b0614f5c8b3..0000000000000000000000000000000000000000 --- a/en/application-dev/ability-deprecated/stage-serviceextension.md +++ /dev/null @@ -1,75 +0,0 @@ -# Service Extension Ability Development - -## When to Use -`ExtensionAbility` is the base class of the new Extension component in the stage model. It is used to process missions without UIs. The lifecycle of an Extension ability is simple and does not involve foreground or background states. `ServiceExtensionAbility` is extended from `ExtensionAbility`. - -You can customize a class that inherits from `ServiceExtensionAbility` and override the lifecycle callbacks in the base class to perform service logic operations during the initialization, connection, and disconnection processes. - -## Available APIs - -**Table 1** ServiceExtensionAbility lifecycle APIs -|API|Description| -|:------|:------| -|onCreate(want: Want): void|Called for the initialization when `startAbility` or `connectAbility` is invoked for a given ability for the first time.| -|onRequest(want: Want, startId: number): void|Called each time `startAbility` is invoked for a given ability. The initial value of `startId` is `1`, and the value is incremented by one each time `startAbility` is invoked for that ability.| -|onConnect(want: Want): rpc.RemoteObject|Called when `connectAbility` is invoked for a given ability. This callback is not invoked for repeated calling of `connectAbility` for a specific ability. However, it will be invoked unless `connectAbility` is called after the ability has been disconnected using `disconnectAbility`. The returned result is a `RemoteObject`.| -|onDisconnect(want: Want): void|Called when `disconnectAbility` is called for a given ability. If the Extension ability is started by `connectAbility` and is not bound to other applications, the `onDestroy` callback will also be triggered to destroy the Extension ability.| -|onDestroy(): void|Called when `terminateSelf` is invoked to terminate the ability.| - - -## Constraints - -OpenHarmony does not support creation of a Service Extension ability for third-party applications. - - -## How to Develop - -1. Declare the Service Extension ability in the `module.json5` file by setting its `type` attribute to `service`. The following is a configuration example of the `module.json5` file: - - - ```json - "extensionAbilities":[{ - "name": "ServiceExtAbility", - "icon": "$media:icon", - "description": "service", - "type": "service", - "exported": true, - "srcEntry": "./ets/ServiceExtAbility/ServiceExtAbility.ts" - }] - ``` - - -2. Customize a class that inherits from `ServiceExtensionAbility` in the .ts file in the directory where the Service Extension ability is defined (`entry\src\main\ets\ServiceExtAbility\ServiceExtAbility.ts` by default) and override the lifecycle callbacks of the base class. The code sample is as follows: - - ```js - import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; - import rpc from '@ohos.rpc'; - - class StubTest extends rpc.RemoteObject { - constructor(des) { - super(des); - } - onRemoteRequest(code, data, reply, option) { - } - } - - class ServiceExtAbility extends ServiceExtensionAbility { - onCreate(want) { - console.log('onCreate, want:' + want.abilityName); - } - onRequest(want, startId) { - console.log('onRequest, want:' + want.abilityName); - } - onConnect(want) { - console.log('onConnect , want:' + want.abilityName); - return new StubTest("test"); - } - onDisconnect(want) { - console.log('onDisconnect, want:' + want.abilityName); - } - onDestroy() { - console.log('onDestroy'); - } - } - ``` - diff --git a/en/application-dev/ability-deprecated/wantagent.md b/en/application-dev/ability-deprecated/wantagent.md deleted file mode 100644 index 0fc2036aac7d8b141310521a704570f28801f063..0000000000000000000000000000000000000000 --- a/en/application-dev/ability-deprecated/wantagent.md +++ /dev/null @@ -1,86 +0,0 @@ -# WantAgent Development -## When to Use -The **WantAgent** class encapsulates want information that specifies a particular action, which can be starting an ability or publishing a common event. You can either call **wantAgent.trigger** to trigger a **WantAgent** directly or add a **WantAgent** to a notification so that it will be triggered when users tap the notification. - -## Available APIs -| API | Description| -| ---------------------------------------------------------------------------------------------- | ----------- | -| getWantAgentInfo(info: WantAgentInfo, callback: AsyncCallback\) | Creates a **WantAgent** object. This API uses an asynchronous callback to return the result.| -| getWantAgent(info: WantAgentInfo): Promise\ | Creates a **WantAgent** object. This API uses a promise to return the result.| -| trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback\) | Triggers a **WantAgent** object.| - -## How to Develop -1. Import the **WantAgent** module. - - ```ts - import wantAgent from '@ohos.app.ability.wantAgent'; - ``` - -2. Create a **WantAgentInfo** object that will be used for starting an ability. For details about the data types and parameters of **WantAgentInfo**, see [WantAgent](../reference/apis/js-apis-wantAgent.md#wantagentinfo). - - ```ts - private wantAgentObj = null // Save the WantAgent object created. It will be used to complete the trigger operations. - - // wantAgentInfo - var wantAgentInfo = { - wants: [ - { - deviceId: "", - bundleName: "com.example.test", - abilityName: "com.example.test.EntryAbility", - action: "", - entities: [], - uri: "", - parameters: {} - } - ], - operationType: wantAgent.OperationType.START_ABILITY, - requestCode: 0, - wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG] - } - ``` - -3. Create a **WantAgentInfo** object for publishing a common event. - - ```ts - private wantAgentObj = null // Save the WantAgent object created. It will be used to complete the trigger operations. - - // wantAgentInfo - var wantAgentInfo = { - wants: [ - { - action: "event_name", // Set the action name. - parameters: {} - } - ], - operationType: wantAgent.OperationType.SEND_COMMON_EVENT, - requestCode: 0, - wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG] - } - ``` - -4. Create a **WantAgent** object and save the returned **wantAgentObj** for subsequent trigger operations. - - ```ts - // Create a WantAgent object. - wantAgent.getWantAgent(wantAgentInfo, (err, wantAgentObj) => { - if (err.code) { - console.error("[WantAgent]getWantAgent err=" + JSON.stringify(err)) - } else { - console.log("[WantAgent]getWantAgent success") - this.wantAgentObj = wantAgentObj - } - }) - ``` - -5. Trigger the **WantAgent** object. - - ```ts - // Trigger the WantAgent object. - var triggerInfo = { - code:0 - } - wantAgent.trigger(wantAgentObj, triggerInfo, (completeData) => { - console.log("[WantAgent]getWantAgent success, completeData: ", + JSON.stringify(completeData)) - }) - ``` diff --git a/en/application-dev/application-models/arkts-ui-widget-creation.md b/en/application-dev/application-models/arkts-ui-widget-creation.md index bc571f93c5623a46a1290064d297003fe7e24c29..a99e4e7bf1f512aa6c5bdcb17fe8ef6d902970bb 100644 --- a/en/application-dev/application-models/arkts-ui-widget-creation.md +++ b/en/application-dev/application-models/arkts-ui-widget-creation.md @@ -1,8 +1,15 @@ # Creating an ArkTS Widget -To create an ArkTS widget in an existing application project, perform the following steps: +You can create a widget in either of the following modes: -1. Create a widget. +- When creating a project, select **Application**. The project created this way does not have a widget by default. You can right-click a module folder and choose **New** > **Service Widget** to create a widget. +- When creating a project, select **Atomic Service**. The project created this way has a widget by default. You can right-click a module folder and choose **New** > **Service Widget** to create a widget. + +![WidgetCreateProject](figures/WidgetCreateProject.png) + +To create an ArkTS widget in an existing project, perform the following steps: + +1. Right-click a module folder and choose **New** > **Service Widget**. ![WidgetProjectCreate1](figures/WidgetProjectCreate1.png) @@ -14,6 +21,6 @@ To create an ArkTS widget in an existing application project, perform the follow ![WidgetProjectCreate3](figures/WidgetProjectCreate3.png) -After an ArkTS widget is created, the following widget-related files are automatically added to the project directory: **EntryFormAbility.ts** (widget lifecycle management file), **WidgetCard.ets** (widget page file), and **form_config.json** (widget configuration file). +After an ArkTS widget is created, the following widget-related files are automatically added to the project directory: **EntryFormAbility.ets** (widget lifecycle management file), **WidgetCard.ets** (widget page file), and **form_config.json** (widget configuration file). ![WidgetProjectView](figures/WidgetProjectView.png) \ No newline at end of file diff --git a/en/application-dev/application-models/arkts-ui-widget-event-call.md b/en/application-dev/application-models/arkts-ui-widget-event-call.md index 69189afb06c941158047462015519499961c9b95..1f22ecb2a555fa0834f9078370ae3e84c7225e43 100644 --- a/en/application-dev/application-models/arkts-ui-widget-event-call.md +++ b/en/application-dev/application-models/arkts-ui-widget-event-call.md @@ -48,7 +48,7 @@ Typically, the call event is triggered for touching of buttons. Below is an exam } ``` -- The UIAbility receives the call event and obtains the transferred parameters. It then executes the target method specified by the **method** parameter. Other data can be obtained in readString mode. Listen for the method required by the call event in the **onCreate** callback of the UIAbility. +- The UIAbility receives the call event and obtains the transferred parameters. It then executes the target method specified by the **method** parameter. Other data can be obtained through the **[readString](../reference/apis/js-apis-rpc.md#readstring)** method. Listen for the method required by the call event in the **onCreate** callback of the UIAbility. ```ts import UIAbility from '@ohos.app.ability.UIAbility'; @@ -65,7 +65,7 @@ Typically, the call event is triggered for touching of buttons. Below is an exam } export default class CameraAbility extends UIAbility { - // If the UIAbility is started for the first time, onCreate is triggered afte the call event is received. + // If the UIAbility is started for the first time, onCreate is triggered after the call event is received. onCreate(want, launchParam) { try { // Listen for the method required by the call event. diff --git a/en/application-dev/application-models/arkts-ui-widget-event-formextensionability.md b/en/application-dev/application-models/arkts-ui-widget-event-formextensionability.md index be7761d8d78da5102afadd2c37043c228dfcd53e..a8a2147aca82c099ea0eed23fd27e65a67853843 100644 --- a/en/application-dev/application-models/arkts-ui-widget-event-formextensionability.md +++ b/en/application-dev/application-models/arkts-ui-widget-event-formextensionability.md @@ -4,19 +4,26 @@ On the widget page, the **postCardAction** API can be used to trigger a message event to start a FormExtensionAbility, which then updates the widget content. The following is an example of this widget update mode. -- On the widget page, register the **onClick** event callback of the button and call the **postCardAction** API in the callback to trigger the event to the FormExtensionAbility. +- On the widget page, register the **onClick** event callback of the button and call the **postCardAction** API in the callback to trigger the event to the FormExtensionAbility. Use [LocalStorageProp](../quick-start/arkts-localstorage.md#localstorageprop) to decorate the widget data to be updated. ```ts let storage = new LocalStorage(); @Entry(storage) @Component struct WidgetCard { - @LocalStorageProp('title') title: string = 'init'; - @LocalStorageProp('detail') detail: string = 'init'; + @LocalStorageProp('title') title: string = 'Title default'; + @LocalStorageProp('detail') detail: string = 'Description default'; build() { Column() { - Button ('Update') + Column() { + Text(`${this.title}`) + .margin(5).fontWeight(FontWeight.Medium).fontSize('14fp') + Text(`${this.detail}`) + .margin(5).fontColor(Color.Gray).fontSize('12fp').height('25%') + }.width('100%').alignItems(HorizontalAlign.Start) + Button('UPDATE') + .margin(15).width('90%') .onClick(() => { postCardAction(this, { 'action': 'message', @@ -25,11 +32,7 @@ On the widget page, the **postCardAction** API can be used to trigger a message } }); }) - Text(`${this.title}`) - Text(`${this.detail}`) - } - .width('100%') - .height('100%') + }.width('90%').height('90%').margin('5%') } } ``` @@ -46,8 +49,8 @@ On the widget page, the **postCardAction** API can be used to trigger a message // Called when a specified message event defined by the form provider is triggered. console.info(`FormAbility onEvent, formId = ${formId}, message: ${JSON.stringify(message)}`); let formData = { - 'title':'Title Update Success.', // Matches the widget layout. - 'detail':'Detail Update Success.', // Matches the widget layout. + 'title':'Title Update.', // It matches the widget layout. + 'detail':'Description update success.', // It matches the widget layout. }; let formInfo = formBindingData.createFormBindingData(formData) formProvider.updateForm(formId, formInfo).then((data) => { @@ -63,4 +66,6 @@ On the widget page, the **postCardAction** API can be used to trigger a message The figure below shows the effect. - ![WidgetUpdatePage](figures/WidgetUpdatePage.png) + | Initial State | After Clicking | + | ------------------------------------------------------- | ----------------------------------------------------- | + | ![WidgetUpdateBefore](figures/widget-update-before.PNG) | ![WidgetUpdateAfter](figures/widget-update-after.PNG) | diff --git a/en/application-dev/application-models/arkts-ui-widget-event-overview.md b/en/application-dev/application-models/arkts-ui-widget-event-overview.md index 299a279c9117dad71e6fea658bb8da3298ed8f05..20e353c42d37d6111019de1e99a6f99a212851c8 100644 --- a/en/application-dev/application-models/arkts-ui-widget-event-overview.md +++ b/en/application-dev/application-models/arkts-ui-widget-event-overview.md @@ -23,8 +23,11 @@ The ArkTS widget provides the **postCardAction()** API for interaction between t | "bundleName" | string | Name of the target bundle when **action** is **"router"** or **"call"**. This parameter is optional.| | "moduleName" | string | Name of the target module when **action** is **"router"** or **"call"**. This parameter is optional.| | "abilityName" | string | Name of the target UIAbility when **action** is **"router"** or **"call"**. This parameter is mandatory.| -| "params" | Object | Additional parameters carried in the current action. The value is a key-value pair in JSON format. For the **"call"** action type, the **method** parameter (mandatory) must be set and its value type must be string.| +| "params" | Object | Additional parameters carried in the current action. The value is a key-value pair in JSON format. This parameter is mandatory.| +>**NOTE** +> +>When **action** is **"router"** or **"call"**, **'method'** of the string type must be passed to **params** to trigger the corresponding method in the UIAbility. Sample code of the **postCardAction()** API: diff --git a/en/application-dev/application-models/arkts-ui-widget-event-router.md b/en/application-dev/application-models/arkts-ui-widget-event-router.md index 733ff7f59b57ec4295fa21cb4d83ae8a5b2b8eb4..b0b62a4e0b66b28d5ee6ab4d21056b5e65192353 100644 --- a/en/application-dev/application-models/arkts-ui-widget-event-router.md +++ b/en/application-dev/application-models/arkts-ui-widget-event-router.md @@ -5,7 +5,7 @@ The **router** capability of the **postCardAction** API can be used in a widget ![WidgerCameraCard](figures/WidgerCameraCard.png) -Generally, a button is used to start a page. +Generally, a button is used to start a page. Below is an example: - Design two buttons on the widget page. When one of the buttons is clicked, **postCardAction** is called to send a router event to the specified UIAbility, with the content to be transferred defined in the event. @@ -57,7 +57,7 @@ Generally, a button is used to start a page. let selectPage = ""; let currentWindowStage = null; - export default class CameraAbility extends UIAbility { + export default class EntryAbility extends UIAbility { // If the UIAbility is started for the first time, the onCreate lifecycle callback is triggered after the router event is received. onCreate(want, launchParam) { // Obtain the targetPage parameter passed in the router event. diff --git a/en/application-dev/application-models/arkts-ui-widget-interaction-overview.md b/en/application-dev/application-models/arkts-ui-widget-interaction-overview.md index afd3cfa70b30ca5f5b6a0e4464958175f8e39cc1..56ff32a0981e46e337f73aa3726b53147ff0e4ae 100644 --- a/en/application-dev/application-models/arkts-ui-widget-interaction-overview.md +++ b/en/application-dev/application-models/arkts-ui-widget-interaction-overview.md @@ -1,6 +1,6 @@ # Widget Data Interaction -The ArkTS widget framework provides the **updateForm()** and **requestForm()** APIs to proactively trigger widget updates. +The ArkTS widget framework provides the **updateForm()** and **requestForm()** APIs to proactively trigger widget updates. You can use [LocalStorageProp](../quick-start/arkts-localstorage.md#localstorageprop) to check the widget data to be updated. ![WidgetLocalStorageProp](figures/WidgetLocalStorageProp.png) diff --git a/en/application-dev/application-models/arkts-ui-widget-lifecycle.md b/en/application-dev/application-models/arkts-ui-widget-lifecycle.md index fb25fd362f67646d65853b870a6a9cb518c4d760..7818157e0d84866a52703a9615ffc8014fa61a14 100644 --- a/en/application-dev/application-models/arkts-ui-widget-lifecycle.md +++ b/en/application-dev/application-models/arkts-ui-widget-lifecycle.md @@ -4,7 +4,7 @@ When creating an ArkTS widget, you need to implement the [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md) lifecycle APIs. -1. Import related modules to **EntryFormAbility.ts**. +1. Import related modules to **EntryFormAbility.ets**. ```ts import formInfo from '@ohos.app.form.formInfo'; @@ -13,7 +13,7 @@ When creating an ArkTS widget, you need to implement the [FormExtensionAbility]( import formProvider from '@ohos.app.form.formProvider'; ``` -2. In **EntryFormAbility.ts**, implement the [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md) lifecycle APIs, including **onAddForm**, whose **want** parameter can be used to obtain the widget information through [FormParam](../reference/apis/js-apis-app-form-formInfo.md#formparam). +2. In **EntryFormAbility.ets**, implement the [[FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md) lifecycle APIs, including **onAddForm**, whose **want** parameter can be used to obtain the widget information through [FormParam](../reference/apis/js-apis-app-form-formInfo.md#formparam). ```typescript import formInfo from '@ohos.app.form.formInfo'; @@ -36,9 +36,8 @@ When creating an ArkTS widget, you need to implement the [FormExtensionAbility]( } onCastToNormalForm(formId) { - // Called when the form provider is notified that a temporary form is successfully - // converted to a normal form. - // Called when the widget host converts the temporary widget into a normal one. The widget provider should do something to respond to the conversion. + // Called when the widget host converts the temporary widget into a normal one. + // The widget provider should do something to respond to the conversion. console.info(`[EntryFormAbility] onCastToNormalForm, formId: ${formId}`); } @@ -60,20 +59,20 @@ When creating an ArkTS widget, you need to implement the [FormExtensionAbility]( } onChangeFormVisibility(newStatus) { - // Called when the form provider receives form events from the system. - // The callback is performed only when formVisibleNotify is set to true and the application is a system application. + // Called when the widget provider receives form events from the system. + // The callback is triggered only when formVisibleNotify is set to true and the application is a system application. console.info('[EntryFormAbility] onChangeFormVisibility'); } onFormEvent(formId, message) { - // Called when a specified message event defined by the form provider is triggered. + // Called when a specified message event defined by the widget provider is triggered. // If the widget supports event triggering, override this method and implement the trigger. console.info('[EntryFormAbility] onFormEvent'); } onRemoveForm(formId) { - // Called to notify the form provider that a specified form has been destroyed. - // Called when the corresponding widget is deleted. The input parameter is the ID of the deleted card. + // Called to notify the widget provider that a specified widget has been destroyed. + // The input parameter is the ID of the deleted card. console.info('[EntryFormAbility] onRemoveForm'); } @@ -83,8 +82,8 @@ When creating an ArkTS widget, you need to implement the [FormExtensionAbility]( } onAcquireFormState(want) { - // Called to return a {@link FormState} object. - // Called when the widget provider receives the status query result of a widget. By default, the initial state of the widget is returned. + // Called to return a FormState object upon a status query request + // from the widget. By default, the initial widget state is returned. return formInfo.FormState.READY; } } diff --git a/en/application-dev/application-models/arkts-ui-widget-modules.md b/en/application-dev/application-models/arkts-ui-widget-modules.md index b9a411426db84a4c1af12e70eab956adc8f25806..eb386c4d72cc3e8d36cd1bcd096786eaa685aa92 100644 --- a/en/application-dev/application-models/arkts-ui-widget-modules.md +++ b/en/application-dev/application-models/arkts-ui-widget-modules.md @@ -15,9 +15,9 @@ - [formBindingData](../reference/apis/js-apis-app-form-formBindingData.md): provides APIs for widget data binding. You can use the APIs to create a **FormBindingData** object and obtain related information. -- [Page layout (Card.ets)](arkts-ui-widget-page-overview.md): provides APIs for a declarative paradigm UI. +- [Page layout (WidgetCard.ets)](arkts-ui-widget-page-overview.md): provides APIs for the declarative UI paradigm. - [Capabilities exclusive to ArkTS widgets](arkts-ui-widget-event-overview.md): include the **postCardAction** API used for interaction between the widget internal and the provider application and can be called only in the widget. - - [ArkTS widget capability list](arkts-ui-widget-page-overview.md#page-capabilities-supported-by-arkts-widgets): contain the APIs, components, events, attributes, and lifecycle callbacks that can be used in ArkTS widgets. + - [ArkTS widget capability list](arkts-ui-widget-page-overview.md): contain the APIs, components, events, attributes, and lifecycle callbacks that can be used in ArkTS widgets. - [Widget configuration](arkts-ui-widget-configuration.md): includes FormExtensionAbility configuration and widget configuration. - Configure the FormExtensionAbility information under **extensionAbilities** in the [module.json5 file](../quick-start/module-configuration-file.md). diff --git a/en/application-dev/application-models/arkts-ui-widget-update-by-proxy.md b/en/application-dev/application-models/arkts-ui-widget-update-by-proxy.md index b7c1c93d21ec24673b3d07c4e971eadd7cd13661..5316b1ec93e2677c416c64cd6cd8c610d7aa5642 100644 --- a/en/application-dev/application-models/arkts-ui-widget-update-by-proxy.md +++ b/en/application-dev/application-models/arkts-ui-widget-update-by-proxy.md @@ -13,6 +13,10 @@ Compared with the [implementation of the ArkTS widget](../application-models/ark - Data management service: provides a mechanism for data sharing among multiple applications. - Data provider: must be a system application that has data sharing enabled. The shared data is identified through the defined **key** + **subscriberId** combination. +> **NOTE** +> +> This feature can be used when the system provides applications as data providers and publicly available shared data identifiers. + Processing flow of the widget provider (indicated by the blue arrows in the figure): 1. The widget provider sets the **dataProxyEnabled** field to **true** in the **form_config.json** file to enable the update-through-proxy feature. @@ -29,7 +33,7 @@ Processing flow of the widget update proxy (indicated by the red arrows in the f 1. The data provider uses the **key** + **subscriberId** combination as the data ID to store data to the database. 2. The data management service detects the change in the database and publishes the new data to all currently registered subscription instances. 3. The Widget Manager parses data from the subscription instance and sends the data to the widget rendering service. -4. The widget rendering service runs the widget page code **widgets.abc**, renders based on the new data, and sends the rendered data to the widget component (../reference/arkui-ts/ts-basic-components-formcomponent.md) corresponding to the widget host. +4. The widget rendering service runs the widget page code **widgets.abc**, which implements rendering based on the new data and sends the rendered data to the [FormComponent](../reference/arkui-ts/ts-basic-components-formcomponent.md) corresponding to the widget host. There are two types of shared data provided by the data provider: diff --git a/en/application-dev/application-models/arkts-ui-widget-update-by-time.md b/en/application-dev/application-models/arkts-ui-widget-update-by-time.md index c3fcf45f3b95e88ca1a0f2bc13aefa94100873c0..d173d0210a2ecce63789a1a5f3de9584a0ec83d8 100644 --- a/en/application-dev/application-models/arkts-ui-widget-update-by-time.md +++ b/en/application-dev/application-models/arkts-ui-widget-update-by-time.md @@ -1,7 +1,5 @@ # Configuring a Widget to Update Periodically -Before configuring a widget to update periodically, enable the periodic update feature by setting the **updateEnabled** field to **true** in the **form_config.json** file. - The widget framework provides the following modes of updating widgets periodically: @@ -9,6 +7,8 @@ The widget framework provides the following modes of updating widgets periodical > **NOTE** > + > Before configuring a widget to update periodically, enable the periodic update feature by setting the **updateEnabled** field to **true** in the **form_config.json** file. + > > **updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used. ```json diff --git a/en/application-dev/application-models/arkts-ui-widget-working-principles.md b/en/application-dev/application-models/arkts-ui-widget-working-principles.md index a8599ca8827c2d41c3ff1be032151c1f6debead9..d9e1b26ddf40654feaa28b26439c401e1551ff64 100644 --- a/en/application-dev/application-models/arkts-ui-widget-working-principles.md +++ b/en/application-dev/application-models/arkts-ui-widget-working-principles.md @@ -13,13 +13,13 @@ - Widget Manager: a resident agent that manages widgets in the system. It provides the [formProvider](../reference/apis/js-apis-app-form-formProvider.md) and [formHost](../reference/apis/js-apis-app-form-formHost.md) APIs as well as the APIs for widget management, usage, and periodic updates. -- Widget rendering service: a service that manages widget rendering instances. Widget rendering instances are bound to the [widget components](../reference/arkui-ts/ts-basic-components-formcomponent.md) on the widget host on a one-to-one basis. The widget rendering service runs the widget page code **widgets.abc** for rendering, and sends the rendered data to the corresponding widget component on the widget host. +- Widget rendering service: a service that manages widget rendering instances. Widget rendering instances are bound to the [FormComponent](../reference/arkui-ts/ts-basic-components-formcomponent.md) on the widget host on a one-to-one basis. The widget rendering service runs the widget page code **widgets.abc** for rendering, and sends the rendered data to the corresponding [FormComponent](../reference/arkui-ts/ts-basic-components-formcomponent.md) on the widget host. **Figure 2** Working principles of the ArkTS widget rendering service ![WidgetRender](figures/WidgetRender.png) -Unlike JS widgets, ArkTS widgets support logic code execution. The widget page code **widgets.abc** is executed by the widget rendering service, which is managed by the Widget Manager. Each widget component of a widget host corresponds to a rendering instance in the widget rendering service. Rendering instances of a widget provider run in the same virtual machine operating environment, and rendering instances of different widget providers run in different virtual machine operating environments. In this way, the resources and state data are isolated between widgets of different widget providers. During development, pay attention to the use of the [globalThis](uiability-data-sync-with-ui.md#using-globalthis-between-uiability-and-ui-page) object. Use one **globalThis** object for widgets from the same widget provider, and different **globalThis** objects for widgets from different widget providers. +Unlike JS widgets, ArkTS widgets support logic code execution. The widget page code **widgets.abc** is executed by the widget rendering service, which is managed by the Widget Manager. Each widget component of a widget host corresponds to a rendering instance in the widget rendering service. Rendering instances of a widget provider run in the same ArkTS virtual machine operating environment, and rendering instances of different widget providers run in different ArkTS virtual machine operating environments. In this way, the resources and state data are isolated between widgets of different widget providers. During development, pay attention to the use of the [globalThis](uiability-data-sync-with-ui.md#using-globalthis-for-data-synchronization) object. Use one **globalThis** object for widgets from the same widget provider, and different **globalThis** objects for widgets from different widget providers. ## Advantages of ArkTS Widgets diff --git a/en/application-dev/application-models/common-event-subscription.md b/en/application-dev/application-models/common-event-subscription.md index c3e3ebfa52415d5e0ebade26973f78a589fb348f..856b7fc44c624910ab1e8d2cb57f8b1f3a2c5d7d 100644 --- a/en/application-dev/application-models/common-event-subscription.md +++ b/en/application-dev/application-models/common-event-subscription.md @@ -12,7 +12,7 @@ For details about the APIs, see [API Reference](../reference/apis/js-apis-common | API| Description| | -------- | -------- | -| createSubscriber(subscribeInfo: [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEventManager.md#commoneventsubscribeinfo), callback: AsyncCallback<[CommonEventData](../reference/apis/js-apis-commonEventManager.md#commoneventdata)>): void | Creates a subscriber. This API uses an asynchronous callback to return the result.| +| createSubscriber(subscribeInfo: [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEventManager.md#commoneventsubscribeinfo), callback: AsyncCallback<[CommonEventSubscriber](../reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md#usage)>): void | Creates a subscriber. This API uses an asynchronous callback to return the result.| | createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise<CommonEventSubscriber> | Creates a subscriber. This API uses a promise to return the result.| | subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback): void | Subscribes to common events.| diff --git a/en/application-dev/application-models/figures/WidgetCreateProject.png b/en/application-dev/application-models/figures/WidgetCreateProject.png new file mode 100644 index 0000000000000000000000000000000000000000..2372e68a25c116ace77374eba86a8ea7a0680988 Binary files /dev/null and b/en/application-dev/application-models/figures/WidgetCreateProject.png differ diff --git a/en/application-dev/application-models/figures/WidgetModules.png b/en/application-dev/application-models/figures/WidgetModules.png index 6eaac0b6ca404eb9575587add72935e9ce580030..1612c2fa34fe9aea0563fa58fc7af378539ba81a 100644 Binary files a/en/application-dev/application-models/figures/WidgetModules.png and b/en/application-dev/application-models/figures/WidgetModules.png differ diff --git a/en/application-dev/application-models/figures/WidgetPrinciple.png b/en/application-dev/application-models/figures/WidgetPrinciple.png index 68ca315394fe2cb5bd2580ca6df38b9940ac1349..3f8d147f07aaa85e1a21859bf58ab4d8bd891de2 100644 Binary files a/en/application-dev/application-models/figures/WidgetPrinciple.png and b/en/application-dev/application-models/figures/WidgetPrinciple.png differ diff --git a/en/application-dev/application-models/figures/WidgetProjectView.png b/en/application-dev/application-models/figures/WidgetProjectView.png index 9d1c06e47502131983b0b7cd56e66269b5be6d88..a1c8b42becc089b6b69f58c362569faeaf84f06f 100644 Binary files a/en/application-dev/application-models/figures/WidgetProjectView.png and b/en/application-dev/application-models/figures/WidgetProjectView.png differ diff --git a/en/application-dev/application-models/figures/WidgetRender.png b/en/application-dev/application-models/figures/WidgetRender.png index 0f46bd74b0e48ac0c9f947d96d5e147786f547c0..1fec0d982b45718a7dbc9d19e679e6806f1c84cc 100644 Binary files a/en/application-dev/application-models/figures/WidgetRender.png and b/en/application-dev/application-models/figures/WidgetRender.png differ diff --git a/en/application-dev/application-models/figures/WidgetUpdatePage.png b/en/application-dev/application-models/figures/WidgetUpdatePage.png deleted file mode 100644 index 075c8e97c85386c062a651f3b4f876e6c049171f..0000000000000000000000000000000000000000 Binary files a/en/application-dev/application-models/figures/WidgetUpdatePage.png and /dev/null differ diff --git a/en/application-dev/application-models/figures/widget-update-after.PNG b/en/application-dev/application-models/figures/widget-update-after.PNG new file mode 100644 index 0000000000000000000000000000000000000000..fddb9f651685332324af9a4d065c29638a58c0ba Binary files /dev/null and b/en/application-dev/application-models/figures/widget-update-after.PNG differ diff --git a/en/application-dev/application-models/figures/widget-update-before.PNG b/en/application-dev/application-models/figures/widget-update-before.PNG new file mode 100644 index 0000000000000000000000000000000000000000..6355f1b66707af8073a2e1dea7f05e839f3a9818 Binary files /dev/null and b/en/application-dev/application-models/figures/widget-update-before.PNG differ diff --git a/en/application-dev/application-models/js-ui-widget-development.md b/en/application-dev/application-models/js-ui-widget-development.md index 178aa903a36b6a4742645cfab82a390364db0b37..9e1cd4d472afc4dcbf830b901b935fde0667e9b4 100644 --- a/en/application-dev/application-models/js-ui-widget-development.md +++ b/en/application-dev/application-models/js-ui-widget-development.md @@ -56,7 +56,7 @@ The **FormExtensionAbility** class has the following APIs. For details, see [For | onFormEvent(formId: string, message: string): void | Called to instruct the widget provider to process a widget event.| | onRemoveForm(formId: string): void | Called to notify the widget provider that a widget is being destroyed.| | onConfigurationUpdate(config: Configuration): void | Called when the configuration of the environment where the widget is running is being updated.| -| onShareForm?(formId: string): { [key: string]: any } | Called to notify the widget provider that the widget host is sharing the widget data.| +| onShareForm?(formId: string): { [key: string]: Object } | Called to notify the widget provider that the widget host is sharing the widget data.| The **FormProvider** class has the following APIs. For details, see [FormProvider](../reference/apis/js-apis-app-form-formProvider.md). @@ -95,7 +95,7 @@ The widget provider development based on the [stage model](stage-model-developme To create a widget in the stage model, you need to implement the lifecycle callbacks of FormExtensionAbility. Generate a widget template and then perform the following: -1. Import related modules to **EntryFormAbility.ts**. +1. Import related modules to **EntryFormAbility.ets**. ```ts @@ -106,7 +106,7 @@ To create a widget in the stage model, you need to implement the lifecycle callb import dataPreferences from '@ohos.data.preferences'; ``` -2. Implement the FormExtension lifecycle callbacks in **EntryFormAbility.ts**. +2. Implement the FormExtension lifecycle callbacks in **EntryFormAbility.ets**. ```ts @@ -176,7 +176,7 @@ To create a widget in the stage model, you need to implement the lifecycle callb "extensionAbilities": [ { "name": "EntryFormAbility", - "srcEntry": "./ets/entryformability/EntryFormAbility.ts", + "srcEntry": "./ets/entryformability/EntryFormAbility.ets", "label": "$string:EntryFormAbility_label", "description": "$string:EntryFormAbility_desc", "type": "form", @@ -547,6 +547,29 @@ The following are examples: } ``` + Note: + + **JSON Value** in **data** supports multi-level nested data. When updating data, ensure that complete data is carried. + + Assume that a widget is displaying the course information of Mr. Zhang on July 18, as shown in the following code snippet. + ```ts + "data": { + "Day": "07.18", + "teacher": { + "name": "Mr.Zhang", + "course": "Math" + } + } + ``` + To update the widget content to the course information of Mr. Li on July 18, you must pass the complete data as follows, instead of only a single date item such as **name** or **course**: + ```ts + "teacher": { + "name": "Mr.Li", + "course": "English" + } + ``` + + - Receive the router event in UIAbility and obtain parameters. diff --git a/en/application-dev/connectivity/net-mdns.md b/en/application-dev/connectivity/net-mdns.md index de7982a5c03908a70e4005bdc5fbea3584c435f5..b2c29f583d7d36eaf5ff14ffe134750c9ef48d7d 100644 --- a/en/application-dev/connectivity/net-mdns.md +++ b/en/application-dev/connectivity/net-mdns.md @@ -11,6 +11,7 @@ Typical MDNS management scenarios include: - Discovering local services and listening to the status changes of local services of the specified type through the **DiscoveryService** object. > **NOTE** +> > To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [mDNS Management](../reference/apis/js-apis-net-mdns.md). The following describes the development procedure specific to each application scenario. @@ -28,9 +29,13 @@ For the complete list of APIs and example code, see [mDNS Management](../referen | ohos.net.mdns.DiscoveryService | startSearchingMDNS(): void | Searches for mDNS services on the LAN.| | ohos.net.mdns.DiscoveryService | stopSearchingMDNS(): void | Stops searching for mDNS services on the LAN.| | ohos.net.mdns.DiscoveryService | on(type: 'discoveryStart', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MdnsError}>): void | Enables listening for **discoveryStart** events.| +| ohos.net.mdns.DiscoveryService | off(type: 'discoveryStart', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MdnsError}>): void | Disables listening for **discoveryStart** events.| | ohos.net.mdns.DiscoveryService | on(type: 'discoveryStop', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MdnsError}>): void | Enables listening for **discoveryStop** events.| +| ohos.net.mdns.DiscoveryService | off(type: 'discoveryStop', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MdnsError}>): void | Disables listening for **discoveryStop** events.| | ohos.net.mdns.DiscoveryService | on(type: 'serviceFound', callback: Callback\): void | Enables listening for **serviceFound** events.| +| ohos.net.mdns.DiscoveryService | off(type: 'serviceFound', callback: Callback\): void | Disables listening for **serviceFound** events.| | ohos.net.mdns.DiscoveryService | on(type: 'serviceLost', callback: Callback\): void | Enables listening for **serviceLost** events.| +| ohos.net.mdns.DiscoveryService | off(type: 'serviceLost', callback: Callback\): void | Disables listening for **serviceLost** events.| ## Managing Local Services @@ -94,10 +99,11 @@ mdns.removeLocalService(context, localServiceInfo, function (error, data) { 1. Connect the device to the Wi-Fi network. 2. Import the **mdns** namespace from **@ohos.net.mdns**. -3. Creates a **DiscoveryService** object, which is used to discover mDNS services of the specified type. +3. Create a **DiscoveryService** object, which is used to discover mDNS services of the specified type. 4. Subscribe to mDNS service discovery status changes. 5. Enable discovery of mDNS services on the LAN. 6. Stop searching for mDNS services on the LAN. +7. Unsubscribe from mDNS service discovery status changes. ```js // Import the mdns namespace from @ohos.net.mdns. @@ -139,4 +145,18 @@ discoveryService.startSearchingMDNS(); // Stop searching for mDNS services on the LAN. discoveryService.stopSearchingMDNS(); + +// Unsubscribe from mDNS service discovery status changes. +discoveryService.off('discoveryStart', (data) => { + console.log(JSON.stringify(data)); +}); +discoveryService.off('discoveryStop', (data) => { + console.log(JSON.stringify(data)); +}); +discoveryService.off('serviceFound', (data) => { + console.log(JSON.stringify(data)); +}); +discoveryService.off('serviceLost', (data) => { + console.log(JSON.stringify(data)); +}); ``` diff --git a/en/application-dev/database/data-sync-of-kv-store.md b/en/application-dev/database/data-sync-of-kv-store.md index b23dd91ed1a7b4ea0cd13f6d9b49de82e1821190..39f893f799a6a4c6bf9ac2d067a5f794a6961d9c 100644 --- a/en/application-dev/database/data-sync-of-kv-store.md +++ b/en/application-dev/database/data-sync-of-kv-store.md @@ -32,7 +32,7 @@ The underlying devices manage the data by device. The device KV stores support d The **DatamgrService** provides the following synchronization types: -- Manual synchronization: The application calls **sync()** to trigger a synchronization. The list of devices to be synchronized and the synchronization mode must be specified. The synchronization mode can be **PULL_ONLY** (pulling remote data to the local end), **PUSH_ONLY** (pushing local data to the remote end), or **PUSH_PULL** (pushing local data to the remote end and pulling remote data to the local end). You can use the [**sync()** with the **query** parameter](../reference/apis/js-apis-distributedKVStore.md#sync-1) to synchronize the data that meets the specified conditions. The manual synchronization is available only for system applications. +- Manual synchronization: The application calls **sync()** to trigger a synchronization. The list of devices to be synchronized and the synchronization mode must be specified. The synchronization mode can be **PULL_ONLY** (pulling remote data to the local end), **PUSH_ONLY** (pushing local data to the remote end), or **PUSH_PULL** (pushing local data to the remote end and pulling remote data to the local end). You can use the [**sync()** with the **query** parameter](../reference/apis/js-apis-distributedKVStore.md#sync-1) to synchronize the data that meets the specified conditions. - Automatic synchronization: The distributed database automatically pushes local data to the remote end and pulls remote data to the local end. An automatic synchronization is triggered when a device goes online or an application updates data. @@ -72,8 +72,6 @@ When data is added, deleted, or modified, a notification is sent to the subscrib - Each KV store supports a maximum of eight callbacks for subscription of data change notifications. -- The manual synchronization is available only for system applications. - ## Available APIs @@ -247,32 +245,31 @@ The following uses a single KV store as an example to describe how to implement > **NOTE** > - > If manual synchronization is used, **deviceIds** is obtained by using [devManager.getTrustedDeviceListSync](../reference/apis/js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are all system interfaces and available only to system applications. + > If manual synchronization is used, **deviceIds** can be obtained by [devManager.getAvailableDeviceListSync](../reference/apis/js-apis-distributedDeviceManager.md#getavailabledevicelistsync). - ```js - import deviceManager from '@ohos.distributedHardware.deviceManager'; + import deviceManager from '@ohos.distributedDeviceManager'; let devManager; - // create deviceManager - deviceManager.createDeviceManager('bundleName', (err, value) => { - if (!err) { - devManager = value; - // deviceIds is obtained by devManager.getTrustedDeviceListSync. - let deviceIds = []; - if (devManager !== null) { - // The ohos.permission.ACCESS_SERVICE_DM permission is required. This permission is available only for system applications. - let devices = devManager.getTrustedDeviceListSync(); - for (let i = 0; i < devices.length; i++) { - deviceIds[i] = devices[i].deviceId; - } - } - try { - // 1000 indicates the maximum delay, in ms. - kvStore.sync(deviceIds, distributedKVStore.SyncMode.PUSH_ONLY, 1000); - } catch (e) { - console.error(`An unexpected error occurred. Code:${e.code},message:${e.message}`); + try { + // create deviceManager + devManager = deviceManager.createDeviceManager(context.applicationInfo.name); + // deviceIds is obtained by devManager.getAvailableDeviceListSync. + let deviceIds = []; + if (devManager != null) { + let devices = devManager.getAvailableDeviceListSync(); + for (let i = 0; i < devices.length; i++) { + deviceIds[i] = devices[i].networkId; } } - }); + try { + // 1000 indicates the maximum delay, in ms. + kvStore.sync(deviceIds, distributedKVStore.SyncMode.PUSH_ONLY, 1000); + } catch (e) { + console.error(`An unexpected error occurred. Code:${e.code},message:${e.message}`); + } + + } catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); + } ``` \ No newline at end of file diff --git a/en/application-dev/database/data-sync-of-rdb-store.md b/en/application-dev/database/data-sync-of-rdb-store.md index 2d6d5a73e0cf7cfae28d7d6296039e28994477a8..7bcc40f6230871e7e9a3af7150cd943b426109c1 100644 --- a/en/application-dev/database/data-sync-of-rdb-store.md +++ b/en/application-dev/database/data-sync-of-rdb-store.md @@ -10,9 +10,16 @@ You can synchronize the application data in a local RDB store on a device to oth OpenHamony supports synchronization of the relational data of an application across multiple devices. -- Distributed table list
After a table is created for an application in an RDB store, you can set it as a distributed table. When querying the RDB store of a remote device, you can obtain the distributed table name of the remote device based on the local table name. +- Distributed table list -- Synchronization mode
Data can be synchronized between devices in either of the following ways:
- Pushing data from a local device to a remote device.
- Pulling data from a remote device to a local device. + After a table is created for an application in an RDB store, you can set it as a distributed table. When querying the RDB store of a remote device, you can obtain the distributed table name of the remote device based on the local table name. + +- Synchronization mode + + Data can be synchronized between devices in either of the following ways: + + - Pushing data from a local device to a remote device. + - Pulling data from a remote device to a local device. ## Working Principles @@ -44,12 +51,10 @@ When data is added, deleted, or modified, a notification is sent to the subscrib - Each RDB store supports a maximum of eight callbacks for subscription of data change notifications. -- Third-party applications cannot call the distributed APIs that must be specified with the device. - ## Available APIs -The following table lists the APIs for cross-device data synchronization of RDB stores. Most of the APIs are executed asynchronously, using a callback or promise to return the result. The following table uses the callback-based APIs as an example. For more information about the APIs, see [RDB Store](../reference/apis/js-apis-data-relationalStore.md). +Most of the APIs for cross-device data synchronization of RDB stores are executed asynchronously in callback or promise mode. The following table uses the callback-based APIs as an example. For more information about the APIs, see [RDB Store](../reference/apis/js-apis-data-relationalStore.md). | API| Description| | -------- | -------- | @@ -73,7 +78,7 @@ The following table lists the APIs for cross-device data synchronization of RDB import relationalStore from '@ohos.data.relationalStore'; ``` -2. Request permissions. +2. Apply for the required permission. 1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). 2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization). @@ -142,32 +147,33 @@ The following table lists the APIs for cross-device data synchronization of RDB > **NOTE** > - > **deviceIds** is obtained by using [devManager.getTrustedDeviceListSync](../reference/apis/js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are all system interfaces and available only to system applications. + > The value of **deviceIds** can be obtained by [deviceManager.getAvailableDeviceListSync](../reference/apis/js-apis-distributedDeviceManager.md#getavailabledevicelistsync). ```js // Obtain device IDs. - import deviceManager from '@ohos.distributedHardware.deviceManager'; - - deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { - if (err) { - console.info(`Failed to create device manager. Code:${err.code},message:${err.message}`); - return; - } - let devices = manager.getTrustedDeviceListSync(); - let deviceId = devices[0].deviceId; - - // Construct a predicate object for querying the distributed table. - let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); - // Query data from the specified remote device and return the query result. - store.remoteQuery(deviceId, 'EMPLOYEE', predicates, ['ID', 'NAME', 'AGE', 'SALARY', 'CODES'], - function (err, resultSet) { - if (err) { - console.error(`Failed to remoteQuery data. Code:${err.code},message:${err.message}`); - return; - } - console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); + import deviceManager from '@ohos.distributedDeviceManager'; + let dmInstance = null; + let deviceId = null; + + try { + dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); + let devices = dmInstance.getAvailableDeviceListSync(); + deviceId = devices[0].networkId; + + // Construct a predicate object for querying the distributed table. + let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); + // Query data from the specified remote device and return the query result. + store.remoteQuery(deviceId, 'EMPLOYEE', predicates, ['ID', 'NAME', 'AGE', 'SALARY', 'CODES'], + function (err, resultSet) { + if (err) { + console.error(`Failed to remoteQuery data. Code:${err.code},message:${err.message}`); + return; } - ) - }) - ``` + console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); + } + ) + } catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); + } + ``` \ No newline at end of file diff --git a/en/application-dev/faqs/faqs-graphics.md b/en/application-dev/faqs/faqs-graphics.md index 345cbf83c5b2976c810e78237cb2587eaa4b1404..4cc8b196d5b8210e2360a598c1b24fdc0edb891b 100644 --- a/en/application-dev/faqs/faqs-graphics.md +++ b/en/application-dev/faqs/faqs-graphics.md @@ -21,42 +21,6 @@ try { } ``` -## How do I hide the status bar to get the immersive effect? - -Applicable to: OpenHarmony 3.2 Beta5 (API version 9) - -**Solution** - -1. Use **onWindowStageCreate** to obtain a **windowClass** object. - - ``` - onWindowStageCreate(windowStage) { - // When the main window is created, set the main page for this ability. - console.log("[Demo] MainAbility onWindowStageCreate") - windowStage.getMainWindow((err, data) => { - if (err.code) { - console.error('Failed to obtain the main window.') - return; - } - // Obtain a windowClass object. - globalThis.windowClass = data; - }) - } - ``` - -2. Enable the full-screen mode for the window and hide the status bar. - - ``` - globalThis.windowClass.setFullScreen(isFullScreen, (err, data) => { - if (err.code) { - console.error('Failed to enable the full-screen mode. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data)); - }); - ``` - - ## How do I obtain the window width and height? Applicable to: OpenHarmony 3.2 Beta5 (API version 9, stage model) diff --git a/en/application-dev/faqs/full-sdk-compile-guide.md b/en/application-dev/faqs/full-sdk-compile-guide.md index 93f94af15a90fac8cd2c87690e9c1ddbefebf559..984f34191b6eac5148782ec71755a9bfe27794c4 100644 --- a/en/application-dev/faqs/full-sdk-compile-guide.md +++ b/en/application-dev/faqs/full-sdk-compile-guide.md @@ -1,8 +1,8 @@ # Full SDK Compilation -The full SDK provides a full set of APIs available in OpenHarmony, including system APIs required by system applications. Vendors can leverage this SDK to develop applications. +The full SDK provides a full set of APIs available in OpenHarmony, including system APIs required by system applications. Vendors can use this SDK to develop applications. -Since OpenHarmony 3.2 Beta5, the full SDK is not provided with the version. If necessary, you can compile the SDK using the full source code. +Since OpenHarmony 3.2 Beta5, the full SDK is not provided with the version. You can obtain the full SDK by compiling the source code. ## Compiling the Full SDK @@ -17,13 +17,20 @@ Since OpenHarmony 3.2 Beta5, the full SDK is not provided with the version. If n 2. Download source code based on the downloaded manifest repository: **repo sync -c -d --force-sync** -3. Perform precompilation: **yes y | apt install libxinerama-dev libxcursor-dev libxrandr-dev libxi-dev && rm -rf prebuilts/clang/ohos/darwin-x86_64/clang-480513 && rm -rf prebuilts/clang/ohos/windows-x86_64/clang-480513 && rm -rf prebuilts/clang/ohos/linux-x86_64/clang-480513 && bash build/prebuilts_download.sh -ndk && apt-get update -qqy && apt-get install doxygen -y --force-yes** +3. Perform precompilation: -4. Perform compilation: **./build.sh --product-name ohos-sdk** + yes y | apt install libxinerama-dev libxcursor-dev libxrandr-dev libxi-dev && rm -rf prebuilts/clang/ohos/darwin-x86_64/clang-480513 && rm -rf prebuilts/clang/ohos/windows-x86_64/clang-480513 && rm -rf prebuilts/clang/ohos/linux-x86_64/clang-480513 && apt-get update -qqy && apt-get install doxygen -y --force-yes +4. Perform compilation on Windows: + + ./build.sh --product-name ohos-sdk + +5. Perform compilation on macOS: + + ./build.sh --product-name ohos-sdk --gn-args full_mini_debug=false --keep-ninja-going --gn-args=is_use_check_deps=false If the compilation is successful, export the files in the **out/sdk/packages/ohos-sdk/** directory. ## Replacing the SDK -After the full SDK is compiled, switch to it in DevEco Studio. For details, see [Guide to Switching to Full SDK](full-sdk-switch-guide.md). +After the full SDK is compiled, switch to it in DevEco Studio. For details, see [Switching to Full SDK](full-sdk-switch-guide.md). diff --git a/en/application-dev/file-management/save-user-file.md b/en/application-dev/file-management/save-user-file.md index a5cc3306c680ec9f5d1463de940e1844c5692a19..d18dee640df7f524cfeaa8c9f05264955b91be2c 100644 --- a/en/application-dev/file-management/save-user-file.md +++ b/en/application-dev/file-management/save-user-file.md @@ -2,7 +2,7 @@ When a user needs to download a file from the network to a local directory or save a user file into another directory, use **FilePicker** to save the file. -The operations for saving images, audio or video clips, and documents are similar. Call **save()** of the corresponding picker instance and pass in **saveOptions**. No permission is required if your application uses **FilePicker** to access files. +The operations for saving images, audio or video clips, and documents are similar. Call **save()** of the corresponding picker instance and pass in **saveOptions**. You do not need to apply for any permission for this type of APIs. The **save()** method saves files in the file manager, not in **Gallery**. @@ -58,7 +58,7 @@ For example, select an image from **Gallery** and save it to the file manager. The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. ```ts - let uri:string; + let uris = null; async photoViewPickerSave() { try { const photoSaveOptions = new picker.PhotoSaveOptions(); // Create a photoSaveOptions instance. @@ -68,9 +68,8 @@ For example, select an image from **Gallery** and save it to the file manager. try { let photoSaveResult = await photoViewPicker.save(photoSaveOptions); if (photoSaveResult != undefined) { - console.info("[picker] photoViewPickerSave photoSaveResult = " + JSON.stringify(photoSaveResult)); - this.uri = photoSaveResult[0]; - console.info('photoViewPicker.save to file succeed and uri is:' + photoSaveResult[0]); + uris = photoSaveResult; + console.info('photoViewPicker.save to file succeed and uris are:' + uris); } } catch (err) { console.error(`[picker] Invoke photoViewPicker.save failed, code is ${err.code}, message is ${err.message}`); @@ -112,6 +111,7 @@ For example, select an image from **Gallery** and save it to the file manager. ```ts const documentSaveOptions = new picker.DocumentSaveOptions(); // Create a documentSaveOptions instance. documentSaveOptions.newFileNames = ["DocumentViewPicker01.txt"]; // (Optional) Set the name of the document to save. + documentSaveOptions.fileSuffixChoices = ['.png', '.txt', '.mp4']; // (Optional) Types of the documents to save. ``` 3. Create a **documentViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-3) to open the **FilePicker** page to save the document. After the user selects the destination folder, the document is saved and the URI of the document saved is returned. @@ -119,11 +119,11 @@ For example, select an image from **Gallery** and save it to the file manager. The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. ```ts - let uri = null; + let uris = null; const documentViewPicker = new picker.DocumentViewPicker(); // Create a documentViewPicker instance. documentViewPicker.save(documentSaveOptions).then((documentSaveResult) => { - uri = documentSaveResult[0]; - console.info('documentViewPicker.save to file succeed and uri is:' + uri); + uris = documentSaveResult; + console.info('documentViewPicker.save to file succeed and uris are:' + uris); }).catch((err) => { console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`); }) diff --git a/en/application-dev/file-management/select-user-file.md b/en/application-dev/file-management/select-user-file.md index 041d20f308e47b7757de53a4735958e54bba6f2e..61c33d630662d5707d6c687fad0acc5624c3fa09 100644 --- a/en/application-dev/file-management/select-user-file.md +++ b/en/application-dev/file-management/select-user-file.md @@ -1,6 +1,6 @@ # Selecting User Files -If your application needs to support share and saving of user files (such as images and videos), you can use OpenHarmony [FilePicker](../reference/apis/js-apis-file-picker.md) to implement selection and saving of user files. No permission is required if your application uses **FilePicker** to access files. +If your application needs to support share and saving of user files (such as images and videos), you can use OpenHarmony [FilePicker](../reference/apis/js-apis-file-picker.md) to implement selection and saving of user files. You do not need to apply for any permission for this type of APIs. The **FilePicker** provides the following interfaces by file type: @@ -25,24 +25,24 @@ The **FilePicker** provides the following interfaces by file type: const photoSelectOptions = new picker.PhotoSelectOptions(); ``` -3. Set the file type and the maximum number of media files to select.
+3. Set the file type and the maximum number of media files to select. + For example, select a maximum of five images. For details about the media file types, see [PhotoViewMIMETypes](../reference/apis/js-apis-file-picker.md#photoviewmimetypes). - ```ts photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; // Select images. photoSelectOptions.maxSelectNumber = 5; // Set the maximum number of images to select. ``` 4. Create a **photoPicker** instance and call [select()](../reference/apis/js-apis-file-picker.md#select) to open the **FilePicker** page for the user to select files. After the files are selected, [PhotoSelectResult](../reference/apis/js-apis-file-picker.md#photoselectresult) is returned. - + The permission on the URIs returned by **select()** is read-only. Further file operations can be performed based on the URIs in the **PhotoSelectResult**. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. ```ts - let uri = null; + let uris = null; const photoViewPicker = new picker.PhotoViewPicker(); photoViewPicker.select(photoSelectOptions).then((photoSelectResult) => { - uri = photoSelectResult.photoUris[0]; - console.info('photoViewPicker.select to file succeed and uri is:' + uri); + uris = photoSelectResult.photoUris; + console.info('photoViewPicker.select to file succeed and uris are:' + uris); }).catch((err) => { console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`); }) @@ -77,6 +77,9 @@ The **FilePicker** provides the following interfaces by file type: ```ts const documentSelectOptions = new picker.DocumentSelectOptions(); + documentSelectOptions.maxSelectNumber = 5; // (Optional) Maximum number of documents to select. + documentSelectOptions.defaultFilePathUri = "file://docs/storage/Users/currentUser/test"; // (Optional) Path of the file or directory to select. + documentSelectOptions.fileSuffixFilters = ['.png', '.txt', '.mp4']; // (Optional) File name extensions of the documents to select. ``` 3. Create a **documentViewPicker** instance, and call [**select()**](../reference/apis/js-apis-file-picker.md#select-3) to open the **FilePicker** page for the user to select documents. After the documents are selected, a result set containing the file URIs is returned. @@ -85,16 +88,12 @@ The **FilePicker** provides the following interfaces by file type: For example, you can use [file management APIs](../reference/apis/js-apis-file-fs.md) to obtain file attributes, such as the file size, access time, and last modification time, based on the URI. If you need to obtain the file name, use [startAbilityForResult](../../application-dev/application-models/uiability-intra-device-interaction.md). - > **NOTE** - > - > Currently, **DocumentSelectOptions** is not configurable. By default, all types of user files are selected. - ```ts - let uri = null; + let uris = null; const documentViewPicker = new picker.DocumentViewPicker(); // Create a documentViewPicker instance. documentViewPicker.select(documentSelectOptions).then((documentSelectResult) => { - uri = documentSelectResult[0]; - console.info('documentViewPicker.select to file succeed and uri is:' + uri); + uris = documentSelectResult; + console.info('documentViewPicker.select to file succeed and uris are:' + uris); }).catch((err) => { console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`); }) @@ -172,7 +171,7 @@ The **FilePicker** provides the following interfaces by file type: let uri = null; const audioViewPicker = new picker.AudioViewPicker(); audioViewPicker.select(audioSelectOptions).then(audioSelectResult => { - uri = audioSelectOptions[0]; + uri = audioSelectResult[0]; console.info('audioViewPicker.select to file succeed and uri is:' + uri); }).catch((err) => { console.error(`Invoke audioViewPicker.select failed, code is ${err.code}, message is ${err.message}`); diff --git a/en/application-dev/napi/neural-network-runtime-guidelines.md b/en/application-dev/napi/neural-network-runtime-guidelines.md index cfb50fdc086b8912e0d5b3a81ec2b7ef9c29e153..b1a13ecd7bf4e1050ca98ef465fd65a1ae543279 100644 --- a/en/application-dev/napi/neural-network-runtime-guidelines.md +++ b/en/application-dev/napi/neural-network-runtime-guidelines.md @@ -19,7 +19,7 @@ The environment requirements for the Neural Network Runtime are as follows: - Development environment: Ubuntu 18.04 or later. - Access device: a standard device running OpenHarmony. The built-in hardware accelerator driver has been connected to the Neural Network Runtime through an HDI API. -The Neural Network Runtime is opened to external systems through OpenHarmony Native APIs. Therefore, you need to use the Native development suite of the OpenHarmony to compile Neural Network Runtime applications. +The Neural Network Runtime is opened to external systems through OpenHarmony Native APIs. Therefore, you need to use the Native development suite of the OpenHarmony to compile Neural Network Runtime applications. ### Environment Setup @@ -484,3 +484,8 @@ The development process of the Neural Network Runtime consists of three phases: rm /data/local/tmp/*nncache ``` +## Samples + +The following sample is provided to help you understand how to connect a third-party AI inference framework to the Neural Network Runtime: + +- [Development Guide for Connecting TensorFlow Lite to NNRt Delegate](https://gitee.com/openharmony/ai_neural_network_runtime/tree/master/example/deep_learning_framework) diff --git a/en/application-dev/napi/xcomponent-guidelines.md b/en/application-dev/napi/xcomponent-guidelines.md index dd365dd461a3bf868451b047aecd1c8f68c5b390..87b0b1e6acf114c1b6ad9b2f39ccfd7804c1adcc 100644 --- a/en/application-dev/napi/xcomponent-guidelines.md +++ b/en/application-dev/napi/xcomponent-guidelines.md @@ -81,7 +81,7 @@ The following describes how to use the **\** to call the native APIs // ... ``` -2. Register the N-API module. For details, see [Using Native APIs in Application Projects](https://gitee.com/openharmony/docs/blob/master/en/application-dev/napi/napi-guidelines.md). +2. Register the N-API module. For details, see [Using Native APIs in Application Projects](napi-guidelines.md). ```c++ // In the napi_init.cpp file, use the Init method to register the target function to transfer the encapsulated C++ methods for the JS side to call. diff --git a/en/application-dev/performance/Readme.md b/en/application-dev/performance/Readme.md index 8172a210af94348fdb22831295c90a19b74965e6..c2e65ad02feaabc1fa88e7beb5f96af3c249568d 100644 --- a/en/application-dev/performance/Readme.md +++ b/en/application-dev/performance/Readme.md @@ -6,7 +6,7 @@ Following these practices, you can reduce your application's startup time, respo - Improving application startup and response time - - [Speeding Up Application Cold Start](../performance/improve-application-startup-and-response/improve-application-cold-start-speed.md) + - [Speeding Up Application Cold Start](improve-application-startup-and-response/improve-application-cold-start-speed.md) Application startup latency is a key factor that affects user experience. To speed up the application cold start, you are advised to perform optimization in the following four phases: @@ -18,16 +18,16 @@ Following these practices, you can reduce your application's startup time, respo ​ 4. Home page loading and drawing - - [Speeding Up Application Response](../performance/improve-application-startup-and-response/improve-application-response.md) + - [Speeding Up Application Response](improve-application-startup-and-response/improve-application-response.md) - A premium interaction experience requires quick response to user input. To improve your application's response time, you are advised to prevent the main thread from being blocked by non-UI tasks and reduce the number of component to be refreshed. + A premium interaction experience requires quick response to user input. To improve your application's response time, you are advised to prevent the main thread from being blocked by non-UI tasks and reduce the number of components to be refreshed. - Reducing frame loss - - [Reducing Nesting](../performance/reduce-frame-loss-and-frame-freezing/reduce-view-nesting-levels.md) + - [Reducing Nesting](reduce-frame-loss-and-frame-freezing/reduce-view-nesting-levels.md) The smoothness of rendering the layout to the screen affects the user perceived quality. It is recommended that you minimize nesting in your code to shorten the render time. - - [Reducing Frame Loss](../performance/reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md) + - [Reducing Frame Loss](reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md) Whether animations in your application run smoothly is a key factor that affects user experience. You are advised to use the system-provided animation APIs to reduce frame loss. diff --git a/en/application-dev/performance/improve-application-startup-and-response/improve-application-cold-start-speed.md b/en/application-dev/performance/improve-application-startup-and-response/improve-application-cold-start-speed.md index b99c5dfc0ac84d75954b53b3a5c291bf60f4314e..0a8dd8883f62b7502c51ac8a51894e81adddea5f 100644 --- a/en/application-dev/performance/improve-application-startup-and-response/improve-application-cold-start-speed.md +++ b/en/application-dev/performance/improve-application-startup-and-response/improve-application-cold-start-speed.md @@ -4,7 +4,7 @@ Application startup latency is a key factor that affects user experience. When a ## Analyzing the Time Required for Application Cold Start -The cold start process of OpenHarmony applications can be divided into four phases: application process creation and initialization, application and ability initialization, ability lifecycle, and home page loading and drawing, as shown in the following figure. +The cold start process of OpenHarmony applications can be divided into four phases: application process creation and initialization, application and ability initialization, ability lifecycle, and home page loading and drawing, as shown below. ![application-cold-start](../figure/application-cold-start.png) @@ -24,7 +24,7 @@ With regard to the icon of the startup page, the recommended maximum resolution "description": "$string:EntryAbility_desc", "icon": "$media:icon", "label": "$string:EntryAbility_label", - "startWindowIcon": "$media:startWindowIcon", // Modify the icon of the startup page. It is recommended that the icon be less than or equal to 256 pixels x 256 pixels. + "startWindowIcon": "$media:startWindowIcon", // Modify the icon of the startup page. It is recommended that the icon be less than or equal to 256 x 256 pixels. "startWindowBackground": "$color:start_window_background", "visible": true, "skills": [ @@ -43,7 +43,7 @@ With regard to the icon of the startup page, the recommended maximum resolution ## 2. Shortening Time Required for Application and Ability Initialization -In this phase of application and ability initialization, resources are loaded, VMs are created, application and ability related objects are created and initialized, and dependent modules are loaded. +In this phase of application and ability initialization, resources are loaded, virtual machines are created, application and ability related objects are created and initialized, and dependent modules are loaded. ### Minimizing the Number of Imported Modules @@ -57,7 +57,7 @@ In this phase of ability lifecycle, the ability lifecycle callbacks are executed In the application startup process, the system executes the ability lifecycle callbacks. Whenever possible, avoid performing time-consuming operations in these callbacks. You are advised to perform time-consuming operations through asynchronous tasks or execute them in other threads. -In these lifecycle callbacks, perform only necessary operations. For details, see [UIAbility Lifecycle](https://gitee.com/openharmony/docs/blob/master/en/application-dev/application-models/uiability-lifecycle.md). +In these lifecycle callbacks, perform only necessary operations. For details, see [UIAbility Lifecycle](../../application-models/uiability-lifecycle.md). ## 4. Shortening Time Required for Home Page Loading and Drawing diff --git a/en/application-dev/performance/improve-application-startup-and-response/improve-application-response.md b/en/application-dev/performance/improve-application-startup-and-response/improve-application-response.md index b740edb6f1f4e2df007631f6feef966762e0d2ba..989cfe91758f2c66830e5f277bbe19ba800f0a93 100644 --- a/en/application-dev/performance/improve-application-startup-and-response/improve-application-response.md +++ b/en/application-dev/performance/improve-application-startup-and-response/improve-application-response.md @@ -61,7 +61,7 @@ struct ImageExample1 { ### Using TaskPool for Asynchronous Processing -Compared with the worker thread, [TaskPool](https://gitee.com/sqsyqqy/docs/blob/master/en/application-dev/reference/apis/js-apis-taskpool.md) provides the task priority setting and automatic thread pool management mechanism. The following is an example: +Compared with the worker thread, [TaskPool](../../reference/apis/js-apis-taskpool.md) provides the task priority setting and automatic thread pool management mechanism. The following is an example: ```javascript import taskpool from '@ohos.taskpool'; diff --git a/en/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md b/en/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md index a61c8649e392b7fd0055e63ab48e0fa335faab7f..0a34c272b6a28109637eb3e3cb9a5ff591dc43ca 100644 --- a/en/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md +++ b/en/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md @@ -90,7 +90,7 @@ struct AttrAnimationExample { } ``` -For more details, see [Property Animator](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/arkui-ts/ts-animatorproperty.md). +For more details, see [Property Animation](../../reference/arkui-ts/ts-animatorproperty.md). ## Using System-Provided Explicit Animation APIs @@ -139,4 +139,4 @@ struct AnimateToExample { } ``` -For more details, see [Explicit Animation](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/arkui-ts/ts-explicit-animation.md). +For more details, see [Explicit Animation](../../reference/arkui-ts/ts-explicit-animation.md). diff --git a/en/application-dev/quick-start/arkts-application-state-management-overview.md b/en/application-dev/quick-start/arkts-application-state-management-overview.md index b481f79298e585c00a8a6e5c80f1c6a5cc092949..951153b3576e906d499a2cbc14063cfd869dc293 100644 --- a/en/application-dev/quick-start/arkts-application-state-management-overview.md +++ b/en/application-dev/quick-start/arkts-application-state-management-overview.md @@ -4,10 +4,10 @@ The decorators described in the previous topics are used to share state variables within a page, that is, within a component tree. If you want to share state data at the application level or across multiple pages, you would need to apply application-level state management. ArkTS provides a wide variety of application state management capabilities: -- [LocalStorage](arkts-localstorage.md): API for storing the UI state, usually used for state sharing within a [UIAbility](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md) or between pages. +- [LocalStorage](arkts-localstorage.md): API for storing the UI state, usually used for state sharing within a [UIAbility](../reference/apis/js-apis-app-ability-uiAbility.md) or between pages. - [AppStorage](arkts-appstorage.md): special, singleton LocalStorage object within the application, which is created by the UI framework at application startup and provides the central storage for application UI state attributes. - [PersistentStorage](arkts-persiststorage.md): API for persisting application attributes. It is usually used together with AppStorage to persist selected AppStorage attributes to the disk so that their values are the same upon application re-start as they were when the application was closed. -- [Environment](arkts-environment.md): a range of environment parameters regarding the device where the application runs. The environment parameters are synchronized to the AppStorage and can be used together with the AppStorage. +- [Environment](arkts-environment.md): a range of environment parameters regarding the device where the application runs. The environment parameters are synchronized to AppStorage and can be used together with AppStorage. diff --git a/en/application-dev/quick-start/arkts-appstorage.md b/en/application-dev/quick-start/arkts-appstorage.md index 50cbcf6aa0854fc901eb6bbf80b41da7c990eaa1..90f97beb2733ad6f0d61803c61147ae3eb5ee6e1 100644 --- a/en/application-dev/quick-start/arkts-appstorage.md +++ b/en/application-dev/quick-start/arkts-appstorage.md @@ -23,8 +23,7 @@ Selected state attributes of AppStorage can be synced with different data source As mentioned above, if you want to establish a binding between AppStorage and a custom component, you'll need the \@StorageProp and \@StorageLink decorators. Use \@StorageProp(key) or \@StorageLink(key) to decorate variables in the component, where **key** identifies the attribute in AppStorage. -When a custom component is initialized, the \@StorageProp(key)/\@StorageLink(key) decorated variable is initialized with the value of the attribute with the given key in AppStorage. Local initialization is mandatory. If an attribute with the given key is missing from AppStorage, it will be added with the stated initializing value. (Whether the attribute with the given key exists in AppStorage depends on the application logic.) - +When a custom component is initialized, the \@StorageProp(key)/\@StorageLink(key) decorated variable is initialized with the value of the attribute with the given key in AppStorage. Whether the attribute with the given key exists in AppStorage depends on the application logic. This means that the attribute with the given key may be missing from AppStorage. In light of this, local initialization is mandatory for the \@StorageProp(key)/\@StorageLink(key) decorated variable. By decorating a variable with \@StorageProp(key), a one-way data synchronization is established with the attribute with the given key in AppStorage. A local change can be made, but it will not be synchronized to AppStorage. An update to the attribute with the given key in AppStorage will overwrite local changes. diff --git a/en/application-dev/quick-start/arkts-builder.md b/en/application-dev/quick-start/arkts-builder.md index 80a262fcd97a0dcf6808bf8cdb84bf78849cb0e1..ab1c53b103db98c49fa42a21f69adff6ea32b86b 100644 --- a/en/application-dev/quick-start/arkts-builder.md +++ b/en/application-dev/quick-start/arkts-builder.md @@ -21,14 +21,14 @@ Syntax: ```ts -@Builder myBuilderFunction({ ... }) +@Builder MyBuilderFunction({ ... }) ``` Usage: ```ts -this.myBuilderFunction({ ... }) +this.MyBuilderFunction({ ... }) ``` - Defining one or more custom builder (\@Builder decorated) functions inside a custom component is allowed. Such a custom builder function can be considered as a private, special type of member functions of that component. @@ -66,7 +66,7 @@ There are two types of parameter passing for custom builder functions: [by-value - The parameter type must be the same as the declared parameter type. The **undefined** or **null** constants as well as expressions evaluating to these values are not allowed. -- All parameters are immutable inside the custom builder function. If mutability and synchronization of the mutation is required, the custom builder should be replaced by a custom component with a [@Link](arkts-link.md) decorated variable. +- All parameters are immutable inside the@Builder decorated function. - The \@Builder function body follows the same [syntax rules](arkts-create-custom-components.md#build-function) as the **build** function. diff --git a/en/application-dev/quick-start/arkts-environment.md b/en/application-dev/quick-start/arkts-environment.md index 2f0718290460508c4510acc298fa85c855bbec26..ac80bd54590b0dffdfa6b3bf82351d27f09917a1 100644 --- a/en/application-dev/quick-start/arkts-environment.md +++ b/en/application-dev/quick-start/arkts-environment.md @@ -15,12 +15,11 @@ Environment is a singleton object created by the ArkUI framework at application - Use **Environment.EnvProp** to save the environment variables of the device to AppStorage. ```ts - // Save the language code of the device to AppStorage. The default value is en. - // Whenever its value changes in the device environment, it will update its value in AppStorage. + // Save languageCode to AppStorage. The default value is en. Environment.EnvProp('languageCode', 'en'); ``` -- To keep a component variable updated with changes in the device environment, this variable should be decorated with \@StorageProp. +- Decorate the variables with \@StorageProp to link them with components. ```ts @StorageProp('languageCode') lang : string = 'en'; @@ -29,6 +28,7 @@ Environment is a singleton object created by the ArkUI framework at application The chain of updates is as follows: Environment > AppStorage > Component. > **NOTE** +> > An \@StorageProp decorated variable can be locally modified, but the change will not be updated to AppStorage. This is because the environment variable parameters are read-only to the application. @@ -69,3 +69,29 @@ if (lang.get() === 'en') { console.info('Hello!'); } ``` + + +## Restrictions + + +Environment can be called only when the [UIContext](../reference/apis/js-apis-arkui-UIContext.md#uicontext), which can be obtained through [runScopedTask](../reference/apis/js-apis-arkui-UIContext.md#runscopedtask), is specified. If Environment is called otherwise, no device environment data can be obtained. + + +```ts +// EntryAbility.ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; + +export default class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + windowStage.loadContent('pages/Index'); + let window = windowStage.getMainWindow() + window.then(window => { + let uicontext = window.getUIContext() + uicontext.runScopedTask(() => { + Environment.EnvProp('languageCode', 'en'); + }) + }) + } +} +``` diff --git a/en/application-dev/quick-start/arkts-get-started.md b/en/application-dev/quick-start/arkts-get-started.md index 79a401430c1a746c1850d6e6b64b72b76487b30b..76cf2844ca662c5f508dac5c574078a201a6eeff 100644 --- a/en/application-dev/quick-start/arkts-get-started.md +++ b/en/application-dev/quick-start/arkts-get-started.md @@ -7,16 +7,16 @@ ArkTS is the preferred main programming language for application development in The following syntaxes in TS are restricted in ArkTS: -- Static typing is enforced. Static typing is one of the most important features of ArkTS. If the program is statically typed, i.e. all types are known at the compile time, it’s much easier to understand which data structures are used in the code. At the same time, since all types are known before the program actually runs, code correctness can be verified by the compiler, which eliminates many runtime type checks and improves the performance. +- Static typing is enforced. Static typing is one of the most important features of ArkTS. If the program is statically typed, that is, all types are known at the compile time, it's much easier to understand which data structures are used in the code. At the same time, since all types are known before the program actually runs, code correctness can be verified by the compiler, which eliminates many runtime type checks and improves the performance. - Changing object layout in runtime is prohibited. To achieve maximum performance benefits, ArkTS requires that layout of objects does not change during program execution. -- Semantics of operators is restricted. To achieve better performance and encourage developers to write cleaner code, ArkTS restricts the semantics of operators. Such as, the binary `+` operator supports only for strings and numbers but not for objects. +- Semantics of operators is restricted. To achieve better performance and encourage developers to write cleaner code, ArkTS restricts the semantics of operators. For example, the binary `+` operator is supported for strings and numbers, but not for objects. -- structural typing is not supported. Support for structural typing is a major feature which needs lots of consideration and careful implementation in language specification, compiler and runtime. Currently, ArkTS does not supports structural typing. The team will be ready to reconsider based on real-world scenarios and feedback. +- Structural typing is not supported. Support for structural typing is a major feature that needs lots of consideration and careful implementation in language specification, compiler and runtime. Currently, ArkTS does not supports structural typing. The team will be ready to reconsider this feature based on real-world scenarios and feedback. -The added features offered by ArkTS for ArkUI framework include the following: +The added features offered by ArkTS for the ArkUI framework include the following: - [Basic syntax](arkts-basic-syntax-overview.md): ArkTS defines declarative UI description, custom components, and dynamic extension of UI elements. All these, together with built-in components, event methods, and attribute methods in ArkUI, jointly underpin UI development. diff --git a/en/application-dev/quick-start/arkts-localstorage.md b/en/application-dev/quick-start/arkts-localstorage.md index 0116d2e18f9023d5769b6b0b67b561b41bb0e149..392dda8432319b5695c593de178c5193fcf2a976 100644 --- a/en/application-dev/quick-start/arkts-localstorage.md +++ b/en/application-dev/quick-start/arkts-localstorage.md @@ -36,7 +36,7 @@ LocalStorage provides two decorators based on the synchronization type of the co ## Restrictions - Once created, the type of a named attribute cannot be changed. Subsequent calls to **Set** must set a value of same type. -- LocalStorage provides page-level storage. The [GetShared](../reference/arkui-ts/ts-state-management.md#getshared9) API can only obtain the LocalStorage instance transferred through [windowStage.loadContent](../reference/apis/js-apis-window.md#loadcontent9) in the current stage. Otherwise, **undefined** is returned. Example: [Sharing a LocalStorage Instance from UIAbility to One or More Pages](#sharing-a-localstorage-instance-from-uiability-to-one-or-more-pages). +- LocalStorage provides page-level storage. The [GetShared](../reference/arkui-ts/ts-state-management.md#getshared10) API can only obtain the LocalStorage instance passed through [windowStage.loadContent](../reference/apis/js-apis-window.md#loadcontent9) in the current stage. If the instance is not available, **undefined** is returned. For the example, see [Example of Sharing a LocalStorage Instance from UIAbility to One or More Pages](#example-of-sharing-a-localstorage-instance-from-uiability-to-one-or-more-pages). ## \@LocalStorageProp @@ -300,9 +300,9 @@ struct CompA { ``` -### State Variable Synchronization Between Sibling Nodes +### Example of Syncing State Variable Between Sibling Components -This example shows how to use \@LocalStorageLink to create a two-way synchronization for the state between sibling nodes. +This example shows how to use \@LocalStorageLink to create a two-way synchronization for the state between sibling components. Check the changes in the **Parent** custom component. @@ -377,7 +377,7 @@ Changes in the **Child** custom component: ``` -### Sharing a LocalStorage Instance from UIAbility to One or More Pages +### Example of Sharing a LocalStorage Instance from UIAbility to One or More Pages In the preceding examples, the LocalStorage instance is shared only in an \@Entry decorated component and its owning child component (a page). To enable a LocalStorage instance to be shared across pages, you can create a LocalStorage instance in the owning UIAbility and call windowStage.[loadContent](../reference/apis/js-apis-window.md#loadcontent9). diff --git a/en/application-dev/quick-start/arkts-persiststorage.md b/en/application-dev/quick-start/arkts-persiststorage.md index fdbacd4235dcd50ea2777e8e3695227ff02be70c..21c854c26557e5fcd5027623b0429b625d6c9c91 100644 --- a/en/application-dev/quick-start/arkts-persiststorage.md +++ b/en/application-dev/quick-start/arkts-persiststorage.md @@ -24,7 +24,7 @@ Persistence of data is a relatively slow operation. Applications should avoid th The preceding situations may overload the change process of persisted data. As a result, the PersistentStorage implementation may limit the change frequency of persisted attributes. -PersistentStorage is associated with UIContext and can be called to persist data only when [UIContext](../reference/apis/js-apis-arkui-UIContext.md#uicontext) is specified. The context can be identified in [runScopedTask](../reference/apis/js-apis-arkui-UIContext.md#runscopedtask). +PersistentStorage can be called to persist data only when the [UIContext](../reference/apis/js-apis-arkui-UIContext.md#uicontext), which can be obtained through [runScopedTask](../reference/apis/js-apis-arkui-UIContext.md#runscopedtask), is specified. ## Application Scenarios diff --git a/en/application-dev/quick-start/arkts-rendering-control-foreach.md b/en/application-dev/quick-start/arkts-rendering-control-foreach.md index 4c916bec86f9c9d22b9bdb60ca476f9cbdcd4846..dc6ae173f51df82fbc48f26df56368450fa6fa79 100644 --- a/en/application-dev/quick-start/arkts-rendering-control-foreach.md +++ b/en/application-dev/quick-start/arkts-rendering-control-foreach.md @@ -3,6 +3,9 @@ **ForEach** enables repeated content based on array-type data. +> **NOTE** +> +> Since API version 9, this API is supported in ArkTS widgets. ## API Description @@ -19,15 +22,15 @@ ForEach( | Name | Type | Mandatory | Description | | ------------- | ---------------------------------------- | ---- | ---------------------------------------- | | arr | Array | Yes | An array, which can be empty, in which case no child component is created. The functions that return array-type values are also allowed, for example, **arr.slice (1, 3)**. The set functions cannot change any state variables including the array itself, such as **Array.splice**, **Array.sort**, and **Array.reverse**.| -| itemGenerator | (item: any, index?: number) => void | Yes | A lambda function used to generate one or more child components for each data item in an array. Each component and its child component list must be contained in parentheses.
**NOTE**
- The type of the child component must be the one allowed inside the parent container component of **ForEach**. For example, a **\** child component is allowed only when the parent container component of **ForEach** is **\**.
- The child build function is allowed to return an **if** or another **ForEach**. **ForEach** can be placed inside **if**.
- The optional **index** parameter should only be specified in the function signature if used in its body.| -| keyGenerator | (item: any, index?: number) => string | No | An anonymous function used to generate a unique and fixed key value for each data item in an array. This key-value generator is optional. However, for performance reasons, it is strongly recommended that the key-value generator be provided, so that the development framework can better identify array changes. For example, if no key-value generator is provided, a reverse of an array will result in rebuilding of all nodes in **ForEach**.
**NOTE**
- Two items inside the same array must never work out the same ID.
- If **index** is not used, an item's ID must not change when the item's position within the array changes. However, if **index** is used, then the ID must change when the item is moved within the array.
- When an item is replaced by a new one (with a different value), the ID of the replaced and the ID of the new item must be different.
- When **index** is used in the build function, it should also be used in the ID generation function.
- The ID generation function is not allowed to mutate any component state.| +| itemGenerator | (item: any, index?: number) => void | Yes | A lambda function used to generate one or more child components for each data item in an array. Each component and its child component list must be contained in parentheses.
**NOTE**
- The type of the child component must be the one allowed inside the parent container component of **ForEach**. For example, a **\** child component is allowed only when the parent container component of **ForEach** is **\**.
- The child build function is allowed to return an **if** or another **ForEach**. **ForEach** can be placed inside **if**.
- The optional **index** parameter should only be specified in the function signature if used in its body.| +| keyGenerator | (item: any, index?: number) => string | No | An anonymous function used to generate a unique and fixed key value for each data item in an array. This key-value generator is optional. However, for performance reasons, it is strongly recommended that the key-value generator be provided, so that the development framework can better identify array changes. For example, if no key-value generator is provided, a reverse of an array will result in rebuilding of all nodes in **ForEach**.
**NOTE**
- Two items inside the same array must never work out the same ID.
- If **index** is not used, an item's ID must not change when the item's position within the array changes. However, if **index** is used, then the ID must change when the item is moved within the array.
- When an item is replaced by a new one (with a different value), the ID of the replaced and the ID of the new item must be different.
- When **index** is used in the build function, it should also be used in the ID generation function.
- The ID generation function is not allowed to mutate any component state.| ## Restrictions - **ForEach** must be used in container components. -- The type of the child component must be the one allowed inside the parent container component of **ForEach**. +- The type of the child component must be the one allowed inside the parent container component of **ForEach**. - The **itemGenerator** function can contain an **if/else** statement, and an **if/else** statement can contain **ForEach**. diff --git a/en/application-dev/quick-start/arkts-rendering-control-lazyforeach.md b/en/application-dev/quick-start/arkts-rendering-control-lazyforeach.md index 95b6665c834a4bdf281b4712717e71f51659c112..30ca2da92bbe84a9f5dd5a7882afac9927c9913e 100644 --- a/en/application-dev/quick-start/arkts-rendering-control-lazyforeach.md +++ b/en/application-dev/quick-start/arkts-rendering-control-lazyforeach.md @@ -34,8 +34,8 @@ interface DataChangeListener { | Name | Type | Mandatory | Description | | ------------- | --------------------------------------- | ---- | ---------------------------------------- | | dataSource | IDataSource | Yes | **LazyForEach** data source. You need to implement related APIs. | -| itemGenerator | (item: any) => void | Yes | Child component generation function, which generates a child component for each data item in the array.
**NOTE**
The function body of **itemGenerator** must be included in braces {...}. **itemGenerator** can and must generate only one child component for each iteration. The **if** statement is allowed in **itemGenerator**, but you must ensure that each branch of the **if** statement creates a child component of the same type. **ForEach** and **LazyForEach** statements are not allowed in **itemGenerator**.| -| keyGenerator | (item: any) => string | No | ID generation function, which generates a unique and fixed ID for each data item in the data source. This ID must remain unchanged for the data item even when the item is relocated in the array. When the item is replaced by a new item, the ID of the new item must be different from that of the replaced item. This ID generation function is optional. However, for performance reasons, it is strongly recommended that the ID generation function be provided, so that the framework can better identify array changes. For example, if no ID generation function is provided, a reverse of an array will result in rebuilding of all nodes in **LazyForEach**.
**NOTE**
The ID generated for each data item in the data source must be unique.| +| itemGenerator | (item: any) => void | Yes | Child component generation function, which generates a child component for each data item in the array.
**NOTE**
The function body of **itemGenerator** must be included in braces {...}. **itemGenerator** can and must generate only one child component for each iteration. The **if** statement is allowed in **itemGenerator**, but you must ensure that each branch of the **if** statement creates a child component of the same type. **ForEach** and **LazyForEach** statements are not allowed in **itemGenerator**.| +| keyGenerator | (item: any) => string | No | ID generation function, which generates a unique and fixed ID for each data item in the data source. This ID must remain unchanged for the data item even when the item is relocated in the array. When the item is replaced by a new item, the ID of the new item must be different from that of the replaced item. This ID generation function is optional. However, for performance reasons, it is strongly recommended that the ID generation function be provided, so that the framework can better identify array changes. For example, if no ID generation function is provided, a reverse of an array will result in rebuilding of all nodes in **LazyForEach**.
**NOTE**
The ID generated for each data item in the data source must be unique.| ## Description of IDataSource @@ -52,10 +52,10 @@ interface IDataSource { | Declaration | Parameter Type | Description | | ---------------------------------------- | ------------------ | ------------------------------------- | -| totalCount(): number | - | Obtains the total number of data records. | -| getData(index: number): any | number | Obtains the data record corresponding to the specified index.
**index**: index of the data record to obtain.| -| registerDataChangeListener(listener:DataChangeListener): void | DataChangeListener | Registers a listener for data changes.
**listener**: listener for data changes. | -| unregisterDataChangeListener(listener:DataChangeListener): void | DataChangeListener | Deregisters the listener for data changes.
**listener**: listener for data changes. | +| totalCount(): number | - | Obtains the total number of data records. | +| getData(index: number): any | number | Obtains the data record corresponding to the specified index.
**index**: index of the data record to obtain.| +| registerDataChangeListener(listener:DataChangeListener): void | DataChangeListener | Registers a listener for data changes.
**listener**: listener for data changes. | +| unregisterDataChangeListener(listener:DataChangeListener): void | DataChangeListener | Deregisters the listener for data changes.
**listener**: listener for data changes. | ## Description of DataChangeListener @@ -77,20 +77,20 @@ interface DataChangeListener { | Declaration | Parameter Type | Description | | ------------------------------------------------------------ | -------------------------------------- | ------------------------------------------------------------ | -| onDataReloaded(): void | - | Invoked when all data is reloaded. | -| onDataAdded(index: number):void(deprecated) | number | Invoked when data is added to the position indicated by the specified index.
This API is deprecated since API version 8. You are advised to use **onDataAdd** instead.
**index**: index of the position where data is added.| -| onDataMoved(from: number, to: number): void(deprecated) | from: number,
to: number | Invoked when data is moved.
This API is deprecated since API version 8. You are advised to use **onDataMove** instead.
**from**: original position of data; **to**: target position of data.
**NOTE**
The ID must remain unchanged before and after data movement. If the ID changes, APIs for deleting and adding data must be called.| -| onDataDeleted(index: number):void(deprecated) | number | Invoked when data is deleted from the position indicated by the specified index. LazyForEach will update the displayed content accordingly.
This API is deprecated since API version 8. You are advised to use **onDataDelete** instead.
**index**: index of the position where data is deleted.| -| onDataChanged(index: number): void(deprecated) | number | Invoked when data in the position indicated by the specified index is changed.
This API is deprecated since API version 8. You are advised to use **onDataChange** instead.
**index**: listener for data changes.| -| onDataAdd(index: number): void8+ | number | Invoked when data is added to the position indicated by the specified index.
**index**: index of the position where data is added.| -| onDataMove(from: number, to: number): void8+ | from: number,
to: number | Invoked when data is moved.
**from**: original position of data; **to**: target position of data.
**NOTE**
The ID must remain unchanged before and after data movement. If the ID changes, APIs for deleting and adding data must be called.| +| onDataReloaded(): void | - | Invoked when all data is reloaded. | +| onDataAdd(index: number): void8+ | number | Invoked when data is added to the position indicated by the specified index.
**index**: index of the position where data is added.| +| onDataMove(from: number, to: number): void8+ | from: number,
to: number | Invoked when data is moved.
**from**: original position of data; **to**: target position of data.
**NOTE**
The ID must remain unchanged before and after data movement. If the ID changes, APIs for deleting and adding data must be called.| | onDataDelete(index: number):void8+ | number | Invoked when data is deleted from the position indicated by the specified index. LazyForEach will update the displayed content accordingly.
**index**: index of the position where data is deleted.
**NOTE**
Before **onDataDelete** is called, ensure that the corresponding data in **dataSource** has been deleted. Otherwise, undefined behavior will occur during page rendering.| -| onDataChange(index: number): void8+ | number | Invoked when data in the position indicated by the specified index is changed.
**index**: index of the position where data is changed.| +| onDataChange(index: number): void8+ | number | Invoked when data in the position indicated by the specified index is changed.
**index**: index of the position where data is changed.| +| onDataAdded(index: number):void(deprecated) | number | Invoked when data is added to the position indicated by the specified index.
This API is deprecated since API version 8. You are advised to use **onDataAdd** instead.
**index**: index of the position where data is added.| +| onDataMoved(from: number, to: number): void(deprecated) | from: number,
to: number | Invoked when data is moved.
This API is deprecated since API version 8. You are advised to use **onDataMove** instead.
**from**: original position of data; **to**: target position of data.
**NOTE**
The ID must remain unchanged before and after data movement. If the ID changes, APIs for deleting and adding data must be called.| +| onDataDeleted(index: number):void(deprecated) | number | Invoked when data is deleted from the position indicated by the specified index. LazyForEach will update the displayed content accordingly.
This API is deprecated since API version 8. You are advised to use **onDataDelete** instead.
**index**: index of the position where data is deleted.| +| onDataChanged(index: number): void(deprecated) | number | Invoked when data in the position indicated by the specified index is changed.
This API is deprecated since API version 8. You are advised to use **onDataChange** instead.
**index**: listener for data changes.| ## Restrictions -- **LazyForEach** must be used in the container component. Only the **\**, **\**, and **\** components support lazy loading (that is, only the visible part and a small amount of data before and after the visible part are loaded for caching). For other components, all data is loaded at the same time. +- LazyForEach must be used in the container component. Only the [\](../reference/arkui-ts/ts-container-list.md), [\](../reference/arkui-ts/ts-container-grid.md), and [\](../reference/arkui-ts/ts-container-swiper.md) components support lazy loading (that is, only the visible part and a small amount of data before and after the visible part are loaded for caching). For other components, all data is loaded at the same time. - **LazyForEach** must create one and only one child component in each iteration. @@ -177,7 +177,7 @@ class BasicDataSource implements IDataSource { } class MyDataSource extends BasicDataSource { - private dataArray: string[] = ['/path/image0', '/path/image1', '/path/image2', '/path/image3']; + private dataArray: string[] = []; public totalCount(): number { return this.dataArray.length; @@ -201,6 +201,12 @@ class MyDataSource extends BasicDataSource { @Entry @Component struct MyComponent { + aboutToAppear() { + for (var i = 100; i >= 80; i--) { + this.data.pushData(`Hello ${i}`) + } + } + private data: MyDataSource = new MyDataSource(); build() { @@ -208,15 +214,17 @@ struct MyComponent { LazyForEach(this.data, (item: string) => { ListItem() { Row() { - Image(item).width('30%').height(50) - Text(item).fontSize(20).margin({ left: 10 }) + Text(item).fontSize(50) + .onAppear(() => { + console.info("appear:" + item) + }) }.margin({ left: 10, right: 10 }) } .onClick(() => { - this.data.pushData('/path/image' + this.data.totalCount()); + this.data.pushData(`Hello ${this.data.totalCount()}`); }) }, item => item) - } + }.cachedCount(5) } } ``` diff --git a/en/application-dev/quick-start/arkts-style.md b/en/application-dev/quick-start/arkts-style.md index a380964f5893e963e6ce3c62c64d1255f37a8042..2d6cfe90ca118435e7a336027312fb4340147d17 100644 --- a/en/application-dev/quick-start/arkts-style.md +++ b/en/application-dev/quick-start/arkts-style.md @@ -45,12 +45,12 @@ If the style of each component needs to be set separately, this will result in a ```ts @Component struct FancyUse { - @State heightVlaue: number = 100 + @State heightValue: number = 100 @Styles fancy() { - .height(this.heightVlaue) + .height(this.heightValue) .backgroundColor(Color.Yellow) .onClick(() => { - this.heightVlaue = 200 + this.heightValue = 200 }) } } @@ -77,14 +77,14 @@ The following example demonstrates the usage of \@Styles inside and outside a co @Entry @Component struct FancyUse { - @State heightVlaue: number = 100 + @State heightValue: number = 100 // Define a \@Styles decorated method inside a component declaration. @Styles fancy() { .width(200) - .height(this.heightVlaue) + .height(this.heightValue) .backgroundColor(Color.Yellow) .onClick(() => { - this.heightVlaue = 200 + this.heightValue = 200 }) } diff --git a/en/application-dev/quick-start/arkts-watch.md b/en/application-dev/quick-start/arkts-watch.md index 08ae0631beda39cd2d511fd05f4d800952c26de1..f1bd84ccd6d0c067525213c0e09169fb100be2a4 100644 --- a/en/application-dev/quick-start/arkts-watch.md +++ b/en/application-dev/quick-start/arkts-watch.md @@ -52,6 +52,51 @@ An application can request to be notified whenever the value of the \@Watch deco ## Application Scenarios +### \@Watch and Custom Component Update + +This example is used to clarify the processing steps of custom component updates and \@Watch. **count** is decorated by \@State in **CountModifier** and \@Prop in **TotalView**. + + +```ts +@Component +struct TotalView { + @Prop @Watch('onCountUpdated') count: number; + @State total: number = 0; + // @Watch cb + onCountUpdated(propName: string): void { + this.total += this.count; + } + + build() { + Text(`Total: ${this.total}`) + } +} + +@Entry +@Component +struct CountModifier { + @State count: number = 0; + + build() { + Column() { + Button('add to basket') + .onClick(() => { + this.count++ + }) + TotalView({ count: this.count }) + } + } +} +``` + +Processing steps: + +1. The click event **Button.onClick** of the **CountModifier** custom component increases the value of **count**. + +2. In response to the change of the @State decorated variable **count**, \@Prop in the child component **TotalView** is updated, and its **\@Watch('onCountUpdated')** callback is triggered, which updates the **total** variable in **TotalView**. + +3. The **Text** component in the child component **TotalView** is re-rendered. + ### Combination of \@Watch and \@Link @@ -124,52 +169,6 @@ The processing procedure is as follows: 2. The value of the \@Link decorated variable **BasketViewer shopBasket** changes. -3. The state management framework calls the \@Watch callback **BasketViewer onBasketUpdated** to update the value of **BaketViewer TotalPurchase**. +3. The state management framework calls the \@Watch callback **BasketViewer onBasketUpdated** to update the value of **BasketViewer TotalPurchase**. 4. Because \@Link decorated shopBasket changes (a new item is added), the ForEach component executes the item Builder to render and build the new item. Because the @State decorated totalPurchase variables changes, the **Text** component is also re-rendered. Re-rendering happens asynchronously. - - -### \@Watch and Custom Component Update - -This example is used to clarify the processing steps of custom component updates and \@Watch. **count** is decorated by \@State in **CountModifier** and \@Prop in **TotalView**. - - -```ts -@Component -struct TotalView { - @Prop @Watch('onCountUpdated') count: number; - @State total: number = 0; - // @Watch cb - onCountUpdated(propName: string): void { - this.total += this.count; - } - - build() { - Text(`Total: ${this.total}`) - } -} - -@Entry -@Component -struct CountModifier { - @State count: number = 0; - - build() { - Column() { - Button('add to basket') - .onClick(() => { - this.count++ - }) - TotalView({ count: this.count }) - } - } -} -``` - -Processing steps: - -1. The click event **Button.onClick** of the **CountModifier** custom component increases the value of **count**. - -2. In response to the change of the @State decorated variable **count**, \@Prop in the child component **TotalView** is updated, and its **\@Watch('onCountUpdated')** callback is triggered, which updates the **total** variable in **TotalView**. - -3. The **Text** component in the child component **TotalView** is re-rendered. diff --git a/en/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md b/en/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md index 686f31abb33cb3f08bc4660198e1590325622dbf..ca0ea20f21c7f6f9e791d968c5d9089c6e0a8085 100644 --- a/en/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md +++ b/en/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md @@ -11,6 +11,7 @@ HUAWEI DevEco Studio For OpenHarmony (DevEco Studio for short) is a one-stop int - **Multi-device bidirectional real-time preview**: Bidirectional preview, real-time preview, live preview, component preview, and multi-device preview of UI code to quickly view how your code runs on devices. For details, see [Previewing Your App/Service](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-previewing-app-service-0000001218760596). - **High-performance build system**: Hvigor, a compilation and building tool to compile and package applications/services in one-click mode, better supporting ArkTS/JS development. - **One-stop information acquisition**: A one-stop information acquisition platform that takes into account the developer journey of learning, development, and help seeking, in order to facilitate developer activities. -- **Efficient code debugging**: Various debugging capabilities such as TS, JS, and C/C++ code breakpoint setting, single-step execution, and variable viewing, improving the efficiency of analyzing application/service issues. +- **Efficient code debugging**: Various debugging capabilities such as ArkTS, JS, and C/C++ code breakpoint setting, single-step execution, and variable viewing, improving the efficiency of analyzing application/service issues. +- **Scenario-based profiling**: A performance profiling tool that provides scenario-based profiling features, such as real-time data monitoring, measurement of the time it takes to execute functions, and memory analysis, to help you quickly locate faulty code. For more information, see [DevEco Studio User Guide (OpenHarmony)](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-deveco-studio-overview-0000001263280421). diff --git a/en/application-dev/quick-start/introduction-to-arkts.md b/en/application-dev/quick-start/introduction-to-arkts.md index b3bbd6671524a508d881c3d5245d0a1958d59c63..4ed847999052fd43951fcbc1452bed456ad78ea3 100644 --- a/en/application-dev/quick-start/introduction-to-arkts.md +++ b/en/application-dev/quick-start/introduction-to-arkts.md @@ -1,48 +1,21 @@ # Introduction -Welcome to the tutorial for ArkTS, a TypeScript-based programming language -designed specifically to build high-performance mobile applications! +Welcome to the tutorial for ArkTS, a TypeScript-based programming language designed specifically to build high-performance mobile applications! -ArkTS is optimized to provide better performance and efficiency, while still -maintaining the familiar syntax of TypeScript. +ArkTS is optimized to provide better performance and efficiency, while still maintaining the familiar syntax of TypeScript. -As mobile devices continue to become more prevalent in our daily lives, -there is a growing need for programming languages optimized for the -mobile environment. Many current programming languages were not designed with -mobile devices in mind, resulting in slow and inefficient applications that -drain battery life. ArkTS has been specifically designed to address such concerns -by prioritizing higher execution efficiency. +As mobile devices continue to become more prevalent in our daily lives, there is a growing need for programming languages optimized for the mobile environment. Many current programming languages were not designed with mobile devices in mind, resulting in slow and inefficient applications that drain battery life. ArkTS has been specifically designed to address such concerns by prioritizing higher execution efficiency. -ArkTS is based on the popular programming language TypeScript that extends -JavaScript by adding type definitions. TypeScript is well-loved by many developers as it -provides a more structured approach to coding in JavaScript. ArkTS aims to -keep the look and feel of TypeScript to enable a seamless transition for the existing -TypeScript developers, and to let mobile developers learn ArkTS quickly. +ArkTS is based on the popular programming language TypeScript that extends JavaScript by adding type definitions. TypeScript is well-loved by many developers as it provides a more structured approach to coding in JavaScript. ArkTS aims to keep the look and feel of TypeScript to enable a seamless transition for the existing TypeScript developers, and to let mobile developers learn ArkTS quickly. One of the key features of ArkTS is its focus on low runtime overhead. -ArkTS imposes stricter limitations on the TypeScript’s dynamically typed features, -reducing runtime overhead and allowing faster execution. By eliminating -the dynamically typed features from the language, ArkTS code can be compiled -ahead-of-time more efficiently, resulting in faster application startup and -lower power consumption. - -Interoperability with JavaScript was a critical consideration in the ArkTS language -design. Many mobile app developers already have TypeScript and JavaScript code and libraries -they would want to reuse. ArkTS has been designed for seamless JavaScript -interoperability, making it easy for the developers to integrate the JavaScript code -into their applications and vice versa. This will allow the developers to -use their existing codebases and libraries to leverage the power of our -new language. - -To ensure best experience for UI app development for OpenHarmony ecosystem, -ArkTS provides support for ArkUI, including its declarative syntax and other -features. Since this feature is outside the scope of the “stock” TypeScript, a verbose -ArkUI example is provided in a separate chapter. - -This tutorial will guide the developers through the core features, syntax, -and best practices of ArkTS. After reading this tutorial through the end, -the developers will be able to build performant and efficient mobile -applications in ArkTS. +ArkTS imposes stricter limitations on the TypeScript's dynamically typed features, reducing runtime overhead and allowing faster execution. By eliminating the dynamically typed features from the language, ArkTS code can be compiled ahead-of-time more efficiently, resulting in faster application startup and lower power consumption. + +Interoperability with JavaScript was a critical consideration in the ArkTS language design. Many mobile app developers already have TypeScript and JavaScript code and libraries they would want to reuse. ArkTS has been designed for seamless JavaScript interoperability, making it easy for the developers to integrate the JavaScript code into their applications and vice versa. This will allow the developers to use their existing codebases and libraries to leverage the power of our new language. + +To ensure best experience for UI app development for OpenHarmony ecosystem, ArkTS provides support for ArkUI, including its declarative syntax and other features. Since this feature is outside the scope of the "stock" TypeScript, a verbose ArkUI example is provided in a separate chapter. + +This tutorial will guide you through the core features, syntax, and best practices of ArkTS. After reading this tutorial through the end, you will be able to build performant and efficient mobile applications in ArkTS. # The Basics @@ -50,15 +23,14 @@ applications in ArkTS. Declarations in ArkTS introduce: -- variables, -- constants, -- functions, and -- types. +- Variables +- Constants +- Functions +- Types ### Variable Declaration -A declaration starting with the keyword `let` introduces a variable which -can have different values during program execution. +A declaration starting with the keyword `let` introduces a variable which can have different values during program execution. ```typescript let hi: string = "hello" @@ -67,8 +39,7 @@ hi = "hello, world" ### Constant Declaration -A declaration starting with the keyword `const` introduces a read-only -constant that can be assigned only once. +A declaration starting with the keyword `const` introduces a read-only constant that can be assigned only once. ```typescript const hello: string = "hello" @@ -78,16 +49,13 @@ A compile-time error occurs if a new value is assigned to a constant. ### Automatic Type Inference -As ArkTS is a statically typed language, the types of all entities, like -variables and constants, have to be known at compile time. +As ArkTS is a statically typed language, the types of all entities, like variables and constants, have to be known at compile time. -However, developers do not need to explicitly specify the type of a declared -entity if a variable or a constant declaration contains an initial value. -All cases that allow the type to be inferred automatically are specified in -the ArkTS Specification. +However, developers do not need to explicitly specify the type of a declared entity if a variable or a constant declaration contains an initial value. -Both variable declarations are valid, and both variables are of the `string` -type: +All cases that allow the type to be inferred automatically are specified in the ArkTS Specification. + +Both variable declarations are valid, and both variables are of the `string` type: ```typescript let hi1: string = "hello" @@ -96,32 +64,30 @@ let hi2 = "hello, world" ## Types -`Class`, `interface`, `function`, `enum`, `union` types, and type -`aliases` are described in the corresponding sections. +`Class`, `interface`, `function`, `enum`, `union` types, and type `aliases` are described in the corresponding sections. ### Numeric Types -ArkTS has `number` and `Number` numeric types. Any integer and -floating-point values can be assigned to a variable of these types. +ArkTS has `number` and `Number` numeric types. Any integer and floating-point values can be assigned to a variable of these types. Numeric literals include integer literals and floating-point literals with the decimal base. Integer literals include the following: -* decimal integers that consist of a sequence of digits. For example: `0`, `117`, `-345`; -* hexadecimal integers that start with 0x (or 0X), and can contain digits (0-9) and letters a-f or A-F. For example: `0x1123`, `0x00111`, `-0xF1A7`; -* octal integers that start with 0o (or 0O) and can only contain digits (0-7). For example: `0o777`; -* binary integers that start with 0b (or 0B), and can only contain the digits 0 and 1. For example: `0b11`, `0b0011`, `-0b11`. +* Decimal integers that consist of a sequence of digits. For example: `0`, `117`, `-345`. +* Hexadecimal integers that start with 0x (or 0X), and can contain digits (0-9) and letters a-f or A-F. For example: `0x1123`, `0x00111`, `-0xF1A7`. +* Octal integers that start with 0o (or 0O) and can only contain digits (0-7). For example: `0o777`. +* Binary integers that start with 0b (or 0B), and can only contain the digits 0 and 1. For example: `0b11`, `0b0011`, `-0b11`. A floating-point literal includes the following: -* decimal integer, optionally signed (i.e., prefixed with “+” or “-“); -* decimal point (“.”); -* fractional part (represented by a string of decimal digits); -* exponent part that starts with “e” or “E”, followed by an optionally signed (i.e., prefixed with “+” or “-”) integer. +* Decimal integer, optionally signed (i.e., prefixed with "+" or "-"); +* Decimal point ("."). +* Fractional part (represented by a string of decimal digits). +* Exponent part that starts with "e" or "E", followed by an optionally signed (i.e., prefixed with "+" or "-") integer. -For example: +Example: ```typescript let n1 = 3.14 @@ -139,8 +105,7 @@ function factorial(n: number) : number { ### `Boolean` -The `boolean` type represents logical values that are either `true` -or `false`. +The `boolean` type represents logical values that are either `true` or `false`. Usually variables of this type are used in conditional statements: @@ -156,12 +121,9 @@ if (isDone) { ### `String` -A `string` is a sequence of characters; some characters can be set by using -escape sequences. +A `string` is a sequence of characters; some characters can be set by using escape sequences. -A `string` literal consists of zero or more characters enclosed in single -(’) or double quotes (“). The special form of string literals are template -literals enclosed in backtick quotes (\`). +A `string` literal consists of zero or more characters enclosed in single (') or double quotes ("). The special form of string literals are template literals enclosed in backtick quotes (\`). ```typescript let s1 = "Hello, world!\n" @@ -185,18 +147,12 @@ let instance: Class ### `Object` Type -An `Object` class type is a base type for all reference types. Any value, -including values of primitive types (they will be automatically boxed), can -be directly assigned to variables of the type `Object`. +An `Object` class type is a base type for all reference types. Any value, including values of primitive types (they will be automatically boxed), can be directly assigned to variables of the type `Object`. ### `Array` Type -An `array` is an object comprised of elements of data types assignable to -the element type specified in the array declaration. -A value of an `array` is set by using *array composite literal*, that is a -list of zero or more expressions enclosed in square brackets ([]). Each -expression represents an element of the `array`. The length of the `array` -is set by the number of expressions. Index of the first array element is 0. +An `array` is an object comprised of elements of data types assignable to the element type specified in the array declaration. +A value of an `array` is set by using *array composite literal*, that is a list of zero or more expressions enclosed in square brackets ([]). Each expression represents an element of the `array`. The length of the `array` is set by the number of expressions. Index of the first array element is 0. The following example creates the `array` with three elements: @@ -206,18 +162,15 @@ let names: string[] = ["Alice", "Bob", "Carol"] ### `Enum` Type -An `enum` type is a value type with a defined set of named values called -enum constants. -In order to be used, an `enum` constant must be prefixed with an enum -`type` name. +An `enum` type is a value type with a defined set of named values called enum constants. +In order to be used, an `enum` constant must be prefixed with an enum `type` name. ```typescript enum Color { Red, Green, Blue } let c: Color = Color.Red ``` -A constant expression can be used to explicitly set the value of an `enum` -constant. +A constant expression can be used to explicitly set the value of an `enum` constant. ```typescript enum Color { White = 0xFF, Grey = 0x7F, Black = 0x00 } @@ -226,9 +179,7 @@ let c: Color = Color.Black ### `Union` Type -A `union` type is a reference type which is created as a combination -of other types. Values of union types can be valid values of all types -a union was created from. +A `union` type is a reference type which is created as a combination of other types. Values of union types can be valid values of all types a union was created from. ```typescript class Cat { @@ -251,7 +202,7 @@ animal = 42 There are different mechanisms to get a value of a particular type from a union. -For example +Example: ```typescript class Cat { sleep () {}; meow () {} } @@ -273,8 +224,7 @@ animal.sleep () // Any animal can sleep ### Type `Aliases` -Type `aliases` provide names for anonymous types (array, function, object -literal or union types) or alternative names for existing types. +Type `aliases` provides names for anonymous types (array, function, object literal or union types) or alternative names for existing types. ```typescript type Matrix = number[][] @@ -287,24 +237,22 @@ type NullableObject = Object | null ### Assignment Operators -Simple assignment operator ‘=’ is used as in “x = y”. +Simple assignment operator '=' is used as in "x = y". -Compound assignment operators combine an assignment with an operator, where -`x op = y` equals `x = x op y`. +Compound assignment operators combine an assignment with an operator, where `x op = y` equals `x = x op y`. -Compound assignment operators are as follows: `+=`, `-=`, `*=`, `/=`, -`%=`, `<<=`, `>>=`, `>>>=`, `&=`, `|=`, `^=`. +Compound assignment operators are as follows: `+=`, `-=`, `*=`, `/=`, `%=`, `<<=`, `>>=`, `>>>=`, `&=`, `|=`, `^=`. ### Comparison Operators -| Operator | Description | -|------------|------------------------------------------------------------------------| -| `==` | returns true if both operands are equal | -| `!=` | returns true if both operands are not equal | -| `>` | returns true if the left operand is greater than the right | -| `>=` | returns true if the left operand is greater than or equal to the right | -| `<` | returns true if the left operand is less then the right | -| `<=` | returns true if the left operand is less than or equal to the right | +| Operator | Description | +| -------- | ------------------------------------------------------------ | +| `==` | Returns true if both operands are equal. | +| `!=` | Returns true if both operands are not equal. | +| `>` | Returns true if the left operand is greater than the right. | +| `>=` | Returns true if the left operand is greater than or equal to the right. | +| `<` | Returns true if the left operand is less than the right. | +| `<=` | Returns true if the left operand is less than or equal to the right. | ### Arithmetic Operators Unary operators are `-`, `+`, `--` and `++`. @@ -333,15 +281,15 @@ Binary operators are as follows: | Operator | Description | |------------|---------------| -| `a && b` | logical AND | -| `a \|\| b` | logical OR | -| `! a` | logical NOT | +| `a && b` | Logical AND | +| `a \|\| b` | Logical OR | +| `! a` | Logical NOT | ## Control Flow ### `If` Statements -An `if` statement is used to execute a sequence of statements when a logical -condition is `true`, or another set of statements (if provided) otherwise. +An `if` statement is used to execute a sequence of statements when a logical condition is `true`, or another set of statements (if provided) otherwise. + The `else` part can also contain more `if` statements. An `if` statement looks as follows: @@ -356,9 +304,7 @@ if (condition1) { } ``` -All conditional expressions must be of the type `boolean` or other types -(`string`, `number`, etc.). For types other than `boolean`, implicit -conversion rules apply: +All conditional expressions must be of the type `boolean` or other types (`string`, `number`, etc.). For types other than `boolean`, implicit conversion rules apply: ```typescript let s1 = "Hello" @@ -374,8 +320,7 @@ if (s2.length != 0) { ### `Switch` Statements -A `switch` statement is used to execute a sequence of statements that match -the value of a switch expression. +A `switch` statement is used to execute a sequence of statements that match the value of a switch expression. A `switch` statement looks as follows: @@ -397,27 +342,21 @@ default: } ``` -The `switch` expression type must be of `number`, `enum` or `string` -types. +The `switch` expression type must be of `number`, `enum` or `string` types. Each label must be either a constant expression or the name of an enum constant. -If the value of a `switch` expression equals the value of some label, then -the corresponding statements are executed. +If the value of a `switch` expression equals the value of some label, then the corresponding statements are executed. -If there is no match, and the `switch` has the default clause, then the -default statements are executed. +If there is no match, and the `switch` has the default clause, then the default statements are executed. -An optional `break` statement allows to break out of the `switch` and -continue executing the statement that follows the `switch`. +An optional `break` statement allows you to break out of the `switch` and continue executing the statement that follows the `switch`. -If there is no `break`, then the next statements in the `switch` is -executed. +If there is no `break`, then the next statements in the `switch` are executed. ### Conditional Expressions -The conditional expression `? :` uses the `boolean` value of the first -expression to decide which of two other expressions to evaluate. +The conditional expression `? :` uses the `boolean` value of the first expression to decide which of two other expressions to evaluate. A conditional expression looks as follows: @@ -425,9 +364,7 @@ A conditional expression looks as follows: condition ? expression1 : expression2 ``` -The condition must be a logical expression. If that logical expression is -`true`, then the first expression is used as the result of the ternary -expression; otherwise, the second expression is used. +The condition must be a logical expression. If that logical expression is `true`, then the first expression is used as the result of the ternary expression; otherwise, the second expression is used. Example: @@ -438,8 +375,7 @@ let message = isValid ? 'Valid' : 'Failed' ### `For` Statements -A `for` statement is executed repeatedly until the specified loop exit -condition is `false`. +A `for` statement is executed repeatedly until the specified loop exit condition is `false`. A `for` statement looks as follows: @@ -451,15 +387,10 @@ for ([init]; [condition]; [update]) { When a `for` statement is executed, the following process takes place: -1. An `init` expression is executed, if any. This expression usually - initializes one or more loop counters. -2. The condition is evaluated. If the value of condition is `true`, or - if the conditional expression is omitted, then the statements in the - `for` body are to be executed. If the value of condition is `false`, - then the `for` loop terminates. +1. An `init` expression is executed, if any. This expression usually initializes one or more loop counters. +2. The condition is evaluated. If the value of condition is `true`, or if the conditional expression is omitted, then the statements in the `for` body are to be executed. If the value of condition is `false`, then the `for` loop terminates. 3. The statements of the `for` body are executed. -4. If there is an `update` expression, then the `update` expression - is executed. +4. If there is an `update` expression, then the `update` expression is executed. 5. Go back to step 2. Example: @@ -491,8 +422,7 @@ for (let ch of "a string object") { /* process ch */ } ### `While` Statements -A `while` statement has its body statements executed as long as the -specified condition evaluates to `true`. +A `while` statement has its body statements executed as long as the specified condition evaluates to `true`. A `while` statement looks as follows: @@ -517,8 +447,7 @@ while (n < 3) { ### `Do-while` Statements -`do-while` statements are executed repetitively until a specified -condition evaluates to false. +`do-while` statements are executed repetitively until a specified condition evaluates to false. A `do-while` statement looks as follows: @@ -555,8 +484,7 @@ while (true) { } ``` -A `break` statement with a label identifier transfers control out of the -enclosing statement to the one which has the same label identifier. +A `break` statement with a label identifier transfers control out of the enclosing statement to the one which has the same label identifier. Example: @@ -573,8 +501,7 @@ label: while (true) { ### `Continue` Statements -A `continue` statement stops the execution of the current loop iteration -and passes control to the next iteration. +A `continue` statement stops the execution of the current loop iteration and passes control to the next iteration. Example: @@ -606,8 +533,7 @@ try { } ``` -The example below shows the `throw` and `try` statements used to handle -the zero division case: +The example below shows the `throw` and `try` statements used to handle the zero division case: ```typescript class ZeroDivisor extends Error {} @@ -655,8 +581,7 @@ function processData(s: string) { ## Function Declarations -A function declaration introduces a named function, specifying its name, -parameters, return type and body. +A function declaration introduces a named function, specifying its name, parameters, return type and body. Below is a simple function with two string parameters and string return type: @@ -668,8 +593,7 @@ function add(x: string, y: string): string { ``` For every parameter its type annotation must be specified. -An optional parameter allows to omit the corresponding argument when -calling a function. The last parameter of a function can be a rest parameter. +An optional parameter allows you to omit the corresponding argument when calling a function. The last parameter of a function can be a rest parameter. ## Optional Parameters @@ -686,8 +610,7 @@ function hello(name?: string) { ``` Another form contains an expression that specifies a default value. -If the corresponding argument to such parameter is omitted in a function call, -then this parameter’s value is default. +If the corresponding argument to such parameter is omitted in a function call, then this parameter's value is default. ```typescript function multiply(n: number, coeff: number = 2): number { @@ -699,8 +622,7 @@ multiply(2, 3) // returns 2*3 ## The Rest Parameter -The last parameter of a function can be a rest parameter. -It allows functions or methods to take unlimited number of arguments. +The last parameter of a function can be a rest parameter. It allows functions or methods to take unlimited number of arguments. ```typescript function sum(...numbers: number[]): number { @@ -716,8 +638,7 @@ sum(1, 2, 3) // returns 6 ## Return Types -If function return type can be inferred from its body content, then it can -be omitted from the function declaration. +If function return type can be inferred from its body content, then it can be omitted from the function declaration. ```typescript // Explicit return type @@ -727,9 +648,7 @@ function foo(): string { return "foo" } function goo() { return "goo" } ``` -The return type of a function that does not need to return a value can be -explicitly specified as `void` or omitted altogether. No return statement -is needed for such functions. +The return type of a function that does not need to return a value can be explicitly specified as `void` or omitted altogether. No return statement is needed for such functions. Both notations below are valid: @@ -740,16 +659,13 @@ function hi2(): void { console.log("hi") } ## Function Scope -Variables and other entities defined in a function are local to the function -and cannot be accessed from the outside. +Variables and other entities defined in a function are local to the function and cannot be accessed from the outside. -If the name of a variable defined in the function is equal to the name of an -entity in the outer scope, then the local definition shadows the outer entity. +If the name of a variable defined in the function is equal to the name of an entity in the outer scope, then the local definition shadows the outer entity. ## Function Calls -Calling a function actually leads to the execution of its body, while -the arguments of the call are assigned to the function parameters. +Calling a function actually leads to the execution of its body, while the arguments of the call are assigned to the function parameters. If the function is defined as follows: @@ -791,11 +707,9 @@ let sum = (x: number, y: number): number => { } ``` -An arrow function return type can be omitted; in such case, it is inferred -from the function body. +An arrow function return type can be omitted; in such case, it is inferred from the function body. -An expression can be specified as an arrow function to make the notation -shorter, i.e., the following two notations are equivalent: +An expression can be specified as an arrow function to make the notation shorter, i.e., the following two notations are equivalent: ```typescript let sum1 = (x: number, y: number) => { return x + y } @@ -804,9 +718,7 @@ let sum2 = (x: number, y: number) => x + y ## Closure -An arrow function is usually defined inside another function. As an inner -function, it can access all variables and functions defined in the outer -functions. +An arrow function is usually defined inside another function. As an inner function, it can access all variables and functions defined in the outer functions. To capture the context, an inner function forms a closure of its environment. The closure allows accessing such an inner function outside its own environment. @@ -826,15 +738,12 @@ In the sample above, the arrow function closure captures the `count` variable. ## Function Overload Signatures -A function can be specified to be called in different ways by writing -overload signatures. To do so, several functions’ headers that have the -same name but different signatures are written and immediately followed -by the single implementation function. +A function can be specified to be called in different ways by writing overload signatures. To do so, several functions' headers that have the same name but different signatures are written and immediately followed by the single implementation function. ```typescript function foo(): void; /* 1st signature */ function foo(x: string): void; /* 2nd signature */ -function foo(x?: string): void { /* implementation signature */ +function foo(x?: string): void { /* Implementation signature */ console.log(x) } @@ -846,11 +755,9 @@ An error occurs if two overload signatures have identical parameter lists. # Classes -A class declaration introduces a new type and defines its fields, methods -and constructors. +A class declaration introduces a new type and defines its fields, methods and constructors. -In the following example, class `Person` is defined, which has fields -‘name’ and ‘surname’, constructor, and a method `fullName`: +In the following example, class `Person` is defined, which has fields **name** and **surname**, constructor, and a method `fullName`: ```typescript class Person { @@ -866,8 +773,7 @@ class Person { } ``` -After the class is defined, its instances can be created by using -the keyword `new`: +After the class is defined, its instances can be created by using the keyword `new`: ```typescript let p = new Person("John", "Smith") @@ -887,12 +793,12 @@ let p: Point = {x: 42, y: 42} ## Fields A field is a variable of some type that is declared directly in a class. + Classes may have instance fields, static fields or both. ### Instance Fields -Instance fields exist on every instance of a class. Each instance has its own -set of instance fields. +Instance fields exist on every instance of a class. Each instance has its own set of instance fields. ```typescript class Person { @@ -917,9 +823,7 @@ this.name ### Static Fields -The keyword `static` is used to declare a field as static. Static fields -belong to the class itself, and all instances of the class share one static -field. +The keyword `static` is used to declare a field as static. Static fields belong to the class itself, and all instances of the class share one static field. The class name is used to access a static field: @@ -938,11 +842,9 @@ console.log(Person.numberOfPersons) ### Getters and Setters -Setters and getters can be used to provide controlled access to object -properties. +Setters and getters can be used to provide controlled access to object properties. -In the following example, a setter is used to forbid setting invalid -values of the ‘age’ property: +In the following example, a setter is used to forbid setting invalid values of the 'age' property: ```typescript class Person { @@ -968,16 +870,13 @@ A class can define a getter, a setter or both. A method is a function that belongs to a class. A class can define instance methods, static methods or both. -A static method belongs to the class itself, and can have access to static -fields only. -A `while` instance method has access to both static (class) fields and -instance fields including private ones of its class. +A static method belongs to the class itself, and can have access to static fields only. +A `while` instance method has access to both static (class) fields and instance fields including private ones of its class. ### Instance Methods The example below illustrates how instanced methods work. -The `calculateArea` method calculates the area of a rectangle by -multiplying the height by the width: +The `calculateArea` method calculates the area of a rectangle by multiplying the height by the width: ```typescript class Rectangle { @@ -1001,8 +900,7 @@ console.log(square.calculateArea()) // output: 100 ### Static Methods -The keyword `static` is used to declare a method as static. Static methods -belong to the class itself and have access to static fields only. +The keyword `static` is used to declare a method as static. Static methods belong to the class itself and have access to static fields only. A static method defines a common behavior of the class as a whole. All instances have access to static methods. @@ -1019,8 +917,7 @@ console.log(Cl.staticMethod()) ### Inheritance -A class can extend another class (called base class) and implement several -interfaces by using the following syntax: +A class can extend another class (called base class) and implement several interfaces by using the following syntax: ```typescript class [extends BaseClassName] [implements listOfInterfaces] { @@ -1028,12 +925,9 @@ class [extends BaseClassName] [implements listOfInterfaces] { } ``` -The extended class inherits fields and methods from the base class, but -not constructors, and can add its own fields and methods as well as override -methods defined by the base class. +The extended class inherits fields and methods from the base class, but not constructors, and can add its own fields and methods as well as override methods defined by the base class. -The base class is also called ‘parent class’ or ‘superclass’. -The extended class also called ‘derived class’ or ‘subclass’. +The base class is also called 'parent class' or 'superclass'. The extended class also called 'derived class' or 'subclass'. Example: @@ -1053,9 +947,7 @@ class Employee extends Person { } ``` -A class containing the `implements` clause must implement all methods -defined in all listed interfaces, except the methods defined with default -implementation. +A class containing the `implements` clause must implement all methods defined in all listed interfaces, except the methods defined with default implementation. ```typescript interface DateInterface { @@ -1071,11 +963,9 @@ class MyDate implements DateInterface { ### Access to Super -The keyword `super` can be used to access instance fields, instance methods -and constructors from the super class. +The keyword `super` can be used to access instance fields, instance methods and constructors from the super class. -It is often used to extend basic functionality of subclass with the required -behavior taken from the super class: +It is often used to extend basic functionality of subclass with the required behavior taken from the super class: ```typescript class Rectangle { @@ -1109,10 +999,8 @@ class FilledRectangle extends Rectangle { ### Override Methods A subclass can override implementation of a method defined in its superclass. -An overridden method can be marked with the keyword `override` to improve -readability. -An overridden method must have the same types of parameters, and same or -derived return type as the original method. +An overridden method can be marked with the keyword `override` to improve readability. +An overridden method must have the same types of parameters, and same or derived return type as the original method. ```typescript class Rectangle { @@ -1132,10 +1020,7 @@ class Square extends Rectangle { ### Method Overload Signatures -A method can be specified to be called in different ways by writing overload -signatures. To do so, several method headers that have the same name but -different signatures are written and immediately followed by the single -implementation method. +A method can be specified to be called in different ways by writing overload signatures. To do so, several method headers that have the same name but different signatures are written and immediately followed by the single implementation method. ```typescript class C { @@ -1150,13 +1035,11 @@ c.foo() // ok, 1st signature is used c.foo("aa") // ok, 2nd signature is used ``` -An error occurs if two overload signatures have the same name and identical -parameter lists. +An error occurs if two overload signatures have the same name and identical parameter lists. ## Constructors -A class declaration may contain a constructor that is used to initialize -object state. +A class declaration may contain a constructor that is used to initialize object state. A constructor is defined as follows: @@ -1166,8 +1049,7 @@ constructor ([parameters]) { } ``` -If no constructor is defined, then a default constructor with an empty -parameter list is created automatically, for example: +If no constructor is defined, then a default constructor with an empty parameter list is created automatically, for example: ```typescript class Point { @@ -1177,13 +1059,11 @@ class Point { let p = new Point() ``` -In this case the default constructor fills the instance fields with -default values for the field types. +In this case the default constructor fills the instance fields with default values for the field types. ### Constructors in Derived Class -The first statement of a constructor body can use the keyword `super` -to explicitly call a constructor of the direct superclass. +The first statement of a constructor body can use the keyword `super` to explicitly call a constructor of the direct superclass. ```typescript class Rectangle { @@ -1198,22 +1078,17 @@ class Square extends Rectangle { } ``` -If a constructor body does not begin with such an explicit call of a -superclass constructor, then the constructor body implicitly begins -with a superclass constructor call `super()`. +If a constructor body does not begin with such an explicit call of a superclass constructor, then the constructor body implicitly begins with a superclass constructor call `super()`. ### Constructor Overload Signatures -A constructor can be specified to be called in different ways by writing -overload signatures. To do so, several constructor headers that have the -same name but different signatures are written and immediately followed -by the single implementation constructor. +A constructor can be specified to be called in different ways by writing overload signatures. To do so, several constructor headers that have the same name but different signatures are written and immediately followed by the single implementation constructor. ```typescript class C { constructor() /* 1st signature */ constructor(x: string) /* 2nd signature */ - constructor(x?: string) { /* implementation signtaure */ + constructor(x?: string) { /* Implementation signature */ console.log(x) } } @@ -1221,8 +1096,7 @@ let c1 = new C() // ok, 1st signature is used let c2 = new C("abc") // ok, 2nd signature is used ``` -An error occurs if two overload signatures have the same name and -identical parameter lists. +An error occurs if two overload signatures have the same name and identical parameter lists. ## Visibility Modifiers @@ -1236,18 +1110,16 @@ There are several visibility modifiers: - `internal`. The default visibility is `public`. -The modifier `internal` allows to limit visibility within -the current package. +The modifier `internal` allows you to limit visibility within the current package. ### Public Visibility -The `public` members (fields, methods, constructors) of a class are -visible in any part of the program, where their class is visible. +The `public` members (fields, methods, constructors) of a class are visible in any part of the program, where their class is visible. ### Private Visibility -A `private` member cannot be accessed outside the class it is declared in, -for example: +A `private` member cannot be accessed outside the class it is declared in. +Example: ```typescript class C { @@ -1264,8 +1136,8 @@ c.y = "b" // compile-time error: 'y' is not visible ### Protected Visibility -The modifier `protected` acts much like the modifier `private`, but -the `protected` members are also accessible in derived classes, for example: +The modifier `protected` acts much like the modifier `private`, but the `protected` members are also accessible in derived classes. +Example: ```typescript class Base { @@ -1282,12 +1154,9 @@ class Derived extends Base { ## Object Literals -An object literal is an expression that can be used to create a class instance -and provide some initial values. It can be used instead of the expression -`new` as it is more convenient in some cases. +An object literal is an expression that can be used to create a class instance and provide some initial values. It can be used instead of the expression `new` as it is more convenient in some cases. -A class composite is written as a comma-separated list of name-value pairs -enclosed in ‘{’ and ‘}’. +A class composite is written as a comma-separated list of name-value pairs enclosed in '{' and '}'. ```typescript class C { @@ -1298,9 +1167,7 @@ class C { let c: C = {n: 42, s: "foo"} ``` -Due to the static typing of the ArkTS, object literals can be used in a -context where the class or interface type of the object literal can be -inferred as in the example above. Other valid cases are illustrated below: +Due to the static typing of the ArkTS, object literals can be used in a context where the class or interface type of the object literal can be inferred as in the example above. Other valid cases are illustrated below: ```typescript class C { @@ -1332,8 +1199,7 @@ let cc: C[] = [{n: 1, s: "a"}, {n: 2, s: "b"}] ### Object Literals of Record Type -The generic Record type is used to map the properties of a type -(Key type) to another type (Value type). +The generic Record type is used to map the properties of a type (Key type) to another type (Value type). A special form of object literal is used to initialize the value of such type: @@ -1361,11 +1227,9 @@ let map: Record = { # Interfaces -An interface declaration introduces a new type. Interfaces are a common way -of defining contracts between various part of codes. +An interface declaration introduces a new type. Interfaces are a common way of defining contracts between various part of codes. -Interfaces are used to write polymorphic code, which can be applied to any -class instances that implement a particular interface. +Interfaces are used to write polymorphic code, which can be applied to any class instances that implement a particular interface. An interface usually contains properties and method headers. @@ -1406,11 +1270,9 @@ class Rectangle implements Area { ## Interface Properties -An interface property can be in a form of field, getter, setter, or both -getter and setter. +An interface property can be in a form of field, getter, setter, or both getter and setter. -A property field is just a shortcut notation of a getter/setter pair, and -the following notations are equal: +A property field is just a shortcut notation of a getter/setter pair, and the following notations are equal: ```typescript interface Style { @@ -1463,8 +1325,7 @@ interface ExtendedStyle extends Style { } ``` -An extended interface contains all properties and methods of the -interface it extends, and can also add its own properties and methods. +An extended interface contains all properties and methods of the interface it extends, and can also add its own properties and methods. ## Interface Visibility Modifiers @@ -1474,13 +1335,11 @@ Only methods with default implementation can be defined as `private`. # Generic Types and Functions -Generic types and functions allow creating the code capable to work over a -variety of types rather than a single type. +Generic types and functions allow creating the code capable to work over a variety of types rather than a single type. ## Generic Classes and Interfaces -A class and an interface can be defined as generics, adding parameters to the -type definition, like the type parameter `Element` in the following example: +A class and an interface can be defined as generics, adding parameters to the type definition, like the type parameter `Element` in the following example: ```typescript class Stack { @@ -1510,9 +1369,7 @@ s.push(55) // That will be a compile-time error ## Generic Constraints -Type parameters of generic types can be bounded. For example, the `Key` -type parameter in the `HashMap` container must have a hash -method, i.e., it must be hashable. +Type parameters of generic types can be bounded. For example, the `Key` type parameter in the `HashMap` container must have a hash method, that is, it must be hashable. ```typescript interface Hashable { @@ -1526,13 +1383,11 @@ class HasMap { } ``` -In the above example, the `Key` type extends `Hashable`, and all methods -of `Hashable` interface can be called for keys. +In the above example, the `Key` type extends `Hashable`, and all methods of `Hashable` interface can be called for keys. ## Generic Functions -Use a generic function to create a more universal code. Consider a function -that returns the last element of the array: +Use a generic function to create a more universal code. Consider a function that returns the last element of the array: ```typescript function last(x: number[]): number { @@ -1541,8 +1396,7 @@ function last(x: number[]): number { console.log(last([1, 2, 3])) // output: 3 ``` -If the same function needs to be defined for any array, then define it as -a generic with a type parameter: +If the same function needs to be defined for any array, then define it as a generic with a type parameter: ```typescript function last(x: T[]): T { @@ -1566,10 +1420,8 @@ console.log(last([1, 2, 3])) ## Generic Defaults -Type parameters of generic types can have defaults. -It allows using just the generic type name instead of specifying the actual -type arguments. -Example below illustrates this for both classes and functions. +Type parameters of generic types can have defaults. It allows using just the generic type name instead of specifying the actual type arguments. +The example below illustrates this for both classes and functions. ```typescript class SomeType {} @@ -1589,10 +1441,8 @@ foo() # Null Safety -All types in ArkTS by default are non-nullable, so the value of a type -cannot be null. -It is similar to TypeScript behavior in strict null checking mode -(`strictNullChecks`), but the rules are stricter. +All types in ArkTS by default are non-nullable, so the value of a type cannot be null. +It is similar to TypeScript behavior in strict null checking mode (`strictNullChecks`), but the rules are stricter. In the example below, all lines cause a compile-time error: @@ -1615,8 +1465,7 @@ if (x != null) { /* do something */ } A postfix operator `!` can be used to assert that its operand is non-null. -If applied to a null value, the operator throws an error. Otherwise, the -type of the value is changed from `T | null` to `T`: +If applied to a null value, the operator throws an error. Otherwise, the type of the value is changed from `T | null` to `T`: ```typescript let x: number | null = 1 @@ -1627,15 +1476,12 @@ y = x! + 1 // ok ## Null-Coalescing Operator -The null-coalescing binary operator `??` checks whether the evaluation -of the left-hand-side expression is equal to null. -If it is, then the result of the expression is the right-hand-side expression; -otherwise, it is the left-hand-side expression. +The null-coalescing binary operator `??` checks whether the evaluation of the left-hand-side expression is equal to null. +If it is, then the result of the expression is the right-hand-side expression; otherwise, it is the left-hand-side expression. In other words, `a ?? b` equals the ternary operator `a != null ? a : b`. -In the following example, the method `getNick` returns a nickname if it is -set; otherwise, an empty string is returned: +In the following example, the method `getNick` returns a nickname if it is set; otherwise, an empty string is returned: ```typescript class Person { @@ -1649,8 +1495,7 @@ class Person { ## Optional Chaining -Optional chaining operator `?.` allows writing code where the evaluation -stops at an expression that is partially evaluated to `null` or `undefined`. +Optional chaining operator `?.` allows writing code where the evaluation stops at an expression that is partially evaluated to `null` or `undefined`. ```typescript class Person { @@ -1672,14 +1517,11 @@ class Person { } ``` -**Note**: the return type of `getSpouseNick` must be `string | null | undefined`, as -the method can return null or undefined. +**Note**: The return type of `getSpouseNick` must be `string | null | undefined`, as the method can return null or undefined. -An optional chain can be of any length and contain any number of `?.` -operators. +An optional chain can be of any length and contain any number of `?.` operators. -In the following sample, the output is a person’s spouse nickname if that -person has a spouse, and the spouse has a nickname. +In the following sample, the output is a person's spouse nickname if that person has a spouse, and the spouse has a nickname. Otherwise, the output is `undefined`: @@ -1702,19 +1544,15 @@ console.log(p.spouse?.nick) // print: undefined Programs are organized as sets of compilation units or modules. -Each module creates its own scope, i.e., any declarations (variables, -functions, classes, etc.) declared in the module are not visible outside -that module unless they are explicitly exported. +Each module creates its own scope, i.e., any declarations (variables, functions, classes, etc.) declared in the module are not visible outside that module unless they are explicitly exported. -Conversely, a variable, function, class, interface, etc. exported from -another module must first be imported to a module. +Conversely, a variable, function, class, interface, etc. exported from another module must first be imported to a module. ## Export A top-level declaration can be exported by using the keyword `export`. -A declared name that is not exported is considered private and can be used -only in the module where it is declared. +A declared name that is not exported is considered private and can be used only in the module where it is declared. ```typescript export class Point { @@ -1733,20 +1571,17 @@ export function Distance(p1: Point, p2: Point): number { ## Import -Import declarations are used to import entities exported from other modules -and provide their bindings in the current module. An import declaration -consists of two parts: +Import declarations are used to import entities exported from other modules and provide their bindings in the current module. +An import declaration consists of two parts: -* Import path that determines the module to import from; -* Import bindings that define the set of usable entities in the imported - module, and the form of use (i.e., qualified or unqualified use). +* Import path that determines the module to import from. +* Import bindings that define the set of usable entities in the imported module, and the form of use (i.e., qualified or unqualified use). Import bindings may have several forms. -Let’s assume a module has the path ‘./utils’ and export entities ‘X’ and ‘Y’. +Let's assume a module has the path './utils' and export entities 'X' and 'Y'. -An import binding of the form `* as A` binds the name ‘A’, and all entities -exported from the module defined by the import path can be accessed by using +An import binding of the form `* as A` binds the name 'A', and all entities exported from the module defined by the import path can be accessed by using the qualified name `A.name`: ```typescript @@ -1755,8 +1590,7 @@ Utils.X // denotes X from Utils Utils.Y // denotes Y from Utils ``` -An import binding of the form `{ ident1, ..., identN }` binds an exported -entity with a specified name, which can be used as a simple name: +An import binding of the form `{ ident1, ..., identN }` binds an exported entity with a specified name, which can be used as a simple name: ```typescript import { X, Y } from "./utils" @@ -1764,8 +1598,7 @@ X // denotes X from Utils Y // denotes Y from Utils ``` -If a list of identifiers contains aliasing of the form `ident as alias`, -then entity `ident` is bound under the name `alias`: +If a list of identifiers contains aliasing of the form `ident as alias`, then entity `ident` is bound under the name `alias`: ```typescript import { X as Z, Y } from "./utils" @@ -1778,17 +1611,13 @@ X // Compile-time error: 'X' is not visible A module can contain any statements at the module level, except `return` ones. -If a module contains a `main` function (program entry point), then -top-level statements of the module are executed immediately before -the body of this function. -Otherwise, they are executed before execution of any other function -of the module. +If a module contains a `main` function (program entry point), then top-level statements of the module are executed immediately before the body of this function. +Otherwise, they are executed before execution of any other function of the module. ## Program Entry Point An entry point of a program (application) is the top-level `main` function. -The `main` function must have either an empty parameter list or a single -parameter of `string[]` type. +The `main` function must have either an empty parameter list or a single parameter of `string[]` type. ```typescript function main() { @@ -1798,18 +1627,11 @@ function main() { # Support for ArkUI -This section demonstrates mechanisms that ArkTS provides for -creating graphical user interface (GUI) programs. The section is based on -the ArkUI declarative framework. ArkUI provides a set of extensions of -the standard TypeScript to declaratively describe the GUI of the applications -and the interaction between the GUI components. +This section demonstrates mechanisms that ArkTS provides for creating graphical user interface (GUI) programs. The section is based on the ArkUI declarative framework. ArkUI provides a set of extensions of the standard TypeScript to declaratively describe the GUI of the applications and the interaction between the GUI components. ## ArkUI Example -The following example provides a complete ArkUI-based application as an -illustration of GUI programming capabilities. For more details of the -ArkUI features, refer to the ArkUI -[tutorial](arkts-get-started.md). +The following example provides a complete ArkUI-based application as an illustration of GUI programming capabilities. For more details of the ArkUI features, refer to the ArkUI [tutorial](arkts-get-started.md). ```typescript // ViewModel classes --------------------------- @@ -1990,7 +1812,7 @@ struct PersonEditView { // delete found contact this.addrBook.contacts.splice(index, 1) - // determin new selectedPerson + // determine new selectedPerson index = (index < this.addrBook.contacts.length) ? index : index - 1 diff --git a/en/application-dev/quick-start/module-configuration-file.md b/en/application-dev/quick-start/module-configuration-file.md index 5fe815d3e9df1e60501504dab5b38f3b860e9b93..fd060ffb672ba9f4dd0dd93afa89952a3fa55461 100644 --- a/en/application-dev/quick-start/module-configuration-file.md +++ b/en/application-dev/quick-start/module-configuration-file.md @@ -238,7 +238,7 @@ The **abilities** tag represents the UIAbility configuration of the module, whic | description | Description of the UIAbility component. The value is a string with a maximum of 255 bytes or a resource index to the description in multiple languages.| String| Yes (initial value: left empty)| | icon | Icon of the UIAbility component. The value is an icon resource index.| String| Yes (initial value: left empty)
If **UIAbility** is set to **MainElement**, this attribute is mandatory.| | label | Name of the UIAbility component displayed to users. The value is a string resource index.| String| Yes (initial value: left empty)
If **UIAbility** is set to **MainElement**, this attribute is mandatory.| -| permissions | Permissions required for another application to access the UIAbility component.
The value is an array of permission names predefined by the system, generally in the reverse domain name notation. It contains a maximum of 255 bytes.| String array| Yes (initial value: left empty)| +| permissions | Permissions required for another application to access the UIAbility component.
The value is generally in the reverse domain name notation and contains a maximum of 255 bytes. It is an array of predefined permission names.| String array| Yes (initial value: left empty)| | [metadata](#metadata)| Metadata information of the UIAbility component.| Object array| Yes (initial value: left empty)| | exported | Whether the UIAbility component can be called by other applications.
- **true**: The UIAbility component can be called by other applications.
- **false**: The UIAbility component cannot be called by other applications.| Boolean| Yes (initial value: **false**)| | continuable | Whether the UIAbility component can be [migrated](../application-models/hop-cross-device-migration.md).
- **true**: The UIAbility component can be migrated.
- **false**: The UIAbility component cannot be migrated.| Boolean| Yes (initial value: **false**)| diff --git a/en/application-dev/quick-start/start-with-ets-stage.md b/en/application-dev/quick-start/start-with-ets-stage.md index 2205e71621f27e3c779dbe27d4f0bca4efc9cbaf..f8972e3f1aa70f294661691b2c61206ed6b1792f 100644 --- a/en/application-dev/quick-start/start-with-ets-stage.md +++ b/en/application-dev/quick-start/start-with-ets-stage.md @@ -3,8 +3,6 @@ > **NOTE** > -> To use ArkTS, your DevEco Studio must be V3.0.0.900 Beta3 or later. -> > In this document, DevEco Studio 4.0 Beta2 is used. You can download it [here](../../release-notes/OpenHarmony-v4.0-beta2.md#version-mapping). ## Creating an ArkTS Project @@ -30,9 +28,9 @@ The following describes how to create the OpenHarmony projects of API 10 and API > **NOTE** > > You can use the low-code development mode apart from the traditional coding approach. - > + > > On the low-code development pages, you can design your application UI in an efficient, intuitive manner, with a wide array of UI editing features. - > + > > To use the low-code development mode, turn on **Enable Super Visual** on the page shown above. 4. Click **Finish**. DevEco Studio will automatically generate the sample code and resources that match your project type. Wait until the project is created. @@ -69,9 +67,9 @@ The following describes how to create the OpenHarmony projects of API 10 and API > **NOTE** > > You can use the low-code development mode apart from the traditional coding approach. - > + > > On the low-code development pages, you can design your application UI in an efficient, intuitive manner, with a wide array of UI editing features. - > + > > To use the low-code development mode, turn on **Enable Super Visual** on the page shown above. 4. Click **Finish**. DevEco Studio will automatically generate the sample code and resources that match your project type. Wait until the project is created. @@ -306,7 +304,13 @@ You can implement page redirection through the [page router](../reference/apis/j .height('5%') // Bind the onClick event to the Next button so that clicking the button redirects the user to the second page. .onClick(() => { - router.pushUrl({ url: 'pages/Second' }) + console.info(`Succeeded in clicking the 'Next' button.`) + // Redirect the user to the second page. + router.pushUrl({ url: 'pages/Second' }).then(() => { + console.info('Succeeded in jumping to the second page.') + }).catch((err) => { + console.error(`Failed to jump to the second page.Code is ${err.code}, message is ${err.message}`) + }) }) } .width('100%') @@ -350,7 +354,14 @@ You can implement page redirection through the [page router](../reference/apis/j .height('5%') // Bind the onClick event to the Back button so that clicking the button redirects the user back to the first page. .onClick(() => { - router.back() + console.info(`Succeeded in clicking the 'Back' button.`) + try { + // Redirect the user back to the first page. + router.back() + console.info('Succeeded in returning to the first page.') + } catch (err) { + console.error(`Failed to return to the first page.Code is ${err.code}, message is ${err.message}`) + } }) } .width('100%') diff --git a/en/application-dev/quick-start/typescript-to-arkts-migration-guide.md b/en/application-dev/quick-start/typescript-to-arkts-migration-guide.md index eb3a47adb6545ddb001689b8374b206703a0b9b3..627a84e3125a9659a90ab945f8f1ecca0b6d15cb 100644 --- a/en/application-dev/quick-start/typescript-to-arkts-migration-guide.md +++ b/en/application-dev/quick-start/typescript-to-arkts-migration-guide.md @@ -19,7 +19,7 @@ categories: PageBreak -# How to Use The Cookbook +# How to Use the Cookbook The main goal of this cookbook is to provide recipes for all partially supported features and explicitly list all unsupported features. @@ -215,19 +215,15 @@ strong positive impact on performance at the cost of low-effort refactoring. ## Semantics of Operators Is Restricted To achieve better performance and encourage developers write clearer code, -ArkTS restricts the semantics of some operators. A couple of examples are -given below, and the full list of restrictions is outlined in [Recipes](#recipes). +ArkTS restricts the semantics of some operators. An example is given below, +and the full list of restrictions is outlined in [Recipes](#recipes). ### Example ```typescript -// Operator `+` is defined for numbers and strings, but not for other types: -class C { - // ... -} -let c1 : C = new C() -let c2 : C = new C() -console.log(c1 + c2) // Compile-time error +// Unary `+` is defined only for numbers, but not for strings: +console.log(+42) // OK +console.log(+"42") // Compile-time error ``` ### Rationale and Impact @@ -358,12 +354,11 @@ console.log(z.get(2)) **See also** * Recipe: Symbol() API is not supported -* Recipe: Attempt to access an undefined property is a compile-time error +* Recipe: Indexed access is not supported for fields * Recipe: delete operator is not supported * Recipe: typeof operator is allowed only in expression contexts * Recipe: in operator is not supported * Recipe: Property-based runtime type checks are not supported -* Recipe: Dynamic property declaration is not supported * Recipe: Usage of standard library is restricted ## Recipe: `Symbol()` API is not supported @@ -378,6 +373,9 @@ because its most popular use cases make no sense in the statically typed environment. In particular, the object layout is defined at compile time, and cannot be changed at runtime. +`Symbol.iterator` and iterable interfaces are not supported either. +Use arrays and library-level containers to iterate over data. + **TypeScript** ```typescript @@ -385,6 +383,26 @@ const sym = Symbol() let o = { [sym]: "value" } + +let obj = { + data: ['a', 'b', 'c'], + [Symbol.iterator]() { + const this_ = this + let index = 0 + return { + next() { + return { + done: index >= this_.data.length, + value: 'name_' + this_.data[index++] + } + } + } + } +} + +for (let t of obj) { + console.log(t) +} ``` **ArkTS** @@ -394,17 +412,21 @@ class SomeClass { public someProperty : string = "" } let o = new SomeClass() + +let arr:string[] = ['a', 'b', 'c'] +for (let t of arr) { + console.log('name_' + t) +} ``` **See also** * Recipe: Objects with property names that are not identifiers are not supported -* Recipe: Attempt to access an undefined property is a compile-time error +* Recipe: Indexed access is not supported for fields * Recipe: delete operator is not supported * Recipe: typeof operator is allowed only in expression contexts * Recipe: in operator is not supported * Recipe: Property-based runtime type checks are not supported -* Recipe: Dynamic property declaration is not supported * Recipe: Usage of standard library is restricted ## Recipe: Private ‘#’ identifiers are not supported @@ -420,7 +442,7 @@ the keyword `private` instead. ```typescript /* - * Such notation for private fields is not supported: + * Such notation for private fields is not supported in ArkTS: class C { #foo: number = 42 } @@ -435,14 +457,14 @@ class C { } ``` -## Recipe: Use unique names for types, namespaces, etc. +## Recipe: Use unique names for types and namespaces. **Rule `arkts-unique-names`** **Severity: error** -Names for types, namespaces and so on must be unique and distinct from other -names, e.g., variable names. +Names for all types (classes, interfaces, enums) and namespaces must be unique +and distinct from other names, e.g., variable names and function names. **TypeScript** @@ -666,7 +688,7 @@ function fn(s: string): SomeObject { **Severity: error** -ArkTS does not allow having sevaral static blocks for class initialization. +ArkTS does not allow having several static blocks for class initialization. Combine static block statements into one static block. **TypeScript** @@ -779,7 +801,9 @@ interface Employee extends Identity, Contact {} **Severity: error** -ArkTS does not support the returning `this` type. Use explicit type instead. +ArkTS does not support type notation using the `this` keyword (for example, +specifying a method’s return type `this` is not allowed). Use explicit type +instead. **TypeScript** @@ -834,7 +858,7 @@ type Y = T extends Array ? Item : never **ArkTS** ```typescript -// Provide explicit contraints within type alias +// Provide explicit constraints within type alias type X1 = T // Rewrite with Object. Less type control, need more type checks for safety @@ -958,95 +982,103 @@ type N = number **Severity: error** -ArkTS does not support indexed access for class fields. Use dot notation -instead. +ArkTS does not support dynamic field declaration and access. Declare all +object fields immediately in the class. Access only those class fields +that are either declared in the class, or accessible via inheritance. Accessing +any other fields is prohibited, and causes compile-time errors. + +To access a field, use `obj.field` syntax, indexed access (`obj["field"]`) +is not supported. An exception are all typed arrays from the standard library +(for example, `Int32Array`), which support access to their elements through +`container[index]` syntax. **TypeScript** ```typescript -class Point {x: number = 0; y: number = 0} +class Point { + x: number = 0 + y: number = 0 +} let p: Point = {x: 1, y: 2} -let x = p["x"] +console.log(p["x"]) + +class Person { + name: string = "" + age: number = 0; // semicolon is required here + [key: string]: string | number +} + +let person: Person = { + name: "John", + age: 30, + email: "***@example.com", + phoneNumber: "18*********", +} ``` **ArkTS** ```typescript -class Point {x: number = 0; y: number = 0} +class Point { + x: number = 0 + y: number = 0 +} let p: Point = {x: 1, y: 2} -let x = p.x +console.log(p.x) + +class Person { + name: string + age: number + email: string + phoneNumber: string + + constructor(name: string, age: number, email: string, + phoneNumber: string) { + this.name = name + this.age = age + this.email = email + this.phoneNumber = phoneNumber + } +} + +let person = new Person("John", 30, "***@example.com", "18*********") +console.log(person["name"]) // Compile-time error +console.log(person.unknownProperty) // Compile-time error + +let arr = new Int32Array(1) +console.log(arr[0]) ``` -## Recipe: Structural identity is not supported +## Recipe: Structural typing is not supported -**Rule `arkts-no-structural-identity`** +**Rule `arkts-no-structural-typing`** **Severity: error** -Currently, ArkTS does not support structural identity, i.e., the compiler +Currently, ArkTS does not support structural typing, i.e., the compiler cannot compare public APIs of two types and decide whether such types are identical. Use other mechanisms (inheritance, interfaces or type aliases) instead. -In the examples below, types `X` and `Y` are equivalent (interchangeble) -in TypeScript, while in ArkTS they are not. - **TypeScript** ```typescript -interface X { +interface I1 { f(): string } -interface Y { // Y is equal to X +interface I2 { // I2 is structurally equivalent to I1 f(): string } -``` - -**ArkTS** -```typescript -interface X { - f(): string -} - -type Y = X // Y is equal to X -``` - -**See also** - -* Recipe: Structural typing is not supported for subtyping / supertyping -* Recipe: Structural typing is not supported for assignability checks -* Recipe: Structural typing is not supported for type inference - -## Recipe: Structural typing is not supported for subtyping / supertyping - -**Rule `arkts-no-structural-subtyping`** - -**Severity: error** - -Currently, ArkTS does not check structural equivalence for type inference, -i.e., the compiler cannot compare public APIs of two types and decide whether -such types are identical. Use other mechanisms (inheritance or interfaces) -instead. - -**TypeScript** - -```typescript class X { - public foo: number - - constructor() { - this.foo = 0 - } + n: number = 0 + s: string = "" } -class Y { - public foo: number - - constructor() { - this.foo = 0 - } +class Y { // Y is structurally equivalent to X + n: number = 0 + s: string = "" } let x = new X() @@ -1057,104 +1089,62 @@ y = x console.log("Assign Y to X") x = y -``` -**ArkTS** - -```typescript -class X { - public foo: number - - constructor() { - this.foo = 0 - } -} - -// Y is derived from X, which explicitly set subtype / supertype relations: -class Y extends X { - constructor() { - super() - } +function foo(x: X) { + console.log(x.n, x.s) } -let x = new X() -let y = new Y() - -console.log("Assign Y to X") -x = y // ok, X is the super class of Y - -// Cannot assign X to Y -//y = x - compile-time error +// X and Y are equivalent because their public API is equivalent. +// Thus the second call is allowed: +foo(new X()) +foo(new Y()) ``` -**See also** - -* Recipe: Structural identity is not supported -* Recipe: Structural typing is not supported for assignability checks -* Recipe: Structural typing is not supported for type inference - -## Recipe: Structural typing is not supported for assignability checks - -**Rule `arkts-no-structural-assignability`** - -**Severity: error** - -Currently, ArkTS does not check structural equivalence when checking if types -are assignable to each other, i.e., the compiler cannot compare public APIs of -two types and decide whether such types are identical. Use other mechanisms -(inheritance or interfaces) instead. - -**TypeScript** +**ArkTS** ```typescript -class X { - public foo: number +interface I1 { + f(): string +} - constructor() { - this.foo = 0 - } +type I2 = I1 // I2 is an alias for I1 + +class B { + n: number = 0 + s: string = "" } -class Y { - public foo: number +// D is derived from B, which explicitly set subtype / supertype relations: +class D extends B { constructor() { - this.foo = 0 + super() } } -let x = new X() -let y = new Y() +let b = new B() +let d = new D() -console.log("Assign X to Y") -y = x +console.log("Assign D to B") +b = d // ok, B is the superclass of D -console.log("Assign Y to X") -x = y -``` +// An attempt to assign b to d will result in a compile-time error: +// d = b -**ArkTS** - -```typescript interface Z { - foo: number + n: number + s: string } // X implements interface Z, which makes relation between X and Y explicit. class X implements Z { - public foo: number - - constructor() { - this.foo = 0 - } + n: number = 0 + s: string = "" } // Y implements interface Z, which makes relation between X and Y explicit. class Y implements Z { - public foo: number - - constructor() { - this.foo = 0 - } + n: number = 0 + s: string = "" } let x: Z = new X() @@ -1165,13 +1155,15 @@ y = x // ok, both are of the same type console.log("Assign Y to X") x = y // ok, both are of the same type -``` -**See also** +function foo(c: Z): void { + console.log(c.n, c.s) +} -* Recipe: Structural identity is not supported -* Recipe: Structural typing is not supported for subtyping / supertyping -* Recipe: Structural typing is not supported for type inference +// X and Y implement the same interface, thus both calls are allowed: +foo(new X()) +foo(new Y()) +``` ## Recipe: Type inference in case of generic function calls is limited @@ -1216,101 +1208,6 @@ function greet(): T { let z = greet() ``` -## Recipe: Structural typing is not supported for type inference - -**Rule `arkts-no-structural-inference`** - -**Severity: error** - -Currently, ArkTS does not support structural typing, i.e., the compiler cannot -compare public APIs of two types and decide whether such types are identical. -Use inheritance and interfaces to specify the relation between the types -explicitly. - -**TypeScript** - -```typescript -class X { - public foo: number - private s: string - - constructor (f: number) { - this.foo = f - this.s = "" - } - - public say(): void { - console.log("X = ", this.foo) - } -} - -class Y { - public foo: number - - constructor (f: number) { - this.foo = f - } - public say(): void { - console.log("Y = ", this.foo) - } -} - -function bar(z: X): void { - z.say() -} - -// X and Y are equivalent because their public API is equivalent. -// Thus the second call is allowed: -bar(new X(1)) -bar(new Y(2) as X) -``` - -**ArkTS** - -```typescript -interface Z { - say(): void -} - -class X implements Z { - public foo: number - private s: string - - constructor (f: number) { - this.foo = f - this.s = "" - } - public say(): void { - console.log("X = ", this.foo) - } -} - -class Y implements Z { - public foo: number - - constructor (f: number) { - this.foo = f - } - public say(): void { - console.log("Y = ", this.foo) - } -} - -function bar(z: Z): void { - z.say() -} - -// X and Y implement the same interface Z, thus both calls are allowed: -bar(new X(1)) -bar(new Y(2)) -``` - -**See also** - -* Recipe: Structural identity is not supported -* Recipe: Structural typing is not supported for subtyping / supertyping -* Recipe: Structural typing is not supported for assignability checks - ## Recipe: RegExp literals are not supported **Rule `arkts-no-regexp-literals`** @@ -1468,7 +1365,7 @@ id_x_y({x: 5, y: 10}) **See also** * Recipe: Object literals cannot be used as type declarations -* Recipe: Array literals must contain elements of only inferrable types +* Recipe: Array literals must contain elements of only inferable types ## Recipe: Object literals cannot be used as type declarations @@ -1506,17 +1403,17 @@ type S = Set **See also** * Recipe: Object literal must correspond to some explicitly declared class or interface -* Recipe: Array literals must contain elements of only inferrable types +* Recipe: Array literals must contain elements of only inferable types -## Recipe: Array literals must contain elements of only inferrable types +## Recipe: Array literals must contain elements of only inferable types -**Rule `arkts-no-noninferrable-arr-literals`** +**Rule `arkts-no-noninferable-arr-literals`** **Severity: error** Basically, ArkTS infers the type of an array literal as a union type of its contents. However, a compile-time error occurs if there is at least one -element with a non-inferrable type (e.g. untyped object literal). +element with a non-inferable type (e.g. untyped object literal). **TypeScript** @@ -1541,33 +1438,6 @@ let a2: C[] = [{n: 1, s: "1"}, {n: 2, s : "2"}] // ditto * Recipe: Object literal must correspond to some explicitly declared class or interface * Recipe: Object literals cannot be used as type declarations -## Recipe: Lambdas require explicit type annotation for parameters - -**Rule `arkts-explicit-param-types-in-lambdas`** - -**Severity: error** - -Currently, ArkTS requires the types of lambda parameters -to be explicitly specified. - -**TypeScript** - -```typescript -// Compile-time error only with noImplicitAny: -let f = (s /* type any is assumed */) => { - console.log(s) -} -``` - -**ArkTS** - -```typescript -// Explicit types for lambda parameters are mandatory: -let f = (s: string) => { - console.log(s) -} -``` - ## Recipe: Use arrow functions instead of function expressions **Rule `arkts-no-func-expressions`** @@ -1694,57 +1564,6 @@ class C1 implements C { } ``` -## Recipe: Attempt to access an undefined property is a compile-time error - -**Rule `arkts-no-undefined-prop-access`** - -**Severity: error** - -ArkTS supports accessing only those class properties that are either declared -in the class, or accessible via inheritance. Accessing any other properties is -prohibited, and causes compile-time errors. Use proper types to check property -existence during compilation. - -**TypeScript** - -```typescript -let person = {name: "Bob", isEmployee: true} - -let n = person["name"] -let e = person["isEmployee"] -let s = person["office"] // Compile-time error only with noImplicitAny -``` - -**ArkTS** - -```typescript -class Person { - constructor(name: string, isEmployee: boolean) { - this.name = name - this.isEmployee = isEmployee - } - - name: string - isEmployee: boolean -} - -let person = new Person("Bob", true) -let n = person.name -let e = person.isEmployee -let s = person.office // Compile-time error -``` - -**See also** - -* Recipe: Objects with property names that are not identifiers are not supported -* Recipe: Symbol() API is not supported -* Recipe: delete operator is not supported -* Recipe: typeof operator is allowed only in expression contexts -* Recipe: in operator is not supported -* Recipe: Property-based runtime type checks are not supported -* Recipe: Dynamic property declaration is not supported -* Recipe: Usage of standard library is restricted - ## Recipe: Only `as T` syntax is supported for type casts **Rule `arkts-as-casts`** @@ -1912,11 +1731,10 @@ p.y = null * Recipe: Objects with property names that are not identifiers are not supported * Recipe: Symbol() API is not supported -* Recipe: Attempt to access an undefined property is a compile-time error +* Recipe: Indexed access is not supported for fields * Recipe: typeof operator is allowed only in expression contexts * Recipe: in operator is not supported * Recipe: Property-based runtime type checks are not supported -* Recipe: Dynamic property declaration is not supported ## Recipe: `typeof` operator is allowed only in expression contexts @@ -1953,72 +1771,12 @@ let s2: string * Recipe: Objects with property names that are not identifiers are not supported * Recipe: Symbol() API is not supported -* Recipe: Attempt to access an undefined property is a compile-time error +* Recipe: Indexed access is not supported for fields * Recipe: delete operator is not supported * Recipe: in operator is not supported * Recipe: Property-based runtime type checks are not supported -* Recipe: Dynamic property declaration is not supported * Recipe: Usage of standard library is restricted -## Recipe: Binary `+` operator supports implicit casts only for numbers, enums and strings - -**Rule `arkts-no-polymorphic-plus`** - -**Severity: error** - -If one of the operands of the binary `+` operator is of the string type -(including enum string constant), then the other operand can be of any type, -and its value is implicitly converted to string. -Otherwise, ArkTS supports implicit casts with `+` only for numbers and -numeric enum constants. -ArkTS, like TypeScript, does not support the operator `+` for the booleans. -Elsewhere, any form of an explicit cast is required. - -**TypeScript** - -```typescript -enum E { E1, E2 } - -let a = 10 + 32 // 42 -let b = E.E1 + 10 // 10 -let c = 10 + "5" // "105" - -let d = "5" + E.E2 // "51" -let e = "Hello, " + "world!" // "Hello, world!" -let f = "string" + true // "stringtrue" - -let g = (new Object()) + "string" // "[object Object]string" - -let i = true + true // JS: 2, TS: compile-time error -let j = true + 2 // JS: 3, TS: compile-time error -let k = E.E1 + true // JS: 1, TS: compile-time error -``` - -**ArkTS** - -```typescript -enum E { E1, E2 } - -let a = 10 + 32 // 42 -let b = E.E1 + 10 // 10 -let c = 10 + "5" // "105" - -let d = "5" + E.E2 // "51" -let e = "Hello, " + "world!" // "Hello, world!" -let f = "string" + true // "stringtrue" - -let g = (new Object()).toString() + "string" - - -let i = true + true // compile-time error -let j = true + 2 // compile-time error -let k = E.E1 + true // compile-time error -``` - -**See also** - -* Recipe: Unary operators +, - and ~ work only on numbers - ## Recipe: `instanceof` operator is partially supported **Rule `arkts-instanceof-ref-types`** @@ -2096,11 +1854,10 @@ let b = p instanceof Person // true, and "name" is guaranteed to be present * Recipe: Objects with property names that are not identifiers are not supported * Recipe: Symbol() API is not supported -* Recipe: Attempt to access an undefined property is a compile-time error +* Recipe: Indexed access is not supported for fields * Recipe: delete operator is not supported * Recipe: typeof operator is allowed only in expression contexts * Recipe: Property-based runtime type checks are not supported -* Recipe: Dynamic property declaration is not supported * Recipe: Usage of standard library is restricted ## Recipe: Destructuring assignment is not supported @@ -2220,35 +1977,6 @@ let x = zp.x let y = zp.y ``` -## Recipe: Inference of implied types is not supported - -**Rule `arkts-no-implied-inference`** - -**Severity: error** - -Currently, ArkTS does not support inference of implied types. -Use explicit type notation instead. -Use `Object[]` if you need containers that hold data of mixed types. - -**TypeScript** - -```typescript -let [a, b, c] = [1, "hello", true] -``` - -**ArkTS** - -```typescript -let a = 1 -let b = "hello" -let c = true - -let arr: Object[] = [1, "hello", true] -let a1 = arr[0] -let b1 = arr[1] -let c1 = arr[2] -``` - ## Recipe: Type annotation in catch clause is not supported **Rule `arkts-no-types-in-catch`** @@ -2315,23 +2043,6 @@ for (let i = 0; i < a.length; ++i) { **See also** -* Recipe: Iterable interfaces are not supported -* Recipe: for-of is supported only for arrays and strings - -## Recipe: Iterable interfaces are not supported - -**Rule `arkts-no-iterable`** - -**Severity: error** - -ArkTS does not support the `Symbol` API, `Symbol.iterator` and -eventually iterable interfaces. Use arrays and library-level containers to -iterate over data. - -**See also** - -* Recipe: Symbol() API is not supported -* Recipe: for .. in is not supported * Recipe: for-of is supported only for arrays and strings ## Recipe: `for-of` is supported only for arrays and strings @@ -2341,7 +2052,8 @@ iterate over data. **Severity: error** ArkTS supports the iteration over arrays and strings by the `for .. of` loop, -but does not support the iteration of objects content. +but does not support the iteration of objects content. All typed arrays from +the standard library (for example, `Int32Array`) are also supported. **TypeScript** @@ -2365,7 +2077,6 @@ for (let n of numbers) { **See also** * Recipe: for .. in is not supported -* Recipe: Iterable interfaces are not supported ## Recipe: Mapped type expression is not supported @@ -2374,7 +2085,7 @@ for (let n of numbers) { **Severity: error** ArkTS does not support mapped types. Use other language idioms and regular -classes to achieve that same behaviour. +classes to achieve that same behavior. **TypeScript** @@ -2409,7 +2120,7 @@ class CFlags { **Severity: error** ArkTS does not support the `with` statement. Use other language idioms -(including fully qualified names of functions) to achieve that same behaviour. +(including fully qualified names of functions) to achieve that same behavior. **TypeScript** @@ -2427,95 +2138,6 @@ let r: number = 42 console.log("Area: ", Math.PI * r * r) ``` -## Recipe: Values computed at runtime are not supported in `case` statements - -**Rule `arkts-no-computed-case`** - -**Severity: error** - -ArkTS supports `case` statements that contain only compile-time values. -Use `if` statements as an alternative. - -**TypeScript** - -```typescript -let x = 2 -let y = 3 -switch (x) { - case 1: - console.log(1) - break - case 2: - console.log(2) - break - case y: - console.log(y) - break - default: - console.log("other") -} -``` - -**ArkTS** - -```typescript -let x = 2 -switch (x) { - case 1: - console.log(1) - break - case 2: - console.log(2) - break - case 3: - console.log(3) - break - default: - console.log("other") -} -``` - -## Recipe: `switch` statements cannot accept values of arbitrary types - -**Rule `arkts-limited-switch`** - -**Severity: error** - -ArkTS restricts the types that are supported in `switch` statements. In -particular, values of the types `number`, `Number`, `string`, `String` -or `enum` are supported. Use `if` statements in case of unsupported types. - -**TypeScript** - -```typescript -class Point { - x: number = 0 - y: number = 0 -} - -let a = new Point() - -switch (a) { - case null: break - default: console.log("not null") -} -``` - -**ArkTS** - -```typescript -class Point { - x: number = 0 - y: number = 0 -} - -let a = new Point() - -if (a != null) { - console.log("not null") -} -``` - ## Recipe: `throw` statements cannot accept values of arbitrary types **Rule `arkts-limited-throw`** @@ -2686,8 +2308,8 @@ function addNum(a: number, b: number): void { **Severity: error** -ArkTS does not support the usage of `this` inside stand-alone functions. -`this` can be used in methods only. +ArkTS does not support the usage of `this` inside stand-alone functions and +inside static methods. `this` can be used in instance methods only. **TypeScript** @@ -2756,7 +2378,7 @@ for (let num of counter(1, 5)) { ```typescript async function complexNumberProcessing(n : number) : Promise { - // Some complex logic for proccessing the number here + // Some complex logic for processing the number here return n } @@ -2907,7 +2529,8 @@ function main(): void { The only supported scenario for the spread operator is to spread an array into the rest parameter. Otherwise, manually “unpack” data from arrays and objects, -where necessary. +where necessary. All typed arrays from the standard library (for example, +`Int32Array`) are also supported. **TypeScript** @@ -2963,7 +2586,7 @@ let p3d = new Point3D({x: 1, y: 2} as Point2D, 3) console.log(p3d.x, p3d.y, p3d.z) ``` -## Recipe: Interface declarations (extends same property) +## Recipe: Interface can not extend interfaces with the same method **Rule `arkts-no-extend-same-prop`** @@ -3066,8 +2689,8 @@ class C implements Mover, Shaker { **Severity: error** -ArkTS does not support merging declratations. Keep all definitions of classes, -interfaces and so on compact in the codebase. +ArkTS does not support merging declarations. Keep all definitions of classes +and interfaces compact in the codebase. **TypeScript** @@ -3192,11 +2815,10 @@ function main(): void { * Recipe: Objects with property names that are not identifiers are not supported * Recipe: Symbol() API is not supported -* Recipe: Attempt to access an undefined property is a compile-time error +* Recipe: Indexed access is not supported for fields * Recipe: delete operator is not supported * Recipe: typeof operator is allowed only in expression contexts * Recipe: in operator is not supported -* Recipe: Dynamic property declaration is not supported * Recipe: Usage of standard library is restricted ## Recipe: Constructor function type is not supported @@ -3249,67 +2871,6 @@ let Impersonizer: PersonCtor = (n: string, a: number): Person => { const person = createPerson(Impersonizer, "John", 30) ``` -## Recipe: Dynamic property declaration is not supported - -**Rule `arkts-no-dyn-prop-decl`** - -**Severity: error** - -ArkTS does not support dynamic property declaration. Declare all object -properties immediately in the class. While replacement for an array of -objects is possible, it is still better to adhere to the static language -paradigm, and declare fields, their names and types explicitly. - -**TypeScript** - -```typescript -class Person { - name: string = "" - age: number = 0; // semicolon is required here - [key: string]: string | number -} - -const person: Person = { - name: "John", - age: 30, - email: "john@example.com", - phoneNumber: 1234567890, -} -``` - -**ArkTS** - -```typescript -class Person { - name: string - age: number - email: string - phoneNumber: number - - constructor(name: string, age: number, email: string, phoneNumber: number) { - this.name = name - this.age = age - this.email = email - this.phoneNumber = phoneNumber - } -} - -function main(): void { - const person: Person = new Person("John", 30, "john@example.com", 1234567890) -} -``` - -**See also** - -* Recipe: Objects with property names that are not identifiers are not supported -* Recipe: Symbol() API is not supported -* Recipe: Attempt to access an undefined property is a compile-time error -* Recipe: delete operator is not supported -* Recipe: typeof operator is allowed only in expression contexts -* Recipe: in operator is not supported -* Recipe: Property-based runtime type checks are not supported -* Recipe: Usage of standard library is restricted - ## Recipe: Enumeration members can be initialized only with compile time expressions of the same type **Rule `arkts-no-enum-mixed-types`** @@ -3364,7 +2925,7 @@ enum E2 { **Severity: error** -ArkTS does not support merging declratations for `enum`. Keep the +ArkTS does not support merging declarations for `enum`. Keep the declaration of each `enum` compact in the codebase. **TypeScript** @@ -3431,7 +2992,7 @@ MyNamespace.x = 2 **Severity: error** -ArkTS does not support statements in namespaces. Use a function to exectute +ArkTS does not support statements in namespaces. Use a function to execute statements. **TypeScript** @@ -3515,7 +3076,7 @@ import "path/to/module" **ArkTS** ```typescript -import * from "path/to/module" +import * as m from "path/to/module" ``` ## Recipe: `import default as ...` is not supported @@ -3608,6 +3169,9 @@ export class C2 { export { Class1 } from "module1" export { C2 as Class2 } from "module1" +// Re-exporting by wild-card is also supported: +// export * from "module1" + // consumer module import { Class1, Class2 } from "module2" ``` @@ -3763,7 +3327,7 @@ declare namespace N { } // Consuming code: -import * from "module" +import * as m from "module" console.log("N.foo called: ", N.foo(42)) ``` @@ -3880,34 +3444,6 @@ let ce = new CustomError() * Recipe: Prototype assignment is not supported -## Recipe: Runtime import expressions are not supported - -**Rule `arkts-no-runtime-import`** - -**Severity: error** - -ArkTS does not support such “runtime” import expressions as `await import...` -because in the language import is a compile-time, not a runtime feature. -Use regular import syntax instead. - -**TypeScript** - -```typescript -const zipUtil = await import("utils/create-zip-file") -``` - -**ArkTS** - -```typescript -import { zipUtil } from "utils/create-zip-file" -``` - -**See also** - -* Recipe: Wildcards in module names are not supported -* Recipe: Universal module definitions (UMD) are not supported -* Recipe: Import assertions are not supported - ## Recipe: Definite assignment assertions are not supported **Rule `arkts-no-definite-assignment`** @@ -4065,8 +3601,7 @@ M.abc = 200 **Severity: error** Currently ArkTS does not support utility types from TypeScript extensions to the -standard library (`Omit`, `Pick`, etc.). Exceptions are: `Partial`, -`Record`. +standard library, except following: `Partial`, `Record`. For the type *Record*, the type of an indexing expression *rec[index]* is of the type *V | undefined*. @@ -4161,7 +3696,7 @@ function readFileSync(path : string) : number[] { return [] } -function decodeImageSync(contrents : number[]) { +function decodeImageSync(contents : number[]) { // ... } @@ -4349,7 +3884,6 @@ import { something } from "module" * Recipe: Wildcards in module names are not supported * Recipe: Universal module definitions (UMD) are not supported -* Recipe: Runtime import expressions are not supported ## Recipe: Usage of standard library is restricted @@ -4364,9 +3898,7 @@ the following APIs is prohibited: Properties and functions of the global object: `eval`, `Infinity`, `NaN`, `isFinite`, `isNaN`, `parseFloat`, `parseInt`, -`encodeURI`, `encodeURIComponent`, `Encode`, -`decodeURI`, `decodeURIComponent`, `Decode`, -`escape`, `unescape`, `ParseHexOctet` +`Encode`, `Decode`, `ParseHexOctet` `Object`: `__proto__`, `__defineGetter__`, `__defineSetter__`, `__lookupGetter__`, `__lookupSetter__`, `assign`, `create`, @@ -4396,11 +3928,10 @@ Properties and functions of the global object: `eval`, * Recipe: Objects with property names that are not identifiers are not supported * Recipe: Symbol() API is not supported -* Recipe: Attempt to access an undefined property is a compile-time error +* Recipe: Indexed access is not supported for fields * Recipe: typeof operator is allowed only in expression contexts * Recipe: in operator is not supported * Recipe: Property-based runtime type checks are not supported -* Recipe: Dynamic property declaration is not supported * Recipe: globalThis is not supported ## Recipe: Strict type checking is enforced @@ -4561,3 +4092,55 @@ class BugReport { } ``` +## Recipe: Classes cannot be used as objects + +**Rule `arkts-no-classes-as-obj`** + +**Severity: error** + +ArkTS does not support using classes as objects (assigning them to variables, +etc.) because in ArkTS, a `class` declaration introduces a new type, +not a value. + +**TypeScript** + +```typescript +class C { + s: string = "" + n: number = 0 +} + +let c = C +``` + +## Recipe: `import` statements after other statements are not allowed + +**Rule `arkts-no-misplaced-imports`** + +**Severity: error** + +In ArkTS, all `import` statements should go before all other statements +in the program. + +**TypeScript** + +```typescript +class C { + s: string = "" + n: number = 0 +} + +import foo from "module1" +``` + +**ArkTS** + +```typescript +import foo from "module1" + +class C { + s: string = "" + n: number = 0 +} +``` + diff --git a/en/application-dev/reference/apis/common_event/commonEvent-account.md b/en/application-dev/reference/apis/common_event/commonEvent-account.md index f850f33644513de697c1cd2f56d2f3439c6660c2..fe1328be2efb39090d7384f969ec8fd546b04b8c 100644 --- a/en/application-dev/reference/apis/common_event/commonEvent-account.md +++ b/en/application-dev/reference/apis/common_event/commonEvent-account.md @@ -44,33 +44,43 @@ APIs related to this event: **activateOsAccount**. This API is a system API. For ## COMMON_EVENT_USER_INFO_UPDATED9+ Indicates that the user information has been updated. -- Value: **usual.event.USER_INFO_UPDATED** +- Value: usual.event.USER_INFO_UPDATED - Required subscriber permissions: none When the distributed account information, system account profile picture, or system account name is changed, the event notification service is triggered to publish this event carrying the system account ID. APIs related to this event: **setOsAccountName**, **setOsAccountProfilePhoto**, and **setOsAccountDistributedInfon**. The first two are system APIs, and the last is a public API. For details, see [@ohos.account.osAccount (OS Account Management)](../js-apis-osAccount.md). +## COMMON_EVENT_USER_UNLOCKED +Indicates that the credential-encrypted storage has been unlocked for the current user after the device is restarted. + +- Value: usual.event.USER_UNLOCKED +- Required subscriber permissions: none + +When the device is unlocked with the lock screen password the first time after user switching, the event notification service is triggered to publish this event carrying the system account ID. + +APIs related to this event: **auth**. This API is a system API. For details, see [@ohos.account.osAccount (OS Account Management)](../js-apis-osAccount.md). + ## COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGIN (Reserved, not supported yet) Indicates a successful login to a distributed account. -- Value: usual.event.DISTRIBUTED_ACCOUNT_LOGIN +- Value: common.event.DISTRIBUTED_ACCOUNT_LOGIN - Required subscriber permissions: none ## COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOUT (Reserved, not supported yet) Indicates a successful logout of a distributed account. -- Value: usual.event.DISTRIBUTED_ACCOUNT_LOGOUT +- Value: common.event.DISTRIBUTED_ACCOUNT_LOGOUT - Required subscriber permissions: none ## COMMON_EVENT_DISTRIBUTED_ACCOUNT_TOKEN_INVALID (Reserved, not supported yet) Indicates the token of a distributed account is invalid. -- Value: usual.event.DISTRIBUTED_ACCOUNT_TOKEN_INVALID +- Value: common.event.DISTRIBUTED_ACCOUNT_TOKEN_INVALID - Required subscriber permissions: none ## COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOFF (Reserved, not supported yet) Indicates that a distributed account is deregistered. -- Value: usual.event.DISTRIBUTED_ACCOUNT_LOGOFF +- Value: common.event.DISTRIBUTED_ACCOUNT_LOGOFF - Required subscriber permissions: none diff --git a/en/application-dev/reference/apis/js-apis-WallpaperExtensionAbility.md b/en/application-dev/reference/apis/js-apis-WallpaperExtensionAbility.md index ff4eca1ad38630fe50188f784b4e24840fed7e41..e1fcf334ce67f666944dda6cd779d5225aad44b1 100644 --- a/en/application-dev/reference/apis/js-apis-WallpaperExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-WallpaperExtensionAbility.md @@ -1,12 +1,12 @@ # @ohos.WallpaperExtensionAbility (WallpaperExtensionAbility) -The **WallpaperExtensionAbility** module provides APIs for developing wallpaper extension abilities and managing the lifecycle of these extension abilities. +The **WallpaperExtensionAbility** module provides lifecycle callbacks for wallpaper extension abilities and APIs for listening for wallpaper changes. > **NOTE** > > The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. > -> The APIs of this module can be used only in the FA model. +> The APIs of this module can be used only in the stage model. > > The APIs provided by this module are system APIs. diff --git a/en/application-dev/reference/apis/js-apis-arkui-UIContext.md b/en/application-dev/reference/apis/js-apis-arkui-UIContext.md index 3862eeefb3dbb77c6171512c424af27e4f623eb8..5e352ae7c4ca2617e464e08282b38e1ef9544d34 100644 --- a/en/application-dev/reference/apis/js-apis-arkui-UIContext.md +++ b/en/application-dev/reference/apis/js-apis-arkui-UIContext.md @@ -139,6 +139,8 @@ animateTo(value: AnimateParam, event: () => void): void Applies a transition animation for state changes. +**System capability**: SystemCapability.ArkUI.ArkUI.Full + Since API version 9, this API is supported in ArkTS widgets. **Parameters** @@ -216,11 +218,14 @@ showAlertDialog(options: AlertDialogParamWithConfirm | AlertDialogParamWithButto Shows an alert dialog box. +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Description| -| ---- | --------------- | -------- | -| options | [AlertDialogParamWithConfirm](../arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithconfirm) \| [AlertDialogParamWithButtons](../arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithbuttons) | Defines and displays the **\** component.| +| Name | Type | Mandatory| Description| +| ---- | --------------- | -------- | -------- | +| options | [AlertDialogParamWithConfirm](../arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithconfirm) \| [AlertDialogParamWithButtons](../arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithbuttons) | Yes| Defines and displays the **\** component.| + **Example** @@ -252,9 +257,11 @@ showActionSheet(value: ActionSheetOptions): void Defines and shows the action sheet. +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **ActionSheetOptions parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory | Description | | ---------- | -------------------------- | ------- | ----------------------------- | | title | [Resource](../arkui-ts/ts-types.md#resource) \| string | Yes | Title of the dialog box.| | message | [Resource](../arkui-ts/ts-types.md#resource) \| string | Yes | Content of the dialog box. | @@ -267,7 +274,7 @@ Defines and shows the action sheet. **SheetInfo parameters** -| Name| Type | Mandatory| Description | +| Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ----------------- | | title | [ResourceStr](../arkui-ts/ts-types.md#resourcestr) | Yes | Text of the option. | | icon | [ResourceStr](../arkui-ts/ts-types.md#resourcestr) | No | Sheet icon. By default, no icon is displayed. | @@ -320,22 +327,24 @@ showDatePickerDialog(options: DatePickerDialogOptions): void Shows a date picker dialog box. +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **DatePickerDialogOptions parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| start | Date | No| Date('1970-1-1') | Start date of the picker.| -| end | Date | No| Date('2100-12-31') | End date of the picker.| -| selected | Date | No| Current system date| Selected date.| -| lunar | boolean | No| false | Whether to display the lunar calendar.| -| showTime | boolean | No| false | Whether to display the time item.| -| useMilitaryTime | boolean | No| false | Whether to display time in 24-hour format.| -| disappearTextStyle | [PickerTextStyle](../arkui-ts/ts-basic-components-datepicker.md#pickertextstyle10) | No| - | Font color, font size, and font width for the top and bottom items.| -| textStyle | [PickerTextStyle](../arkui-ts/ts-basic-components-datepicker.md#pickertextstyle10) | No| - | Font color, font size, and font width of all items except the top, bottom, and selected items.| -| selectedTextStyle | [PickerTextStyle](../arkui-ts/ts-basic-components-datepicker.md#pickertextstyle10) | No| - | Font color, font size, and font width of the selected item.| -| onAccept | (value: [DatePickerResult](../arkui-ts/ts-basic-components-datepicker.md#datepickerresult)) => void | No| - | Callback invoked when the OK button in the dialog box is clicked.| -| onCancel | () => void | No| - | Callback invoked when the Cancel button in the dialog box is clicked.| -| onChange | (value: [DatePickerResult](../arkui-ts/ts-basic-components-datepicker.md#datepickerresult)) => void | No| - | Callback invoked when the selected item in the picker changes.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| start | Date | No| Start date of the picker.
Default value: **Date('1970-1-1')**| +| end | Date | No| End date of the picker.
Default value: **Date('2100-12-31')**| +| selected | Date | No| Selected date.
Default value: current system date| +| lunar | boolean | No| Whether to display the lunar calendar.
Default value: **false**| +| showTime | boolean | No| Whether to display the time item.
Default value: **false**| +| useMilitaryTime | boolean | No| Whether to display time in 24-hour format.
Default value: **false**| +| disappearTextStyle | [PickerTextStyle](../arkui-ts/ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width for the top and bottom items.| +| textStyle | [PickerTextStyle](../arkui-ts/ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of all items except the top, bottom, and selected items.| +| selectedTextStyle | [PickerTextStyle](../arkui-ts/ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of the selected item.| +| onAccept | (value: [DatePickerResult](../arkui-ts/ts-basic-components-datepicker.md#datepickerresult)) => void | No| Callback invoked when the OK button in the dialog box is clicked.| +| onCancel | () => void | No| Callback invoked when the Cancel button in the dialog box is clicked.| +| onChange | (value: [DatePickerResult](../arkui-ts/ts-basic-components-datepicker.md#datepickerresult)) => void | No| Callback invoked when the selected item in the picker changes.| **Example** @@ -365,6 +374,8 @@ showTimePickerDialog(options: TimePickerDialogOptions): void Shows a time picker dialog box. +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **TimePickerDialogOptions parameters** | Name| Type| Mandatory| Description| @@ -404,9 +415,11 @@ showTextPickerDialog(options: TextPickerDialogOptions): void Shows a text picker in the given settings. +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **TextPickerDialogOptions parameters** -| Name| Type| Mandatory| Description| +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | range | string[] \| [Resource](../arkui-ts/ts-types.md#resource)\|[TextPickerRangeContent](../arkui-ts/ts-basic-components-textpicker.md#textpickerrangecontent10)[] | Yes| Data selection range of the picker. This parameter cannot be set to an empty array. If set to an empty array, it will not be displayed.| | selected | number | No| Index of the selected item.
Default value: **0**| @@ -507,7 +520,7 @@ In the following API examples, you must first use [getFont()](#getfont) in **UIC ### registerFont -registerFont(options: FontOptions): void +registerFont(options: font.FontOptions): void Registers a custom font with the font manager. @@ -515,9 +528,9 @@ Registers a custom font with the font manager. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | --------------------------- | ---- | ----------- | -| options | [FontOptions](js-apis-font.md#fontoptions) | Yes | Information about the custom font to register.| +| Name | Type | Mandatory| Description | +| ------- | ----------------------------------------------- | ---- | ---------------------- | +| options | [font.FontOptions](js-apis-font.md#fontoptions) | Yes | Information about the custom font to register.| **Example** @@ -528,13 +541,61 @@ font.registerFont({ familySrc: '/font/medium.ttf' }); ``` +### getStstemFontList + +getSystemFontList(): Array\ + +Obtains the list of supported fonts. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| -------------- | ------------------ | +| Array\ | List of supported fonts.| + +**Example** + +```ts +let font = uiContext.getFont(); +font.getSystemFontList() +``` + +### getFontByName + +getFontByName(fontName: string): font.FontInfo + +Obtains information about a system font based on the font name. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | -------------- | +| fontName | string | Yes | System font name.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------- | +| [FontInfo](js-apis-font.md#fontinfo10) | Information about the system font.| + +**Example** + +```ts +let font = uiContext.getFont(); +font.getFontByName('Sans Italic') +``` + ## ComponentUtils In the following API examples, you must first use [getComponentUtils()](#getcomponentutils) in **UIContext** to obtain a **ComponentUtils** instance, and then call the APIs using the obtained instance. ### getRectangleById -getRectangleById(key: string): ComponentInfo +getRectangleById(id: string): componentUtils.ComponentInfo Obtains the size, position, translation, scaling, rotation, and affine matrix information of the specified component. @@ -544,13 +605,13 @@ Obtains the size, position, translation, scaling, rotation, and affine matrix in | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------- | -| key | string | Yes | Unique component ID.| +| id | string | Yes | Unique component ID.| **Return value** -| Type | Description | -| ------------- | ------------------------------------------------------------ | -| ComponentInfo | Size, position, translation, scaling, rotation, and affine matrix information of the component. | +| Type | Description | +| -------------------------------------------------------- | ------------------------------------------------ | +| [ComponentInfo](js-apis-arkui-componentUtils.md#componentinfo) | Size, position, translation, scaling, rotation, and affine matrix information of the component.| **Example** @@ -567,7 +628,7 @@ In the following API examples, you must first use [getUIInspector()](#getuiinspe ### createComponentObserver -createComponentObserver(id: string): ComponentObserver +createComponentObserver(id: string): inspector.ComponentObserver Creates an observer for the specified component. @@ -581,8 +642,8 @@ Creates an observer for the specified component. **Return value** -| Type | Description | -| --------------------------------------- | -------------------------------------------------- | +| Type | Description | +| ------------------------------------------------------------ | -------------------------------------------------- | | [ComponentObserver](js-apis-arkui-inspector.md#componentobserver) | Component observer, which is used to register and unregister listeners for completion of component layout or drawing.| **Example** @@ -598,7 +659,7 @@ In the following API examples, you must first use [getMediaQuery()](#getmediaque ### matchMediaSync -matchMediaSync(condition: string): MediaQueryListener +matchMediaSync(condition: string): mediaQuery.MediaQueryListener Sets the media query criteria and returns the corresponding listening handle. @@ -629,7 +690,7 @@ In the following API examples, you must first use [getRouter()](#getrouter) in * ### pushUrl -pushUrl(options: RouterOptions): Promise<void> +pushUrl(options: router.RouterOptions): Promise<void> Navigates to a specified page in the application. @@ -637,9 +698,9 @@ Navigates to a specified page in the application. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------------------- | ---- | --------- | -| options | [RouterOptions](js-apis-router.md#routeroptions) | Yes | Page routing parameters.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------- | ---- | ------------------ | +| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes | Page routing parameters.| **Return value** @@ -680,7 +741,7 @@ router.pushUrl({ ### pushUrl -pushUrl(options: RouterOptions, callback: AsyncCallback<void>): void +pushUrl(options: router.RouterOptions, callback: AsyncCallback<void>): void Navigates to a specified page in the application. @@ -690,7 +751,7 @@ Navigates to a specified page in the application. | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | --------- | -| options | [RouterOptions](js-apis-router.md#routeroptions) | Yes | Page routing parameters.| +| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes | Page routing parameters.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** @@ -726,7 +787,7 @@ router.pushUrl({ ### pushUrl -pushUrl(options: RouterOptions, mode: RouterMode): Promise<void> +pushUrl(options: router.RouterOptions, mode: router.RouterMode): Promise<void> Navigates to a specified page in the application. @@ -734,10 +795,10 @@ Navigates to a specified page in the application. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------------------- | ---- | ---------- | -| options | [RouterOptions](js-apis-router.md#routeroptions) | Yes | Page routing parameters. | -| mode | [RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------- | ---- | -------------------- | +| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes | Page routing parameters. | +| mode | [router.RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| **Return value** @@ -778,7 +839,7 @@ router.pushUrl({ ### pushUrl -pushUrl(options: RouterOptions, mode: RouterMode, callback: AsyncCallback<void>): void +pushUrl(options: router.RouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void Navigates to a specified page in the application. @@ -788,8 +849,8 @@ Navigates to a specified page in the application. | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | ---------- | -| options | [RouterOptions](js-apis-router.md#routeroptions) | Yes | Page routing parameters. | -| mode | [RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| +| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes | Page routing parameters. | +| mode | [router.RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** @@ -825,17 +886,17 @@ router.pushUrl({ ### replaceUrl -replaceUrl(options: RouterOptions): Promise<void> +replaceUrl(options: router.RouterOptions): Promise<void> Replaces the current page with another one in the application and destroys the current page. -**System capability**: SystemCapability.ArkUI.ArkUI.Lite +**System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------------------------- | ---- | ------------------ | -| options | [RouterOptions](js-apis-router.md#routeroptions) | Yes | Description of the new page.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------- | ---- | ------------------ | +| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes | Description of the new page.| **Return value** @@ -872,17 +933,17 @@ router.replaceUrl({ ### replaceUrl -replaceUrl(options: RouterOptions, callback: AsyncCallback<void>): void +replaceUrl(options: router.RouterOptions, callback: AsyncCallback<void>): void Replaces the current page with another one in the application and destroys the current page. -**System capability**: SystemCapability.ArkUI.ArkUI.Lite +**System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** | Name | Type | Mandatory| Description | | ------- | ------------------------------- | ---- | ------------------ | -| options | [RouterOptions](js-apis-router.md#routeroptions) | Yes | Description of the new page.| +| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes | Description of the new page.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** @@ -914,18 +975,18 @@ router.replaceUrl({ ### replaceUrl -replaceUrl(options: RouterOptions, mode: RouterMode): Promise<void> +replaceUrl(options: router.RouterOptions, mode: router.RouterMode): Promise<void> Replaces the current page with another one in the application and destroys the current page. -**System capability**: SystemCapability.ArkUI.ArkUI.Lite +**System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------------------- | ---- | ---------- | -| options | [RouterOptions](js-apis-router.md#routeroptions) | Yes | Description of the new page. | -| mode | [RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------- | ---- | -------------------- | +| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes | Description of the new page. | +| mode | [router.RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| **Return value** @@ -946,34 +1007,32 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc ```ts let router = uiContext.getRouter(); -router.replaceUrl({ - url: 'pages/detail', - params: { - data1: 'message' - } -}, router.RouterMode.Standard) - .then(() => { - // success - }) - .catch(err => { - console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); - }) +try { + router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message' + } + }, router.RouterMode.Standard) +} catch (err) { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); +} ``` ### replaceUrl -replaceUrl(options: RouterOptions, mode: RouterMode, callback: AsyncCallback<void>): void +replaceUrl(options: router.RouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void Replaces the current page with another one in the application and destroys the current page. -**System capability**: SystemCapability.ArkUI.ArkUI.Lite +**System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | ---------- | -| options | [RouterOptions](js-apis-router.md#routeroptions) | Yes | Description of the new page. | -| mode | [RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| +| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes | Description of the new page. | +| mode | [router.RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** @@ -1005,7 +1064,7 @@ router.replaceUrl({ ### pushNamedRoute -pushNamedRoute(options: NamedRouterOptions): Promise<void> +pushNamedRoute(options: router.NamedRouterOptions): Promise<void> Navigates to a page using the named route. This API uses a promise to return the result. @@ -1013,9 +1072,9 @@ Navigates to a page using the named route. This API uses a promise to return the **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------------------- | ---- | --------- | -| options | [NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Page routing parameters.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | ------------------ | +| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Page routing parameters.| **Return value** @@ -1056,9 +1115,9 @@ router.pushNamedRoute({ ### pushNamedRoute -pushNamedRoute(options: NamedRouterOptions, callback: AsyncCallback<void>): void +pushNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback<void>): void -Navigates to a page using the named route. This API uses an asynchronous callback to return the result. +Navigates to a page using the named route. This API uses a promise to return the result. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -1066,7 +1125,7 @@ Navigates to a page using the named route. This API uses an asynchronous callbac | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | --------- | -| options | [NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Page routing parameters.| +| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Page routing parameters.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** @@ -1101,7 +1160,7 @@ router.pushNamedRoute({ ``` ### pushNamedRoute -pushNamedRoute(options: NamedRouterOptions, mode: RouterMode): Promise<void> +pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): Promise<void> Navigates to a page using the named route. This API uses a promise to return the result. @@ -1109,10 +1168,10 @@ Navigates to a page using the named route. This API uses a promise to return the **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------------------- | ---- | ---------- | -| options | [NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Page routing parameters. | -| mode | [RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | -------------------- | +| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Page routing parameters. | +| mode | [router.RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| **Return value** @@ -1153,9 +1212,9 @@ router.pushNamedRoute({ ### pushNamedRoute -pushNamedRoute(options: NamedRouterOptions, mode: RouterMode, callback: AsyncCallback<void>): void +pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void -Navigates to a page using the named route. This API uses an asynchronous callback to return the result. +Navigates to a page using the named route. This API uses a promise to return the result. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -1163,8 +1222,8 @@ Navigates to a page using the named route. This API uses an asynchronous callbac | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | ---------- | -| options | [NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Page routing parameters. | -| mode | [RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| +| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Page routing parameters. | +| mode | [router.RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** @@ -1200,7 +1259,7 @@ router.pushNamedRoute({ ### replaceNamedRoute -replaceNamedRoute(options: NamedRouterOptions): Promise<void> +replaceNamedRoute(options: router.NamedRouterOptions): Promise<void> Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result. @@ -1208,9 +1267,9 @@ Replaces the current page with another one using the named route and destroys th **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------------------------- | ---- | ------------------ | -| options | [NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Description of the new page.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | ------------------ | +| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Description of the new page.| **Return value** @@ -1224,7 +1283,7 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | if UI execution context not found. | +| 100001 | if UI execution context not found, only throw in standard system. | | 100004 | if the named route is not exist. | **Example** @@ -1247,9 +1306,9 @@ router.replaceNamedRoute({ ### replaceNamedRoute -replaceNamedRoute(options: NamedRouterOptions, callback: AsyncCallback<void>): void +replaceNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback<void>): void -Replaces the current page with another one using the named route and destroys the current page. This API uses an asynchronous callback to return the result. +Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -1257,7 +1316,7 @@ Replaces the current page with another one using the named route and destroys th | Name | Type | Mandatory| Description | | ------- | ------------------------------- | ---- | ------------------ | -| options | [NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Description of the new page.| +| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Description of the new page.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** @@ -1266,7 +1325,7 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | if UI execution context not found. | +| 100001 | if UI execution context not found, only throw in standard system. | | 100004 | if the named route is not exist. | **Example** @@ -1289,7 +1348,7 @@ router.replaceNamedRoute({ ### replaceNamedRoute -replaceNamedRoute(options: NamedRouterOptions, mode: RouterMode): Promise<void> +replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): Promise<void> Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result. @@ -1297,10 +1356,10 @@ Replaces the current page with another one using the named route and destroys th **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------------------- | ---- | ---------- | -| options | [NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Description of the new page. | -| mode | [RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | -------------------- | +| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Description of the new page. | +| mode | [router.RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| **Return value** @@ -1315,7 +1374,7 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | if can not get the delegate. | +| 100001 | if can not get the delegate, only throw in standard system. | | 100004 | if the named route is not exist. | **Example** @@ -1338,9 +1397,9 @@ router.replaceNamedRoute({ ### replaceNamedRoute -replaceNamedRoute(options: NamedRouterOptions, mode: RouterMode, callback: AsyncCallback<void>): void +replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void -Replaces the current page with another one using the named route and destroys the current page. This API uses an asynchronous callback to return the result. +Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -1348,8 +1407,8 @@ Replaces the current page with another one using the named route and destroys th | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | ---------- | -| options | [NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Description of the new page. | -| mode | [RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| +| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Description of the new page. | +| mode | [router.RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** @@ -1358,7 +1417,7 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | if UI execution context not found. | +| 100001 | if UI execution context not found, only throw in standard system. | | 100004 | if the named route is not exist. | **Example** @@ -1381,7 +1440,7 @@ router.replaceNamedRoute({ ### back -back(options?: RouterOptions ): void +back(options?: router.RouterOptions ): void Returns to the previous page or a specified page. @@ -1389,9 +1448,9 @@ Returns to the previous page or a specified page. **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------------------------- | ---- | ------------------------------------------------------------ | -| options | [RouterOptions](js-apis-router.md#routeroptions) | No | Description of the page. The **url** parameter indicates the URL of the page to return to. If the specified page does not exist in the page stack, the application does not respond. If no URL is set, the application returns to the previous page, and the page is not rebuilt. The page in the page stack is not reclaimed. It will be reclaimed after being popped up.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| options | [router.RouterOptions](js-apis-router.md#routeroptions) | No | Description of the page. The **url** parameter indicates the URL of the page to return to. If the specified page does not exist in the page stack, the application does not respond. If no URL is set, the application returns to the previous page, and the page is not rebuilt. The page in the page stack is not reclaimed. It will be reclaimed after being popped up.| **Example** @@ -1439,7 +1498,7 @@ console.log('pages stack size = ' + size); ### getState -getState(): RouterState +getState(): router.RouterState Obtains state information about the current page. @@ -1463,7 +1522,7 @@ console.log('current path = ' + page.path); ### showAlertBeforeBackPage -showAlertBeforeBackPage(options: EnableAlertOptions): void +showAlertBeforeBackPage(options: router.EnableAlertOptions): void Enables the display of a confirm dialog box before returning to the previous page. @@ -1471,9 +1530,9 @@ Enables the display of a confirm dialog box before returning to the previous pag **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ---------------------------------------- | ---- | --------- | -| options | [EnableAlertOptions](js-apis-router.md#enablealertoptions) | Yes | Description of the dialog box.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | ------------------ | +| options | [router.EnableAlertOptions](js-apis-router.md#enablealertoptions) | Yes | Description of the dialog box.| **Error codes** @@ -1487,13 +1546,15 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc ```ts let router = uiContext.getRouter(); -try { - router.showAlertBeforeBackPage({ - message: 'Message Info' - }); -} catch(error) { - console.error(`showAlertBeforeBackPage failed, code is ${error.code}, message is ${error.message}`); -} +router.showAlertBeforeBackPage({ + message: 'Message Info' +}); + .then(() => { + // success + }) + .catch(err => { + console.error(`showAlertBeforeBackPage failed, code is ${error.code}, message is ${error.message}`); + }) ``` ### hideAlertBeforeBackPage @@ -1538,7 +1599,7 @@ In the following API examples, you must first use [getPromptAction()](#getprompt ### showToast -showToast(options: ShowToastOptions): void +showToast(options: promptAction.ShowToastOptions): void Shows a toast. @@ -1546,9 +1607,9 @@ Shows a toast. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------------------------- | ---- | ------- | -| options | [ShowToastOptions](js-apis-promptAction.md#showtoastoptions) | Yes | Toast options.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | -------------- | +| options | [promptAction.ShowToastOptions](js-apis-promptAction.md#showtoastoptions) | Yes | Toast options.| **Error codes** @@ -1574,7 +1635,7 @@ try { ### showDialog -showDialog(options: ShowDialogOptions, callback: AsyncCallback<ShowDialogSuccessResponse<): void +showDialog(options: promptAction.ShowDialogOptions, callback: AsyncCallback<promptAction.ShowDialogSuccessResponse>): void Shows a dialog box. This API uses an asynchronous callback to return the result. @@ -1582,10 +1643,10 @@ Shows a dialog box. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ------------ | -| options | [ShowDialogOptions](js-apis-promptAction.md#showdialogoptions) | Yes | Dialog box options.| -| callback | AsyncCallback<[ShowDialogSuccessResponse](js-apis-promptAction.md#showdialogsuccessresponse)> | Yes | Callback used to return the dialog box response result. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------ | +| options | [promptAction.ShowDialogOptions](js-apis-promptAction.md#showdialogoptions) | Yes | Dialog box options.| +| callback | AsyncCallback<[promptAction.ShowDialogSuccessResponse](js-apis-promptAction.md#showdialogsuccessresponse)> | Yes | Callback used to return the dialog box response result. | **Error codes** @@ -1627,7 +1688,7 @@ try { ### showDialog -showDialog(options: ShowDialogOptions): Promise<ShowDialogSuccessResponse> +showDialog(options: promptAction.ShowDialogOptions): Promise<promptAction.ShowDialogSuccessResponse> Shows a dialog box. This API uses a promise to return the result synchronously. @@ -1635,15 +1696,15 @@ Shows a dialog box. This API uses a promise to return the result synchronously. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | --------------------------------------- | ---- | ------ | -| options | [ShowDialogOptions](js-apis-promptAction.md#showdialogoptions) | Yes | Dialog box options.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | ------------ | +| options | [promptAction.ShowDialogOptions](js-apis-promptAction.md#showdialogoptions) | Yes | Dialog box options.| **Return value** -| Type | Description | -| ---------------------------------------- | -------- | -| Promise<[ShowDialogSuccessResponse](js-apis-promptAction.md#showdialogsuccessresponse)> | Promise used to return the dialog box response result.| +| Type | Description | +| ------------------------------------------------------------ | ---------------- | +| Promise<[promptAction.ShowDialogSuccessResponse](js-apis-promptAction.md#showdialogsuccessresponse)> | Promise used to return the dialog box response result.| **Error codes** @@ -1685,7 +1746,7 @@ try { ### showActionMenu -showActionMenu(options: ActionMenuOptions, callback: AsyncCallback<ActionMenuSuccessResponse>):void +showActionMenu(options: promptAction.ActionMenuOptions, callback:promptAction.ActionMenuSuccessResponse):void Shows an action menu. This API uses an asynchronous callback to return the result. @@ -1693,10 +1754,10 @@ Shows an action menu. This API uses an asynchronous callback to return the resul **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | --------- | -| options | [ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | Yes | Action menu options. | -| callback | AsyncCallback<[ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)> | Yes | Callback used to return the action menu response result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------ | +| options | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | Yes | Action menu options. | +| callback | [promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse) | Yes | Callback used to return the action menu response result.| **Error codes** @@ -1737,7 +1798,7 @@ try { ### showActionMenu -showActionMenu(options: ActionMenuOptions): Promise<ActionMenuSuccessResponse> +showActionMenu(options: promptAction.ActionMenuOptions): Promise<promptAction.ActionMenuSuccessResponse> Shows an action menu. This API uses a promise to return the result synchronously. @@ -1745,15 +1806,15 @@ Shows an action menu. This API uses a promise to return the result synchronously **Parameters** -| Name | Type | Mandatory | Description | -| ------- | --------------------------------------- | ---- | ------- | -| options | [ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | Yes | Action menu options.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | -------------- | +| options | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | Yes | Action menu options.| **Return value** -| Type | Description | -| ---------------------------------------- | ------- | -| Promise<[ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)> | Promise used to return the action menu response result.| +| Type | Description | +| ------------------------------------------------------------ | -------------- | +| Promise<[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)> | Promise used to return the action menu response result.| **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md b/en/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md index 25a6deb575728408b625e3c4f32aadfa05ffe960..818d35f722a41276b4f00fca2f195875f8b9e614 100644 --- a/en/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md +++ b/en/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md @@ -57,7 +57,7 @@ struct Index { Row() { Column() { Image(( (this.resManager.getDrawableDescriptor($r('app.media.icon').id)))) - Image((( (this.resManager.getDrawableDescriptor($r('app.media.drawable') + Image((( (this.resManager.getDrawableDescriptor($r('app.media.icon') .id))).getForeground()).getPixelMap()) }.height('50%') }.width('50%') @@ -80,7 +80,8 @@ Obtains this **pixelMap** object. **Example** ```ts -pixmap: PixelMap = ( (this.resManager.getDrawableDescriptor($r('app.media.icon') +let resManager = getContext().resourceManager +let pixmap: PixelMap = ( (resManager.getDrawableDescriptor($r('app.media.icon') .id))).getPixelMap(); ``` @@ -99,7 +100,8 @@ Obtains the **pixelMap** object where the foreground, background, and mask are b **Example** ```ts -pixmap: PixelMap = ( (this.resManager.getDrawableDescriptor($r('app.media.drawable') +let resManager = getContext().resourceManager +let pixmap: PixelMap = ( (resManager.getDrawableDescriptor($r('app.media.icon') .id))).getPixelMap(); ``` @@ -118,7 +120,8 @@ Obtains the **DrawableDescriptor** object of the foreground. **Example** ```ts -drawable: DrawableDescriptor = ( (this.resManager.getDrawableDescriptor($r('app.media.drawable') +let resManager = getContext().resourceManager +let drawable: DrawableDescriptor = ( (resManager.getDrawableDescriptor($r('app.media.icon') .id))).getForeground(); ``` @@ -137,7 +140,8 @@ Obtains the **DrawableDescriptor** object of the background. **Example** ```ts -drawable: DrawableDescriptor = ( (this.resManager.getDrawableDescriptor($r('app.media.drawable') +let resManager = getContext().resourceManager +let drawable: DrawableDescriptor = ( (resManager.getDrawableDescriptor($r('app.media.icon') .id))).getBackground(); ``` @@ -156,6 +160,26 @@ Obtains the **DrawableDescriptor** object of the mask. **Example** ```ts -drawable: DrawableDescriptor = ( (this.resManager.getDrawableDescriptor($r('app.media.drawable') +let resManager = getContext().resourceManager +let drawable: DrawableDescriptor = ( (resManager.getDrawableDescriptor($r('app.media.icon') .id))).getMask(); ``` +## LayeredDrawableDescriptor.getMaskClipPath +static getMaskClipPath(): string + +Obtains the built-in clipping path parameters of the system. It is a static method of **LayeredDrawableDescriptor**. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| ---------------------------------------- | -------------------- | +| string | String of the clipping path.| + +**Example** + ```ts +Image($r('app.media.icon')) + .width('200px').height('200px') + .clip(new Path({commands:LayeredDrawableDescriptor.getMaskClipPath()})) + ``` diff --git a/en/application-dev/reference/apis/js-apis-base.md b/en/application-dev/reference/apis/js-apis-base.md index 8435c5b922204a5e94a437219564ca3f52520b39..2b7446e510e8b60af714cb39b145dd80228e9cf4 100644 --- a/en/application-dev/reference/apis/js-apis-base.md +++ b/en/application-dev/reference/apis/js-apis-base.md @@ -40,7 +40,7 @@ ErrorCallback\ { Defines a common callback that carries an error parameter. -The error parameter is of the [BusinessError](#businesserror) type. +The information returned by the callback is of the [BusinessError](#businesserror) type. **System capability**: SystemCapability.Base @@ -68,7 +68,7 @@ The type of the asynchronous return value is defined by the developer. | Name| Type | Mandatory| Description | | ---- | ------------------------------------------------------------ | ---- | ---------------------------- | -| err | [BusinessError](https://gitee.com/openharmony/docs/pulls/20172/files#businesserror) | Yes | Common error information about the API invoking failure.| +| err | [BusinessError](#businesserror) | Yes | Common error information about the API invoking failure.| | data | T | Yes | Common callback information. | ## BusinessError diff --git a/en/application-dev/reference/apis/js-apis-curve.md b/en/application-dev/reference/apis/js-apis-curve.md index c09e42bbe96a4dca2c0e5c336fa393ee71423894..6c47da8d85af191fdc7fc4fca312906f97c49d26 100644 --- a/en/application-dev/reference/apis/js-apis-curve.md +++ b/en/application-dev/reference/apis/js-apis-curve.md @@ -41,7 +41,7 @@ Since API version 9, this API is supported in ArkTS widgets. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Description: | +| Name | Description | | ------------------- | ------------------------------------------------------------ | | Linear | The animation speed keeps unchanged. | | Ease | The animation starts slowly, accelerates, and then slows down towards the end. The cubic-bezier curve (0.25, 0.1, 0.25, 1.0) is used.| @@ -78,7 +78,7 @@ Creates a step curve. | Name| Type | Mandatory| Description | | ------ | ------- | ----| ------------------------------------------------------------ | -| count | number | Yes | Number of steps. The value must be a positive integer.
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the value **0**.| +| count | number | Yes | Number of steps. The value must be a positive integer.
Value range: [1, +∞)
**NOTE**
A value less than 1 evaluates to the value **1**.| | end | boolean | Yes | Whether jumping occurs when the interpolation ends.
- **true**: Jumping occurs when the interpolation ends.
- **false**: Jumping occurs when the interpolation starts.| **Return value** @@ -174,7 +174,7 @@ Creates a spring animation curve. If multiple spring animations are applied to t | Name | Type | Mandatory | Description | | --------- | ------ | ---- | ----- | | response | number | No | Duration of one complete oscillation.
Default value: **0.55**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0.55**.| -| dampingFraction | number | No | Damping coefficient.
**0**: undamped. In this case, the spring oscillates forever.
> 0 and < 1: underdamped. In this case, the spring overshoots the equilibrium position.
**1**: critically damped.
> 1: overdamped. In this case, the spring approaches equilibrium gradually.
Default value: **0.825**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0.55**.| +| dampingFraction | number | No | Damping coefficient.
**0**: undamped. In this case, the spring oscillates forever.
> 0 and < 1: underdamped. In this case, the spring overshoots the equilibrium position.
**1**: critically damped.
> 1: overdamped. In this case, the spring approaches equilibrium gradually.
Default value: **0.825**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0.825**.| | overlapDuration | number | No | Duration for animations to overlap, in seconds. When animations overlap, the **response** values of these animations will transit smoothly over this duration if they are different.
Default value: **0**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0**.
The spring animation curve is physics-based. Its duration depends on the **springMotion** parameters and the previous velocity, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). The time cannot be normalized. Therefore, the interpolation cannot be obtained using the **interpolate** function of the curve.| @@ -209,7 +209,7 @@ Creates a responsive spring animation curve. It is a special case of [springMoti | --------- | ------ | ---- | ----- | | response | number | No | See **response** in **springMotion**.
Default value: **0.15**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0.15**.| | dampingFraction | number | No | See **dampingFraction** in **springMotion**.
Default value: **0.86**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0.86**.| -| overlapDuration | number | No | See **overlapDuration** in **springMotion**.
Default value: **0.25**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0.25**.
To apply custom settings for a spring animation, you are advised to use **springMotion**. When using **responsiveSpringMotion**, you are advised to retain the default settings.
The duration of the responsive spring animation depends on the **responsiveSpringMotion** parameters and the previous velocity, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). In addition, the interpolation cannot be obtained using the **interpolate** function of the curve. | +| overlapDuration | number | No | See **overlapDuration** in **springMotion**.
Default value: **0.25**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0.25**.
To apply custom settings for a spring animation, you are advised to use **springMotion**. When using **responsiveSpringMotion**, you are advised to retain the default settings.
The duration of the responsive spring animation depends on the **responsiveSpringMotion** parameters and the previous velocity, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). In addition, the interpolation cannot be obtained using the **interpolate** function of the curve.| **Return value** @@ -237,16 +237,16 @@ Creates an interpolating spring curve animated from 0 to 1. The actual animation **Parameters** | Name | Type | Mandatory | Description | | --------- | ------ | ---- | ----- | -| velocity | number | Yes | Initial velocity. It is applied by external factors to the spring animation, designed to help ensure the smooth transition from the previous motion state. The velocity is the normalized velocity, and its value is equal to the actual velocity at the beginning of the animation divided by the animation attribute change value.| -| mass | number | Yes | Mass, which influences the inertia in the spring system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.| -| stiffness | number | Yes | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position.| -| damping | number | Yes | Damping. It is a pure number and has no real physical meaning. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion, and the smaller the oscillation amplitude.| +| velocity | number | Yes | Initial velocity. It is applied by external factors to the spring animation, designed to help ensure the smooth transition from the previous motion state. The velocity is the normalized velocity, and its value is equal to the actual velocity at the beginning of the animation divided by the animation attribute change value.
Value range: (-∞, +∞)| +| mass | number | Yes | Mass, which influences the inertia in the spring system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the value **1**.| +| stiffness | number | Yes | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position.
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the value **1**.| +| damping | number | Yes | Damping. It is a pure number and has no real physical meaning. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion, and the smaller the oscillation amplitude.
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the value **1**.| **Return value** | Type | Description | | ---------------------------------- | ---------------- | -| [ICurve](#icurve)| Interpolation curve.| +| [ICurve](#icurve)| Curve.
**NOTE**
The spring animation curve is physics-based. Its duration depends on the** interpolatingSpring** parameters, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). The time cannot be normalized. Therefore, the interpolation cannot be obtained using the [interpolate](#interpolate9) function of the curve.| **Example** @@ -279,10 +279,10 @@ Creates a custom curve. ```ts import Curves from '@ohos.curves' -interpolate(fraction) { - return Math.sqrt(fraction); +let interpolate = function(fraction) { + return Math.sqrt(fraction) } -private curve = Curves.customCurve(this.interpolate) // Create a custom curve. +let curve = Curves.customCurve(interpolate) // Create a custom interpolation curve. ``` @@ -316,7 +316,7 @@ Since API version 9, this API is supported in ArkTS widgets. ```ts import Curves from '@ohos.curves' -let curve = Curves.initCurve(Curve.EaseIn) // Create an ease-in curve. +let curveValue = Curves.initCurve(Curve.EaseIn) // Create an ease-in curve. let value: number = curve.interpolate(0.5) // Calculate the interpolation for half of the time. ``` diff --git a/en/application-dev/reference/apis/js-apis-data-relationalStore.md b/en/application-dev/reference/apis/js-apis-data-relationalStore.md index 8d30126fec7cf31a42a9ae3bacf5d66db8b83238..cc77cf104bf296e0ef08ba948f2e47c537d73be8 100644 --- a/en/application-dev/reference/apis/js-apis-data-relationalStore.md +++ b/en/application-dev/reference/apis/js-apis-data-relationalStore.md @@ -577,7 +577,7 @@ Defines the data types allowed. ## ValuesBucket -Defines the types of the key and value in a KV pair. This type is not multi-thread safe. If a **ValuesBucket** instance is operated by multiple threads at the same time in an application, use a lock for the instance. +Enumerates the types of the key in a KV pair. This type is not multi-thread safe. If a **ValuesBucket** instance is operated by multiple threads at the same time in an application, use a lock for the instance. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -587,13 +587,14 @@ Defines the types of the key and value in a KV pair. This type is not multi-thre ## PRIKeyType10+ -Represents the type of the primary key in a row of a database table. +Enumerates the types of the primary key in a row of a database table. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core | Type | Description | | ---------------- | ---------------------------------- | -| number \| string | The type of the primary key can be number or string.| +| number | The primary key is a number.| +| string | The primary key is a string.| ## UTCTime10+ @@ -798,7 +799,8 @@ Sets an **RdbPredicates** to specify the remote devices to connect on the networ > **NOTE** > -> The value of **devices** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> The value of **devices** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). +If **inDevices** is specified in **predicates** when **sync()** is called, data is synchronized with the specified device. If **inDevices** is not specified, data is synchronized with all devices on the network by default. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -817,22 +819,20 @@ Sets an **RdbPredicates** to specify the remote devices to connect on the networ **Example** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; +import deviceManager from '@ohos.distributedDeviceManager'; let dmInstance = null; let deviceIds = []; -deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { - if (err) { - console.log("create device manager failed, err=" + err); - return; - } - dmInstance = manager; - let devices = dmInstance.getTrustedDeviceListSync(); - for (var i = 0; i < devices.length; i++) { - deviceIds[i] = devices[i].deviceId; - } -}) - +try { + dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); + let devices = dmInstance.getAvailableDeviceListSync(); + for (var i = 0; i < devices.length; i++) { + deviceIds[i] = devices[i].networkId; + } +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} + let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.inDevices(deviceIds); ``` @@ -844,6 +844,7 @@ inAllDevices(): RdbPredicates Sets an **RdbPredicates** to specify all remote devices on the network to connect during distributed database synchronization. + **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** @@ -2733,7 +2734,7 @@ Queries data from the RDB store of a remote device based on specified conditions > **NOTE** > -> The value of **device** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> The value of **device** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -2758,19 +2759,17 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; +import deviceManager from '@ohos.distributedDeviceManager'; let dmInstance = null; let deviceId = null; -deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { - if (err) { - console.log("create device manager failed, err=" + err); - return; - } - dmInstance = manager; - let devices = dmInstance.getTrustedDeviceListSync(); - deviceId = devices[0].deviceId; -}) +try { + dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); + let devices = dmInstance.getAvailableDeviceListSync(); + deviceId = devices[0].networkId; +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); predicates.greaterThan("id", 0); @@ -2803,7 +2802,7 @@ Queries data from the RDB store of a remote device based on specified conditions > **NOTE** > -> The value of **device** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> The value of **device** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -2833,19 +2832,17 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; +import deviceManager from '@ohos.distributedDeviceManager'; let dmInstance = null; let deviceId = null; -deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { - if (err) { - console.log("create device manager failed, err=" + err); - return; - } - dmInstance = manager; - let devices = dmInstance.getTrustedDeviceListSync(); - deviceId = devices[0].deviceId; -}) +try { + dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); + let devices = dmInstance.getAvailableDeviceListSync(); + deviceId = devices[0].networkId; +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); predicates.greaterThan("id", 0); @@ -3586,6 +3583,8 @@ store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIB }) ``` + + ### setDistributedTables10+ setDistributedTables(tables: Array<string>, type: DistributedType, config: DistributedConfig, callback: AsyncCallback<void>): void @@ -3682,7 +3681,7 @@ Obtains the distributed table name of a remote device based on the local table n > **NOTE** > -> The value of **device** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> The value of **device** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -3707,19 +3706,17 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; +import deviceManager from '@ohos.distributedDeviceManager'; let dmInstance = null; let deviceId = null; -deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { - if (err) { - console.log("create device manager failed, err=" + err); - return; - } - dmInstance = manager; - let devices = dmInstance.getTrustedDeviceListSync(); - deviceId = devices[0].deviceId; -}) +try { + dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); + let devices = dmInstance.getAvailableDeviceListSync(); + deviceId = devices[0].networkId; +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} store.obtainDistributedTableName(deviceId, "EMPLOYEE", function (err, tableName) { if (err) { @@ -3738,7 +3735,7 @@ Obtains the distributed table name of a remote device based on the local table n > **NOTE** > -> The value of **device** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> The value of **device** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -3768,19 +3765,17 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; +import deviceManager from '@ohos.distributedDeviceManager'; let dmInstance = null; let deviceId = null; -deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { - if (err) { - console.log("create device manager failed, err=" + err); - return; - } - dmInstance = manager; - let devices = dmInstance.getTrustedDeviceListSync(); - deviceId = devices[0].deviceId; -}) +try { + dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); + let devices = dmInstance.getAvailableDeviceListSync(); + deviceId = devices[0].networkId; +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} let promise = store.obtainDistributedTableName(deviceId, "EMPLOYEE"); promise.then((tableName) => { @@ -3819,21 +3814,19 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; +import deviceManager from '@ohos.distributedDeviceManager'; let dmInstance = null; let deviceIds = []; -deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { - if (err) { - console.log("create device manager failed, err=" + err); - return; - } - dmInstance = manager; - let devices = dmInstance.getTrustedDeviceListSync(); - for (var i = 0; i < devices.length; i++) { - deviceIds[i] = devices[i].deviceId; - } -}) +try { + dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); + let devices = dmInstance.getAvailableDeviceListSync(); + for (var i = 0; i < devices.length; i++) { + deviceIds[i] = devices[i].networkId; + } +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); predicates.inDevices(deviceIds); @@ -3883,21 +3876,19 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; +import deviceManager from '@ohos.distributedDeviceManager'; let dmInstance = null; let deviceIds = []; -deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { - if (err) { - console.log("create device manager failed, err=" + err); - return; - } - dmInstance = manager; - let devices = dmInstance.getTrustedDeviceListSync(); - for (var i = 0; i < devices.length; i++) { - deviceIds[i] = devices[i].deviceId; - } -}) +try { + dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); + let devices = dmInstance.getAvailableDeviceListSync(); + for (var i = 0; i < devices.length; i++) { + deviceIds[i] = devices[i].networkId; + } +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); predicates.inDevices(deviceIds); @@ -4129,7 +4120,7 @@ Registers an intra-process or inter-process event listener for the RDB store. Th | Name | Type | Mandatory| Description | | ------------ | --------------- | ---- | ------------------------------------------------------------ | | event | string | Yes | Event name to observe. | -| interProcess | boolean | Yes | Type of the event to observe.
The value **true** means the inter-process event.
The value **false** means the intra-process event. | +| interProcess | boolean | Yes | Type of the event to observe.
The value **true** means the inter-process event.
The value **false** means the intra-process event.| | observer | Callback\ | Yes | Callback invoked to return the result. | **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-devicestatus-draginteraction.md b/en/application-dev/reference/apis/js-apis-devicestatus-draginteraction.md index 01b50c8fc58606caf233a011df6e5bdc86eb2b80..8eba8e2a29d2b80ec3bcbf2ec51a3ba43036da4b 100644 --- a/en/application-dev/reference/apis/js-apis-devicestatus-draginteraction.md +++ b/en/application-dev/reference/apis/js-apis-devicestatus-draginteraction.md @@ -1,4 +1,4 @@ -# @ohos. deviceStatus.dragInteraction (Drag) +# @ohos.deviceStatus.dragInteraction (Drag) The **dragInteraction** module provides the APIs to enable and disable listening for dragging status changes. @@ -14,7 +14,7 @@ import dragInteraction from '@ohos.deviceStatus.dragInteraction' ``` -## dragInteraction.on +## dragInteraction.on('drag') on(type: 'drag', callback: Callback<DragState>): void; @@ -41,7 +41,7 @@ try { } ``` -## dragInteraction.off +## dragInteraction.off('drag') off(type: 'drag', callback?: Callback<DragState>): void; diff --git a/en/application-dev/reference/apis/js-apis-distributedKVStore.md b/en/application-dev/reference/apis/js-apis-distributedKVStore.md index 6cde0cf71b73660bf168b36feac2805753f08b79..2a4e91e3d798268e945744cf2c3d90755357dd32 100644 --- a/en/application-dev/reference/apis/js-apis-distributedKVStore.md +++ b/en/application-dev/reference/apis/js-apis-distributedKVStore.md @@ -12,8 +12,7 @@ The **distributedKVStore** module provides the following functions: > **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. -> - All the APIs that need to obtain **deviceId** in this module are available only to system applications. +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -2030,7 +2029,7 @@ deviceId(deviceId:string):Query Creates a **Query** object with the device ID as the key prefix. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2819,7 +2818,7 @@ removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void Deletes data of a device. This API uses an asynchronous callback to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -2871,7 +2870,7 @@ removeDeviceData(deviceId: string): Promise<void> Deletes data of a device. This API uses a promise to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4550,7 +4549,7 @@ sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void Synchronizes the KV store manually. For details about the synchronization modes of KV stores, see [Cross-Device Synchronization of KV Stores](../../database/data-sync-of-kv-store.md). > **NOTE** > -> **deviceIds** is the **networkId** in [DeviceInfo](js-apis-device-manager.md#deviceinfo), which is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceIds** is **networkId** in [DeviceBasicInfo](js-apis-distributedDeviceManager.md#devicebasicinfo), which can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -4576,40 +4575,41 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err **Example** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; +import deviceManager from '@ohos.distributedDeviceManager'; let devManager; const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; // create deviceManager -deviceManager.createDeviceManager('bundleName', (err, value) => { - if (!err) { - devManager = value; - let deviceIds = []; - if (devManager != null) { - var devices = devManager.getTrustedDeviceListSync(); - for (var i = 0; i < devices.length; i++) { - deviceIds[i] = devices[i].networkId; - } - } - try { - kvStore.on('syncComplete', function (data) { - console.info('Sync dataChange'); - }); - kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err) { - if (err != undefined) { - console.error(`Failed to sync.code is ${err.code},message is ${err.message}`); - return; - } - console.info('Succeeded in putting data'); - const mode = distributedKVStore.SyncMode.PULL_ONLY; - kvStore.sync(deviceIds, mode, 1000); - }); - } catch (e) { - console.error(`Failed to sync.code is ${e.code},message is ${e.message}`); +try { + devManager = deviceManager.createDeviceManager(context.applicationInfo.name); + let deviceIds = []; + if (devManager != null) { + var devices = devManager.getAvailableDeviceListSync(); + for (var i = 0; i < devices.length; i++) { + deviceIds[i] = devices[i].networkId; } } -}); + try { + kvStore.on('syncComplete', function (data) { + console.info('Sync dataChange'); + }); + kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err) { + if (err != undefined) { + console.error(`Failed to sync.code is ${err.code},message is ${err.message}`); + return; + } + console.info('Succeeded in putting data'); + const mode = distributedKVStore.SyncMode.PULL_ONLY; + kvStore.sync(deviceIds, mode, 1000); + }); + } catch (e) { + console.error(`Failed to sync.code is ${e.code},message is ${e.message}`); + } + +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} ``` ### sync @@ -4619,7 +4619,7 @@ sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of KV stores, see [Cross-Device Synchronization of KV Stores](../../database/data-sync-of-kv-store.md). > **NOTE** > -> **deviceIds** is the **networkId** in [DeviceInfo](js-apis-device-manager.md#deviceinfo), which is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceIds** is **networkId** in [DeviceBasicInfo](js-apis-distributedDeviceManager.md#devicebasicinfo), which can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -4646,43 +4646,44 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err **Example** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; +import deviceManager from '@ohos.distributedDeviceManager'; let devManager; const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; // create deviceManager -deviceManager.createDeviceManager('bundleName', (err, value) => { - if (!err) { - devManager = value; - let deviceIds = []; - if (devManager != null) { - var devices = devManager.getTrustedDeviceListSync(); - for (var i = 0; i < devices.length; i++) { - deviceIds[i] = devices[i].networkId; - } - } - try { - kvStore.on('syncComplete', function (data) { - console.info('Sync dataChange'); - }); - kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err) { - if (err != undefined) { - console.error(`Failed to sync.code is ${err.code},message is ${err.message}`); - return; - } - console.info('Succeeded in putting data'); - const mode = distributedKVStore.SyncMode.PULL_ONLY; - const query = new distributedKVStore.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - kvStore.sync(deviceIds, query, mode, 1000); - }); - } catch (e) { - console.error(`Failed to sync.code is ${e.code},message is ${e.message}`); +try { + let devManager = deviceManager.createDeviceManager(context.applicationInfo.name); + let deviceIds = []; + if (devManager != null) { + var devices = devManager.getAvailableDeviceListSync(); + for (var i = 0; i < devices.length; i++) { + deviceIds[i] = devices[i].networkId; } } -}); + try { + kvStore.on('syncComplete', function (data) { + console.info('Sync dataChange'); + }); + kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err) { + if (err != undefined) { + console.error(`Failed to sync.code is ${err.code},message is ${err.message}`); + return; + } + console.info('Succeeded in putting data'); + const mode = distributedKVStore.SyncMode.PULL_ONLY; + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + query.deviceId(devManager.getLocalDeviceNetworkId()); + kvStore.sync(deviceIds, query, mode, 1000); + }); + } catch (e) { + console.error(`Failed to sync.code is ${e.code},message is ${e.message}`); + } + +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} ``` ### on('dataChange') @@ -5046,7 +5047,7 @@ get(deviceId: string, key: string, callback: AsyncCallback<boolean | string | Obtains a string value that matches the specified device ID and key. This API uses an asynchronous callback to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5101,7 +5102,7 @@ get(deviceId: string, key: string): Promise<boolean | string | number | Uint8 Obtains a string value that matches the specified device ID and key. This API uses a promise to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5281,7 +5282,7 @@ getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry Obtains all KV pairs that match the specified device ID and key prefix. This API uses an asynchronous callback to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5348,7 +5349,7 @@ getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]> Obtains all KV pairs that match the specified device ID and key prefix. This API uses a promise to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5544,7 +5545,7 @@ getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]> Obtains the KV pairs that match the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5616,7 +5617,7 @@ getEntries(deviceId: string, query: Query): Promise<Entry[]> Obtains the KV pairs that match the specified device ID and **Query** object. This API uses a promise to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5824,7 +5825,7 @@ getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KVS Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses an asynchronous callback to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5879,7 +5880,7 @@ getResultSet(deviceId: string, keyPrefix: string): Promise<KVStoreResultSet&g Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses a promise to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5935,7 +5936,7 @@ getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KVStoreR Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -6011,7 +6012,7 @@ getResultSet(deviceId: string, query: Query): Promise<KVStoreResultSet> Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -6154,7 +6155,7 @@ getResultSet(query: Query, callback:AsyncCallback<KVStoreResultSet>): void Obtains a **KVStoreResultSet** object that matches the specified **Query** object for this device. This API uses an asynchronous callback to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -6343,7 +6344,7 @@ getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicat Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses an asynchronous callback to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System API**: This is a system API. @@ -6404,7 +6405,7 @@ getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicat Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses a promise to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System API**: This is a system API. @@ -6585,7 +6586,7 @@ getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number& Obtains the number of results that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -6651,7 +6652,7 @@ getResultSize(deviceId: string, query: Query): Promise<number> Obtains the number of results that matches the specified device ID and **Query** object. This API uses a promise to return the result. > **NOTE** > -> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). > For details about how to obtain **deviceId**, see [sync()](#sync). **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore diff --git a/en/application-dev/reference/apis/js-apis-file-picker.md b/en/application-dev/reference/apis/js-apis-file-picker.md index b8572f3bf4df0d6a60b5f7835ac1bf9346d19b1f..5b2efaad03192b5a7492411ac91e6f633858866a 100644 --- a/en/application-dev/reference/apis/js-apis-file-picker.md +++ b/en/application-dev/reference/apis/js-apis-file-picker.md @@ -138,7 +138,7 @@ async function example() { save(option?: PhotoSaveOptions) : Promise<Array<string>> -Saves one or more images or videos in a **photoPicker** page. This API uses a promise to return the result. You can pass in **PhotoSaveOptions** to specify the file names of the images or videos to save. The **save()** API saves the file in the file manager, not in the Gallery. +Saves one or more images or videos in a **photoPicker** page. This API uses a promise to return the result. You can pass in **PhotoSaveOptions** to specify the file names of the images or videos to save. The **save()** API saves files in the file manager, not in **Gallery**. **System capability**: SystemCapability.FileManagement.UserFileService @@ -177,7 +177,7 @@ async function example() { save(option: PhotoSaveOptions, callback: AsyncCallback<Array<string>>) : void -Saves one or more images or videos in a **photoPicker** page. This API uses an asynchronous callback to return the result. You can pass in **PhotoSaveOptions** to specify the file names of the images or videos to save. The **save()** API saves the file in the file manager, not in the Gallery. +Saves one or more images or videos in a **photoPicker** page. This API uses an asynchronous callback to return the result. You can pass in **PhotoSaveOptions** to specify the file names of the images or videos to save. The **save()** API saves files in the file manager, not in **Gallery**. **System capability**: SystemCapability.FileManagement.UserFileService @@ -213,7 +213,7 @@ async function example() { save(callback: AsyncCallback<Array<string>>) : void -Saves one or more images or videos in a **photoPicker** page. This API uses an asynchronous callback to return the result. The **save()** API saves the file in the file manager, not in the Gallery. +Saves one or more images or videos in a **photoPicker** page. This API uses an asynchronous callback to return the result. The **save()** API saves files in the file manager, not in **Gallery**. **System capability**: SystemCapability.FileManagement.UserFileService @@ -244,7 +244,7 @@ async function example() { ## DocumentViewPicker -Provides APIs for selecting and saving non-media files, for example, documents in a variety of formats. Before using the APIs of **DocumentViewPicker**, you need to create a **DocumentViewPicker** instance. +Provides the **DocumentViewPicker** object for selecting and saving documents in different formats. Before using the APIs of **DocumentViewPicker**, you need to create a **DocumentViewPicker** instance. **System capability**: SystemCapability.FileManagement.UserFileService @@ -715,8 +715,8 @@ Defines the options for selecting images or videos. | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | -------------------------------- | -| MIMEType? | [PhotoViewMIMETypes](#photoviewmimetypes) | No | Available media file types. **IMAGE_VIDEO_TYPE** is used by default.| -| maxSelectNumber? | number | No | Maximum number of media files to select. The default value is **50**, and the maximum value is **500**. | +| MIMEType | [PhotoViewMIMETypes](#photoviewmimetypes) | No | Available media file types. **IMAGE_VIDEO_TYPE** is used by default.| +| maxSelectNumber | number | No | Maximum number of media files to select. The default value is **50**, and the maximum value is **500**. | ## PhotoSelectResult @@ -737,14 +737,20 @@ Defines the options for saving images or videos. | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | ---------------------------- | -| newFileNames? | Array<string> | No | Names of the files to save. If this parameter is not specified, the user needs to enter the file names.| +| newFileNames | Array<string> | No | Names of the files to save. If this parameter is not specified, the user needs to enter the file names.| ## DocumentSelectOptions -Defines the options for selecting documents. Currently, this parameter cannot be configured. +Defines the options for selecting documents. **System capability**: SystemCapability.FileManagement.UserFileService +| Name | Type | Mandatory| Description | +| ----------------------- | ------------------- | ---- | -------------------------------- | +| maxSelectNumber | number | No | Maximum number of files or directories that can be selected.
Value range: 1–500
Maximum value: **500** | +| defaultFilePathUri | string | No | Path of the file or directory to select.| +| fileSuffixFilters | Array<string> | No | File name extensions of the documents to select.| + ## DocumentSaveOptions Defines the options for saving documents. @@ -753,7 +759,9 @@ Defines the options for saving documents. | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | ---------------------------- | -| newFileNames? | Array<string> | No | Names of the documents to save. If this parameter is not specified, the user needs to enter the document names. | +| newFileNames | Array<string> | No | Names of the documents to save. If this parameter is not specified, the user needs to enter the document names. | +| defaultFilePathUri | string | No | Path of the file or directory to save.| +| fileSuffixChoices | Array<string> | No | File name extensions of the documents to save.| ## AudioSelectOptions @@ -769,4 +777,4 @@ Defines the options for saving audio files. | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | ---------------------------- | -| newFileNames? | Array<string> | No | Name of the audio files to save. If this parameter is not specified, the user needs to enter the file names.| +| newFileNames | Array<string> | No | Name of the audio files to save. If this parameter is not specified, the user needs to enter the file names.| diff --git a/en/application-dev/reference/apis/js-apis-font.md b/en/application-dev/reference/apis/js-apis-font.md index f63ae0b839e472b9b6c11db6b6da4684507b11c6..6ed6b13fbe3c9e05d9fb0afb1c802770fe7044d1 100644 --- a/en/application-dev/reference/apis/js-apis-font.md +++ b/en/application-dev/reference/apis/js-apis-font.md @@ -54,7 +54,7 @@ struct FontExample { // Both familyName and familySrc support the string type. font.registerFont({ familyName: 'medium', - familySrc: '/font/medium.ttf' + familySrc: '/font/medium.ttf' // The font file is at the same level as the pages directory. }) // Both familyName and familySrc support the Resource type. @@ -138,7 +138,7 @@ Obtains information about a system font based on the font name. | ---------------- | ---------------------------- | | FontInfo | Information about the system font. | -## FontInfo +## FontInfo10+ **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -170,7 +170,7 @@ struct FontExample { Column() { Button("getFontByName") .onClick(() => { - this.fontInfo = font.getFontByName('HarmonyOS Sans Italic') + this.fontInfo = font.getFontByName('Sans Italic') console.log("getFontByName(): path = " + this.fontInfo.path) console.log("getFontByName(): postScriptName = " + this.fontInfo.postScriptName) console.log("getFontByName(): fullName = " + this.fontInfo.fullName) diff --git a/en/application-dev/reference/apis/js-apis-mindSporeLite.md b/en/application-dev/reference/apis/js-apis-mindSporeLite.md index 6a80afa3976c1ee8c4fdce9e3ffa0e1288fdd62c..499ce6a24deb7cbcd6c380a26f559a4413fd5989 100644 --- a/en/application-dev/reference/apis/js-apis-mindSporeLite.md +++ b/en/application-dev/reference/apis/js-apis-mindSporeLite.md @@ -1,7 +1,7 @@ # @ohos.ai.mindSporeLite (Inference) MindSpore Lite is an AI engine that implements AI model inference for different hardware devices. It has been used in a wide range of fields, such as image classification, target recognition, facial recognition, and character recognition. -The **mindSporeLite** module provides APIs for the MindSpore Lite inference engine to implment model inference. +The **mindSporeLite** module provides APIs for the MindSpore Lite inference engine to implement model inference. > **NOTE** > @@ -48,7 +48,7 @@ Defines the CPU backend device option. | threadNum | number | Yes | Yes | Number of runtime threads. The default value is **2**. | | threadAffinityMode | [ThreadAffinityMode](#threadaffinitymode) | Yes | Yes | Affinity mode for binding runtime threads to CPU cores. The default value is **mindSporeLite.ThreadAffinityMode.NO_AFFINITIES**.| | threadAffinityCoreList | number[] | Yes | Yes | List of CPU cores bound to runtime threads. Set this parameter only when **threadAffinityMode** is set. If **threadAffinityMode** is set to **mindSporeLite.ThreadAffinityMode.NO_AFFINITIES**, this parameter is empty. The number in the list indicates the SN of the CPU core. The default value is **[]**.| -| precisionMode | string | Yes | Yes | Whether to enable the Float16 inference mode. The value **preferred_fp16** means to enable half-precision inference and the default value **force_fp32** means to disable half-precision inference. Other settings are not supported.| +| precisionMode | string | Yes | Yes | Whether to enable the Float16 inference mode. The value **preferred_fp16** means to enable half-precision inference and the default value **enforce_fp32** means to disable half-precision inference. Other settings are not supported.| **Float16 inference mode**: a mode that uses half-precision inference. Float16 uses 16 bits to represent a number and therefore it is also called half-precision. @@ -125,7 +125,7 @@ Loads the input model from the full path for model inference. This API uses an a ```js let context: mindSporeLite.Context = {}; -let context = {'target': ['cpu']}; +context = {'target': ['cpu']}; let model_file = '/path/to/xxx.ms'; mindSporeLite.loadModelFromFile(model_file, context, (result) => { const modelInputs = result.getInputs(); @@ -181,17 +181,17 @@ Loads the input model from the memory for inference. This API uses an asynchrono ```js import resourceManager from '@ohos.resourceManager' -@State modelName: string = 'xxx.ms'; +let modelName = '/path/to/xxx.ms'; let syscontext = globalThis.context; -syscontext.resourceManager.getRawFileContent(this.modelName).then((buffer) => { - this.modelBuffer = buffer; +syscontext.resourceManager.getRawFileContent(modelName).then((buffer) => { + let modelBuffer = buffer; + mindSporeLite.loadModelFromBuffer(modelBuffer.buffer, (result) => { + const modelInputs = result.getInputs(); + console.log(modelInputs[0].name); + }) }).catch(error => { console.error('Failed to get buffer, error code: ${error.code},message:${error.message}.'); }) -mindSporeLite.loadModelFromBuffer(this.modelBuffer.buffer, (result) => { - const modelInputs = result.getInputs(); - console.log(modelInputs[0].name); -}) ``` ## mindSporeLite.loadModelFromBuffer @@ -213,19 +213,19 @@ Loads the input model from the memory for inference. This API uses an asynchrono ```js import resourceManager from '@ohos.resourceManager' -@State modelName: string = 'xxx.ms'; +let modelName = '/path/to/xxx.ms'; let syscontext = globalThis.context; -syscontext.resourceManager.getRawFileContent(this.modelName).then((error,buffer) => { - this.modelBuffer = buffer; +syscontext.resourceManager.getRawFileContent(modelName).then((error,buffer) => { + let modelBuffer = buffer; + let context: mindSporeLite.Context = {}; + context = {'target': ['cpu']}; + mindSporeLite.loadModelFromBuffer(modelBuffer.buffer, context, (result) => { + const modelInputs = result.getInputs(); + console.log(modelInputs[0].name); + }) }).catch(error => { console.error('Failed to get buffer, error code: ${error.code},message:${error.message}.'); }) -let context: mindSporeLite.Context = {}; -context = {'target': ['cpu']}; -mindSporeLite.loadModelFromBuffer(this.modelBuffer.buffer, context, (result) => { - const modelInputs = result.getInputs(); - console.log(modelInputs[0].name); -}) ``` ## mindSporeLite.loadModelFromBuffer @@ -252,17 +252,17 @@ Loads the input model from the memory for inference. This API uses a promise to ```js import resourceManager from '@ohos.resourceManager' -@State modelName: string = 'xxx.ms'; +let modelName = '/path/to/xxx.ms'; let syscontext = globalThis.context; -syscontext.resourceManager.getRawFileContent(this.modelName).then((buffer) => { - this.modelBuffer = buffer; +syscontext.resourceManager.getRawFileContent(modelName).then((buffer) => { + let modelBuffer = buffer; + mindSporeLite.loadModelFromBuffer(modelBuffer.buffer).then((result) => { + const modelInputs = result.getInputs(); + console.log(modelInputs[0].name); + }) }).catch(error => { console.error('Failed to get buffer, error code: ${error.code},message:${error.message}.'); }) -mindSporeLite.loadModelFromBuffer(model_file).then((result) => { - const modelInputs = result.getInputs(); - console.log(modelInputs[0].name); -}) ``` ## mindSporeLite.loadModelFromFd @@ -284,7 +284,7 @@ Loads the input model based on the specified file descriptor for inference. This ```js import fs from '@ohos.file.fs'; let model_file = '/path/to/xxx.ms'; -let file = await fs.open(model_file, 0); +let file = fs.openSync(model_file, fs.OpenMode.READ_ONLY); mindSporeLite.loadModelFromFd(file.fd, (result) => { const modelInputs = result.getInputs(); console.log(modelInputs[0].name); @@ -313,7 +313,7 @@ import fs from '@ohos.file.fs'; let model_file = '/path/to/xxx.ms'; let context : mindSporeLite.Context = {}; context = {'target': ['cpu']}; -let file = await fs.open(model_file, 0); +let file = fs.openSync(model_file, fs.OpenMode.READ_ONLY); mindSporeLite.loadModelFromFd(file.fd, context, (result) => { const modelInputs = result.getInputs(); console.log(modelInputs[0].name); @@ -345,7 +345,7 @@ Loads the input model based on the specified file descriptor for inference. This ```js import fs from '@ohos.file.fs'; let model_file = '/path/to/xxx.ms'; -let file = await fs.open(model_file, 0); +let file = fs.openSync(model_file, fs.OpenMode.READ_ONLY); let mindSporeLiteModel = await mindSporeLite.loadModelFromFd(file.fd); mindSporeLite.loadModelFromFd(file.fd).then((result) => { const modelInputs = result.getInputs(); @@ -383,9 +383,9 @@ mindSporeLite.loadModelFromFile(model_file).then((result) => { ``` ### predict -predict(inputs: MSTensor[], callback: Callback<Model>): void +predict(inputs: MSTensor[], callback: Callback<MSTensor[]>): void -Executes the inference model. This API uses an asynchronous callback to return the result. +Executes the inference model. This API uses an asynchronous callback to return the result. Ensure that the model object is not reclaimed when being invoked. **System capability**: SystemCapability.AI.MindSporeLite @@ -394,21 +394,21 @@ Executes the inference model. This API uses an asynchronous callback to return t | Name| Type | Mandatory| Description | | ------ | ----------------------- | ---- | -------------------------- | | inputs | [MSTensor](#mstensor)[] | Yes | Model input, which is an **MSTensor** object.| -| callback | Callback<[Model](#model)> | Yes | Callback used to return the result, which is a **Model** object.| +| callback | Callback<[MSTensor](#mstensor)[]> | Yes | Callback used to return the result, **MSTensor** object.| **Example** ```js import resourceManager from '@ohos.resourceManager' -@State inputName: string = 'input_data.bin'; +let inputName = 'input_data.bin'; let syscontext = globalThis.context; -syscontext.resourceManager.getRawFileContent(this.inputName).then((buffer) => { - this.inputBuffer = buffer; +syscontext.resourceManager.getRawFileContent(inputName).then(async (buffer) => { + let inputBuffer = buffer; let model_file = '/path/to/xxx.ms'; let mindSporeLiteModel = await mindSporeLite.loadModelFromFile(model_file); const modelInputs = mindSporeLiteModel.getInputs(); - modelInputs[0].setData(this.inputBuffer.buffer); - result.predict(modelInputs, (result) => { + modelInputs[0].setData(inputBuffer.buffer); + mindSporeLiteModel.predict(modelInputs, (result) => { let output = new Float32Array(result[0].getData()); for (let i = 0; i < output.length; i++) { console.log(output[i].toString()); @@ -420,7 +420,7 @@ syscontext.resourceManager.getRawFileContent(this.inputName).then((buffer) => { predict(inputs: MSTensor[]): Promise<MSTensor[]> -Executes the inference model. This API uses a promise to return the result. +Executes the inference model. This API uses a promise to return the result. Ensure that the model object is not reclaimed when being invoked. **System capability**: SystemCapability.AI.MindSporeLite @@ -440,15 +440,15 @@ Executes the inference model. This API uses a promise to return the result. ```js import resourceManager from '@ohos.resourceManager' -@State inputName: string = 'input_data.bin'; +let inputName = 'input_data.bin'; let syscontext = globalThis.context; -syscontext.resourceManager.getRawFileContent(this.inputName).then((buffer) => { - this.inputBuffer = buffer; +syscontext.resourceManager.getRawFileContent(inputName).then(async (buffer) => { + let inputBuffer = buffer; let model_file = '/path/to/xxx.ms'; let mindSporeLiteModel = await mindSporeLite.loadModelFromFile(model_file); const modelInputs = mindSporeLiteModel.getInputs(); - modelInputs[0].setData(this.inputBuffer.buffer); - result.predict(modelInputs).then((result) => { + modelInputs[0].setData(inputBuffer.buffer); + mindSporeLiteModel.predict(modelInputs).then((result) => { let output = new Float32Array(result[0].getData()); for (let i = 0; i < output.length; i++) { console.log(output[i].toString()); @@ -541,15 +541,15 @@ Obtains tensor data. ```js import resourceManager from '@ohos.resourceManager' -@State inputName: string = 'input_data.bin'; +let inputName = 'input_data.bin'; let syscontext = globalThis.context; -syscontext.resourceManager.getRawFileContent(this.inputName).then((buffer) => { - this.inputBuffer = buffer; +syscontext.resourceManager.getRawFileContent(inputName).then(async (buffer) => { + let inputBuffer = buffer; let model_file = '/path/to/xxx.ms'; let mindSporeLiteModel = await mindSporeLite.loadModelFromFile(model_file); const modelInputs = mindSporeLiteModel.getInputs(); - modelInputs[0].setData(this.inputBuffer.buffer); - result.predict(modelInputs).then((result) => { + modelInputs[0].setData(inputBuffer.buffer); + mindSporeLiteModel.predict(modelInputs).then((result) => { let output = new Float32Array(result[0].getData()); for (let i = 0; i < output.length; i++) { console.log(output[i].toString()); @@ -576,15 +576,15 @@ Sets the tensor data. ```js import resourceManager from '@ohos.resourceManager' -@State inputName: string = 'input_data.bin'; +let inputName = 'input_data.bin'; let syscontext = globalThis.context; -syscontext.resourceManager.getRawFileContent(this.inputName).then((buffer) => { - this.inputBuffer = buffer; +syscontext.resourceManager.getRawFileContent(inputName).then(async (buffer) => { + let inputBuffer = buffer; + let model_file = '/path/to/xxx.ms'; + let mindSporeLiteModel = await mindSporeLite.loadModelFromFile(model_file); + const modelInputs = mindSporeLiteModel.getInputs(); + modelInputs[0].setData(inputBuffer.buffer); }) -let model_file = '/path/to/xxx.ms'; -let mindSporeLiteModel = await mindSporeLite.loadModelFromFile(model_file); -const modelInputs = mindSporeLiteModel.getInputs(); -modelInputs[0].setData(this.inputBuffer.buffer); ``` ## DataType diff --git a/en/application-dev/reference/apis/js-apis-net-mdns.md b/en/application-dev/reference/apis/js-apis-net-mdns.md index de9ee7cf502b8fc8bd60c7c7a8c649104f89a7c0..3d05860d5304e03b3f7745e1ec27e91fb78712e5 100644 --- a/en/application-dev/reference/apis/js-apis-net-mdns.md +++ b/en/application-dev/reference/apis/js-apis-net-mdns.md @@ -718,6 +718,41 @@ discoveryService.on('discoveryStart', (data) => { discoveryService.stopSearchingMDNS(); ``` +### off('discoveryStart')10+ + +off(type: 'discoveryStart', callback?: Callback<{ serviceInfo: LocalServiceInfo, errorCode?: MdnsError }>): void; + +Disables listening for **discoveryStart** events. + +**System capability**: SystemCapability.Communication.NetManager.MDNS + +**Parameters** + +| Name | Type | Mandatory| Description | +|-------------|--------------|-----------|-----------------------------------------------------| +| type | string | Yes |Event type. This field has a fixed value of **discoveryStart**.
**discoveryStart**: event of starting discovery of mDNS services on the LAN.| +| callback | Callback<{serviceInfo: [LocalServiceInfo](#localserviceinfo), errorCode?: [MdnsError](#mdnserror)}> | Yes | Callback used to return the mDNS service and error information. | + +**Example** + +```js +// See mdns.createDiscoveryService. +let context = globalThis.context; +let serviceType = "_print._tcp"; +let discoveryService = mdns.createDiscoveryService(context, serviceType); +discoveryService.startSearchingMDNS(); + +discoveryService.on('discoveryStart', (data) => { + console.log(JSON.stringify(data)); +}); + +discoveryService.stopSearchingMDNS(); + +discoveryService.off('discoveryStart', (data) => { + console.log(JSON.stringify(data)); +}); +``` + ### on('discoveryStop')10+ on(type: 'discoveryStop', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MdnsError}>): void @@ -749,6 +784,41 @@ discoveryService.on('discoveryStop', (data) => { discoveryService.stopSearchingMDNS(); ``` +### off('discoveryStop')10+ + +off(type: 'discoveryStop', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MdnsError}>): void + +Disables listening for **discoveryStop** events. + +**System capability**: SystemCapability.Communication.NetManager.MDNS + +**Parameters** + +| Name | Type | Mandatory| Description | +|-------------|--------------|-----------|-----------------------------------------------------| +| type | string | Yes |Event type. This field has a fixed value of **discoveryStop**.
**discoveryStop**: event of stopping discovery of mDNS services on the LAN.| +| callback | Callback<{serviceInfo: [LocalServiceInfo](#localserviceinfo), errorCode?: [MdnsError](#mdnserror)}> | Yes | Callback used to return the mDNS service and error information. | + +**Example** + +```js +// See mdns.createDiscoveryService. +let context = globalThis.context; +let serviceType = "_print._tcp"; +let discoveryService = mdns.createDiscoveryService(context, serviceType); +discoveryService.startSearchingMDNS(); + +discoveryService.on('discoveryStop', (data) => { + console.log(JSON.stringify(data)); +}); + +discoveryService.stopSearchingMDNS(); + +discoveryService.off('discoveryStop', (data) => { + console.log(JSON.stringify(data)); +}); +``` + ### on('serviceFound')10+ on(type: 'serviceFound', callback: Callback\): void @@ -780,6 +850,41 @@ discoveryService.on('serviceFound', (data) => { discoveryService.stopSearchingMDNS(); ``` +### off('serviceFound')10+ + +off(type: 'serviceFound', callback: Callback\): void + +Disables listening for **serviceFound** events. + +**System capability**: SystemCapability.Communication.NetManager.MDNS + +**Parameters** + +| Name | Type | Mandatory| Description | +|-------------|--------------|-----------|-----------------------------------------------------| +| type | string | Yes |Event type. This field has a fixed value of **serviceFound**.
**serviceFound**: event indicating an mDNS service is found.| +| callback | Callback<[LocalServiceInfo](#localserviceinfo)> | Yes | mDNS service information. | + +**Example** + +```js +// See mdns.createDiscoveryService. +let context = globalThis.context; +let serviceType = "_print._tcp"; +let discoveryService = mdns.createDiscoveryService(context, serviceType); +discoveryService.startSearchingMDNS(); + +discoveryService.on('serviceFound', (data) => { + console.log(JSON.stringify(data)); +}); + +discoveryService.stopSearchingMDNS(); + +discoveryService.off('serviceFound', (data) => { + console.log(JSON.stringify(data)); +}); +``` + ### on('serviceLost')10+ on(type: 'serviceLost', callback: Callback\): void @@ -811,6 +916,41 @@ discoveryService.on('serviceLost', (data) => { discoveryService.stopSearchingMDNS(); ``` +### off('serviceLost')10+ + +off(type: 'serviceLost', callback: Callback\): void + +Disables listening for **serviceLost** events. + +**System capability**: SystemCapability.Communication.NetManager.MDNS + +**Parameters** + +| Name | Type | Mandatory| Description | +|-------------|--------------|-----------|-----------------------------------------------------| +| type | string | Yes |Event type. This field has a fixed value of **serviceLost**.
serviceLost: event indicating that an mDNS service is removed.| +| callback | Callback<[LocalServiceInfo](#localserviceinfo)> | Yes | mDNS service information. | + +**Example** + +```js +// See mdns.createDiscoveryService. +let context = globalThis.context; +let serviceType = "_print._tcp"; +let discoveryService = mdns.createDiscoveryService(context, serviceType); +discoveryService.startSearchingMDNS(); + +discoveryService.on('serviceLost', (data) => { + console.log(JSON.stringify(data)); +}); + +discoveryService.stopSearchingMDNS(); + +discoveryService.off('serviceLost', (data) => { + console.log(JSON.stringify(data)); +}); +``` + ## LocalServiceInfo10+ Defines the mDNS service information. diff --git a/en/application-dev/reference/apis/js-apis-notification.md b/en/application-dev/reference/apis/js-apis-notification.md index 646f07fc4d30ec6ad4585eacd840a99954b34973..4b3f492ec950383b86cf277b31d91da38a22d901 100644 --- a/en/application-dev/reference/apis/js-apis-notification.md +++ b/en/application-dev/reference/apis/js-apis-notification.md @@ -74,7 +74,7 @@ Publishes a notification. This API uses a promise to return the result. ```js // NotificationRequest object let notificationRequest = { - notificationId: 1, + id: 1, content: { contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { @@ -161,7 +161,7 @@ Publishes a notification to a specified user. This API uses a promise to return ```js let notificationRequest = { - notificationId: 1, + id: 1, content: { contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { @@ -1460,7 +1460,7 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal | --------------- | ----------------------------------| ---- | -------------------- | | bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application. | | notificationKey | [NotificationKey](#notificationkeydeprecated) | Yes | Notification key. | -| reason | [RemoveReason](#removereason9-deprecated) | Yes | Indicates the reason for deleting a notification. | +| reason | [RemoveReason](#removereason-deprecated) | Yes | Reason for deleting a notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1502,7 +1502,7 @@ Removes a notification for a specified bundle. This API uses a promise to return | --------------- | --------------- | ---- | ---------- | | bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application.| | notificationKey | [NotificationKey](#notificationkeydeprecated) | Yes | Notification key. | -| reason | [RemoveReason](#removereason9-deprecated) | Yes | Reason for deleting the notification. | +| reason | [RemoveReason](#removereason-deprecated) | Yes | Reason for deleting the notification. | **Example** @@ -1536,8 +1536,8 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | -------------------- | -| hashCode | string | Yes | Unique notification ID. It is the **hashCode** in the [NotificationRequest](#notificationrequest) object of [SubscribeCallbackData](#subscribecallbackdata) of the [onConsume](js-apis-inner-notification-notificationSubscriber.md#onconsume) callback. | -| reason | [RemoveReason](#removereason9-deprecated) | Yes | Indicates the reason for deleting a notification. | +| hashCode | string | Yes | Unique notification ID. It is the **hashCode** in the [NotificationRequest](#notificationrequest) object of [SubscribeCallbackData](#subscribecallbackdata) of the [onConsume](js-apis-inner-notification-notificationSubscriber.md#onconsume) callback.| +| reason | [RemoveReason](#removereason-deprecated) | Yes | Reason for deleting a notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1573,7 +1573,7 @@ Removes a notification for a specified bundle. This API uses a promise to return | Name | Type | Mandatory| Description | | -------- | ---------- | ---- | ---------- | | hashCode | string | Yes | Unique notification ID.| -| reason | [RemoveReason](#removereason9-deprecated) | Yes | Reason for deleting the notification. | +| reason | [RemoveReason](#removereason-deprecated) | Yes | Reason for deleting the notification. | **Example** @@ -2872,10 +2872,10 @@ Notification.getDeviceRemindType().then((data) => { > > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [notificationManager.BundleOption](js-apis-inner-notification-notificationCommonDef.md#bundleoption) instead. -| Name | Type | Read-only| Mandatory| Description | -| ------ | ------ |---- | --- | ------ | -| bundle | string | No | Yes | Bundle information of the application.| -| uid | number | No | No | User ID.| +| Name | Type | Mandatory| Description | +| ------ | ------ | --- | ------ | +| bundle | string | Yes | Bundle information of the application.| +| uid | number | No | User ID.| ## NotificationKeydeprecated @@ -3059,7 +3059,7 @@ Describes the notification request. | classification | string | Yes | Yes | Notification category.
**System API**: This is a system API and cannot be called by third-party applications. | | groupName8+| string | Yes | Yes | Notification group name. | | template8+ | [NotificationTemplate](#notificationtemplate8) | Yes | Yes | Notification template. | -| isRemoveAllowed8+ | boolean | Yes | No | Whether the notification can be removed.
**System API**: This is a system API and cannot be called by third-party applications. | +| isRemoveAllowed10+ | boolean | Yes | No | Whether the notification can be removed.
**System API**: This is a system API and cannot be called by third-party applications. | | source8+ | number | Yes | No | Notification source.
**System API**: This is a system API and cannot be called by third-party applications. | | distributedOption8+ | [DistributedOptions](#distributedoptions8) | Yes | Yes | Distributed notification options. | | deviceId8+ | string | Yes | No | Device ID of the notification source.
**System API**: This is a system API and cannot be called by third-party applications. | @@ -3203,7 +3203,7 @@ Provides the notification user input. | TYPE_CONTINUOUS | 1 | Continuous notification. | | TYPE_TIMER | 2 | Timed notification. | -## RemoveReason9+ deprecated +## RemoveReason deprecated **System capability**: SystemCapability.Notification.Notification @@ -3211,9 +3211,9 @@ Provides the notification user input. > **NOTE** > -> This API is supported since API version 9 and deprecated since API version 9. You are advised to use [notificationManager.RemoveReason](js-apis-notificationSubscribe.md#removereason) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [notificationManager.RemoveReason](js-apis-notificationSubscribe.md#removereason) instead. | Name | Value | Description | | -------------------- | --- | -------------------- | -| CLICK_REASON_REMOVE9+ | 1 | The notification is removed after a click on it. | -| CANCEL_REASON_REMOVE9+ | 2 | The notification is removed by the user. | +| CLICK_REASON_REMOVE | 1 | The notification is removed after a click on it. | +| CANCEL_REASON_REMOVE | 2 | The notification is removed by the user. | diff --git a/en/application-dev/reference/apis/js-apis-notificationSubscribe.md b/en/application-dev/reference/apis/js-apis-notificationSubscribe.md index 1ca3f7833aadfde7058e24f8231d0e0360d82122..10a7091a75c1e9354921fe46bdbc1ce4bccb1a2e 100644 --- a/en/application-dev/reference/apis/js-apis-notificationSubscribe.md +++ b/en/application-dev/reference/apis/js-apis-notificationSubscribe.md @@ -443,6 +443,90 @@ notificationSubscribe.remove(hashCode, reason).then(() => { console.info("remove success"); }); ``` +## NotificationSubscribe.remove + +remove(hashCodes: Array\, reason: RemoveReason, callback: AsyncCallback\): void + +Removes specified notifications. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +|-----------|-------------------------------| ---- |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| hashCodes | Array\ | Yes | Array of unique notification IDs. It is the **hashCode** in the [NotificationRequest](js-apis-inner-notification-notificationRequest.md#notificationrequest) object of [SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata) of the [onConsume](js-apis-inner-notification-notificationSubscriber.md#onConsume) callback.| +| reason | [RemoveReason](#removereason) | Yes | Reason for removing the notification. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +let hashCodes = ['hashCode1', 'hashCode2']; + +function removeCallback(err) { + if (err) { + console.error(`remove failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("remove success"); + } +} +let reason = notificationSubscribe.RemoveReason.CANCEL_REASON_REMOVE; +notificationSubscribe.remove(hashCodes, reason, removeCallback); +``` + +## NotificationSubscribe.remove + +remove(hashCodes: Array\, reason: RemoveReason): Promise\ + +Removes specified notifications. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +|-----------|-------------------------------| ---- |-------------| +| hashCodes | Array\ | Yes | Array of unique notification IDs.| +| reason | [RemoveReason](#removereason) | Yes | Reason for removing the notification. | + +**Error codes** + +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +let hashCodes = ['hashCode1','hashCode2']; +let reason = notificationSubscribe.RemoveReason.CLICK_REASON_REMOVE; +notificationSubscribe.remove(hashCodes, reason).then(() => { + console.info("remove success"); +}); +``` ## NotificationSubscribe.removeAll diff --git a/en/application-dev/reference/apis/js-apis-photoAccessHelper.md b/en/application-dev/reference/apis/js-apis-photoAccessHelper.md index 808334727bbbf917dad8a7f801bcc7896ad12ee3..6840c523a55cbb457417eed6391473d5a325aa8a 100644 --- a/en/application-dev/reference/apis/js-apis-photoAccessHelper.md +++ b/en/application-dev/reference/apis/js-apis-photoAccessHelper.md @@ -1155,126 +1155,6 @@ async function example() { } ``` -### createDeleteRequest - -createDeleteRequest(uriList: Array<string>, callback: AsyncCallback<void>): void; - -Creates a dialog box for deleting photos. This API uses an asynchronous callback to return the result. The deleted photos are moved to the trash. - -**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO - -**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------- | -| uriList | Array<string> | Yes | URIs of the media files to delete.| -| callback | AsyncCallback<void> | Yes | Callback that returns no value.| - -**Error codes** - -For details about the error codes, see [Universal Error Codes](../errorcodes/errorcode-universal.md). - -| ID| Error Message| -| -------- | ---------------------------------------- | -| 401 | if parameter is invalid. | - -**Example** - -```ts -import dataSharePredicates from '@ohos.data.dataSharePredicates'; - -async function example() { - console.info('createDeleteRequestDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions = { - fetchColumns: [], - predicates: predicates - }; - try { - const fetchResult = await phAccessHelper.getAssets(fetchOptions); - var asset = await fetchResult.getFirstObject(); - } catch (err) { - console.info('fetch failed, message =', err); - } - - if (asset == undefined) { - console.error('asset not exist'); - return; - } - phAccessHelper.createDeleteRequest([asset.uri], (err) => { - if (err == undefined) { - console.info('createDeleteRequest successfully'); - } else { - console.error('createDeleteRequest failed with error: ' + err); - } - }); -} -``` - -### createDeleteRequest - -createDeleteRequest(uriList: Array<string>): Promise<void>; - -Creates a dialog box for deleting photos. This API uses a promise to return the result. The deleted photos are moved to the trash. - -**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO - -**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------- | -| uriList | Array<string> | Yes | URIs of the media files to delete.| - -**Return value** - -| Type | Description | -| --------------------------------------- | ----------------- | -| Promise<void>| Promise that returns no value.| - -**Error codes** - -For details about the error codes, see [Universal Error Codes](../errorcodes/errorcode-universal.md). - -| ID| Error Message| -| -------- | ---------------------------------------- | -| 401 | if parameter is invalid. | - -**Example** - -```ts -import dataSharePredicates from '@ohos.data.dataSharePredicates'; - -async function example() { - console.info('createDeleteRequestDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions = { - fetchColumns: [], - predicates: predicates - }; - try { - const fetchResult = await phAccessHelper.getAssets(fetchOptions); - var asset = await fetchResult.getFirstObject(); - } catch (err) { - console.info('fetch failed, message =', err); - } - - if (asset == undefined) { - console.error('asset not exist'); - return; - } - try { - await phAccessHelper.createDeleteRequest([asset.uri]); - console.info('createDeleteRequest successfully'); - } catch (err) { - console.error('createDeleteRequest failed with error: ' + err); - } -} -``` - ### release release(callback: AsyncCallback<void>): void @@ -3725,7 +3605,6 @@ Defines the key information about an image or video file. | POSITION | 'position' | File location type. **System API**: This is a system API. | | DATE_TRASHED | 'date_trashed' | Date when the file was deleted. The value is the number of seconds between the time when the file is deleted and January 1, 1970. **System API**: This is a system API. | | HIDDEN | 'hidden' | Whether the file is hidden. **System API**: This is a system API. | -| CAMERA_SHOT_KEY | 'camera_shot_key' | Key for the Untra Snamshot feature, which allows the camera to take photos or record videos with the screen off. (This parameter is available only for the system camera, and the key value is defined by the system camera.)
**System API**: This is a system API. | ## AlbumKeys @@ -3747,7 +3626,6 @@ Defines the options for creating an image or video asset. | Name | Type | Mandatory| Description | | ---------------------- | ------------------- | ---- | ------------------------------------------------ | | subtype | [PhotoSubtype](#photosubtype) | No | Subtype of the image or video. **System API**: This is a system API. | -| cameraShotKey | string | No | Key for the Untra Snamshot feature, which allows the camera to take photos or record videos with the screen off. (This parameter is available only for the system camera, and the key value is defined by the system camera.)
**System API**: This is a system API. | ## CreateOptions diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md index d61b8272edee9b2b522139a9976df17027be98a5..a40dac5160a291338c6c1885cf7c5f82c204095f 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @@ -596,8 +596,8 @@ Provides the information about the suspension delay. | LOCATION | 4 | Positioning and navigation. | | BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. | | MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. | -| WIFI_INTERACTION | 7 | WLAN-related (system API).| -| VOIP | 8 | Audio and video calls (system API). | +| WIFI_INTERACTION | 7 | WLAN-related.
**System API**: This is a system API. | +| VOIP | 8 | Audio and video calls.
**System API**: This is a system API. | | TASK_KEEPING | 9 | Computing task (effective only for specific devices). | ## EfficiencyResourcesRequest diff --git a/en/application-dev/reference/apis/js-apis-socket.md b/en/application-dev/reference/apis/js-apis-socket.md index 27403a677649049b97c6d3530f75a8e3e1256329..6780a6483b0285dd525ee532a1718f0388b5f06c 100644 --- a/en/application-dev/reference/apis/js-apis-socket.md +++ b/en/application-dev/reference/apis/js-apis-socket.md @@ -1,4 +1,4 @@ -# # @ohos.net.socket (Socket Connection) +# @ohos.net.socket (Socket Connection) The **socket** module implements data transfer over TCP, UDP, Web, and TLS socket connections. @@ -1691,7 +1691,7 @@ listen(address: NetAddress, callback: AsyncCallback\): void Binds the IP address and port number. The port number can be specified or randomly allocated by the system. The server listens to and accepts TCP socket connections established over the socket. Multiple threads are used to process client data concurrently. This API uses an asynchronous callback to return the result. -> **NOTE** +> **NOTE**
> The server uses this API to perform the **bind**, **listen**, and **accept** operations. If the **bind** operation fails, the system randomly allocates a port number. **Required permissions**: ohos.permission.INTERNET @@ -1736,7 +1736,7 @@ listen(address: NetAddress): Promise\ Binds the IP address and port number. The port number can be specified or randomly allocated by the system. The server listens to and accepts TCP socket connections established over the socket. Multiple threads are used to process client data concurrently. This API uses a promise to return the result. -> **NOTE** +> **NOTE**
> The server uses this API to perform the **bind**, **listen**, and **accept** operations. If the **bind** operation fails, the system randomly allocates a port number. **Required permissions**: ohos.permission.INTERNET @@ -2515,7 +2515,7 @@ tcpServer.on('connect', function(client) { ### off('close')10+ -on(type: 'close', callback: Callback\): void +off(type: 'close', callback?: Callback): void Unsubscribes from **close** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result. @@ -5706,7 +5706,7 @@ tlsServer.on('connect', function(client) { ### off('close')10+ -on(type: 'close', callback: Callback\): void +off(type: 'close', callback?: Callback): void Unsubscribes from **close** events of a **TLSSocketConnection** object. This API uses an asynchronous callback to return the result. diff --git a/en/application-dev/reference/apis/js-apis-syscap.md b/en/application-dev/reference/apis/js-apis-syscap.md index 05439e8cd6949a8f50caec8481fae3eb908cac3c..d9e5601d2e1096f363edf984857e06ef9999ab89 100644 --- a/en/application-dev/reference/apis/js-apis-syscap.md +++ b/en/application-dev/reference/apis/js-apis-syscap.md @@ -29,12 +29,17 @@ Checks whether a SysCap is supported. **Example** ```js -import geolocation from '@ohos.geolocation' +import geoLocationManager from '@ohos.geoLocationManager' -const isLocationAvailable = canIUse('SystemCapability.Location.Location'); +const isLocationAvailable = canIUse('SystemCapability.Location.Location.Core'); if (isLocationAvailable) { - geolocation.getCurrentLocation((location) => { - console.log(location.latitude, location.longitue); + geoLocationManager.getCurrentLocation((err, location) => { + if (err) { + console.log('err=' + JSON.stringify(err)); + } + if (location) { + console.log('location=' + JSON.stringify(location)); + } }); } else { console.log('Location not by this device.'); diff --git a/en/application-dev/reference/apis/js-apis-system-date-time.md b/en/application-dev/reference/apis/js-apis-system-date-time.md index c457247270be59898c2328e95b015d442cf41382..d78f005217ddae233bedcb3c37a3284655cec0e5 100644 --- a/en/application-dev/reference/apis/js-apis-system-date-time.md +++ b/en/application-dev/reference/apis/js-apis-system-date-time.md @@ -22,6 +22,8 @@ Sets the system time. This API uses an asynchronous callback to return the resul **System capability**: SystemCapability.MiscServices.Time +**Required permissions**: ohos.permission.SET_TIME + **Parameters** | Name | Type | Mandatory| Description | @@ -57,6 +59,8 @@ Sets the system time. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Time +**Required permissions**: ohos.permission.SET_TIME + **Parameters** | Name| Type | Mandatory| Description | @@ -158,7 +162,7 @@ Obtains the time elapsed since the Unix epoch. This API uses a promise to return | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------- | -| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| +| isNano | boolean | No | Whether the time to return is in nanoseconds. The default value is **false**.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| **Return value** @@ -253,7 +257,7 @@ Obtains the time elapsed since system startup, excluding the deep sleep time. Th | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ----------------------------------- | -| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| +| isNano | boolean | No | Whether the time to return is in nanoseconds. The default value is **false**.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| **Return value** @@ -348,7 +352,7 @@ Obtains the time elapsed since system startup, including the deep sleep time. Th | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------- | -| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| +| isNano | boolean | No | Whether the time to return is in nanoseconds. The default value is **false**.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| **Return value** @@ -380,6 +384,8 @@ Sets the system date. This API uses an asynchronous callback to return the resul **System capability**: SystemCapability.MiscServices.Time +**Required permissions**: ohos.permission.SET_TIME + **Parameters** | Name | Type | Mandatory| Description | @@ -414,6 +420,8 @@ Sets the system date. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Time +**Required permissions**: ohos.permission.SET_TIME + **Parameters** | Name| Type| Mandatory| Description | @@ -509,6 +517,8 @@ Sets the system time zone. This API uses an asynchronous callback to return the **System capability**: SystemCapability.MiscServices.Time +**Required permissions**: ohos.permission.SET_TIME_ZONE + **Parameters** | Name | Type | Mandatory| Description | @@ -542,6 +552,8 @@ Sets the system time zone. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Time +**Required permissions**: ohos.permission.SET_TIME_ZONE + **Parameters** | Name | Type | Mandatory| Description | diff --git a/en/application-dev/reference/apis/js-apis-system-timer.md b/en/application-dev/reference/apis/js-apis-system-timer.md index cc15e7f85a4dec87d1d23f0bc10fab0514d7df5d..e0c0e3cb5768eecc8a2ece9df1d5400ac835751d 100644 --- a/en/application-dev/reference/apis/js-apis-system-timer.md +++ b/en/application-dev/reference/apis/js-apis-system-timer.md @@ -36,8 +36,8 @@ Defines the initialization options for **createTimer**. | Name | Type | Mandatory| Description | | --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | | type | number | Yes | Timer type.
**1**: CPU time type. (The start time of the timer cannot be later than the current system time.)
**2**: wakeup type.
**4**: exact type.
**8**: idle type (not supported currently).| -| repeat | boolean | Yes | Whether the timer is a repeating timer. The value **true** means that the timer is a repeating timer, and **false** means that the timer is a one-shot timer. | -| interval | number | No | Repeat interval. For a repeating timer, the value must be greater than 5000 ms. For a one-shot timer, the value is **0**.| +| repeat | boolean | Yes | Whether the timer is a repeating timer.
The value **true** means that the timer is a repeating timer, and **false** means that the timer is a one-shot timer. | +| interval | number | No | Repeat interval.
For a repeating timer, the value must be greater than 5000 ms. For a one-shot timer, the value is **0**.| | wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | No | **WantAgent** object of the notification to be sent when the timer expires. (An application MainAbility can be started, but not a Service ability.)| | callback | number | Yes | Callback used to return the timer ID. | @@ -48,8 +48,6 @@ createTimer(options: TimerOptions, callback: AsyncCallback<number>): void Creates a timer. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -89,7 +87,6 @@ createTimer(options: TimerOptions): Promise<number> Creates a timer. This API uses a promise to return the result. -**System API**: This is a system API. **System capability**: SystemCapability.MiscServices.Time @@ -133,8 +130,6 @@ startTimer(timer: number, triggerTime: number, callback: AsyncCallback<void&g Starts a timer. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -178,8 +173,6 @@ startTimer(timer: number, triggerTime: number): Promise<void> Starts a timer. This API uses a promise to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -226,8 +219,6 @@ stopTimer(timer: number, callback: AsyncCallback<void>): void Stops a timer. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -271,8 +262,6 @@ stopTimer(timer: number): Promise<void> Stops a timer. This API uses a promise to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -319,8 +308,6 @@ destroyTimer(timer: number, callback: AsyncCallback<void>): void Destroys a timer. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -365,8 +352,6 @@ destroyTimer(timer: number): Promise<void> Destroys a timer. This API uses a promise to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.MiscServices.Time **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-usb-deprecated.md b/en/application-dev/reference/apis/js-apis-usb-deprecated.md index f5c4bc2d05b1ac5e085f573c1730882afc38a03c..6a772fd6b99471ac17ea1657a01db89b72636dd6 100644 --- a/en/application-dev/reference/apis/js-apis-usb-deprecated.md +++ b/en/application-dev/reference/apis/js-apis-usb-deprecated.md @@ -137,7 +137,7 @@ Checks whether the application has the permission to access the device. **Example** ```js -let devicesName="1-1"; +let devicesName= "1-1"; let bool = usb.hasRight(devicesName); console.log(bool); ``` @@ -146,7 +146,7 @@ console.log(bool); requestRight(deviceName: string): Promise<boolean> -Requests the temporary permission for the application to access a USB device. This API uses a promise to return the result. +Requests the temporary permission for the application to access a USB device. This API uses a promise to return the result. By default, system applications are granted the device access permission. **System capability**: SystemCapability.USB.USBManager @@ -165,7 +165,7 @@ Requests the temporary permission for the application to access a USB device. Th **Example** ```js -let devicesName="1-1"; +let devicesName= "1-1"; usb.requestRight(devicesName).then((ret) => { console.log(`requestRight = ${ret}`); }); @@ -375,7 +375,14 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi **Example** ```js -let param = new usb.USBControlParams(); +let param = { + request: 0, + reqType: 0, + target:0, + value: 0, + index: 0, + data: null +}; usb.controlTransfer(devicepipe, param).then((ret) => { console.log(`controlTransfer = ${ret}`); }) @@ -500,7 +507,7 @@ Converts the USB function list in the numeric mask format to a string in Device **Example** ```js -let funcs = usb.ACM | usb.ECM; +let funcs = usb.FunctionType.ACM | usb.FunctionType.ECM; let ret = usb.usbFunctionsToString(funcs); ``` @@ -529,8 +536,12 @@ Sets the current USB function list in Device mode. **Example** ```js -let funcs = usb.HDC; -let ret = usb.setCurrentFunctions(funcs); +let funcs = usb.FunctionType.HDC; +usb.setCurrentFunctions(funcs).then(() => { + console.info('usb setCurrentFunctions successfully.'); +}).catch(err => { + console.error('usb setCurrentFunctions failed: ' + err.code + ' message: ' + err.message); +}); ``` ## usb.getCurrentFunctions9+ @@ -848,7 +859,7 @@ Enumerates power role types. | Name | Value | Description | | ------ | ---- | ---------- | -| NONE | 0 | None | +| NONE | 0 | None. | | SOURCE | 1 | External power supply.| | SINK | 2 | Internal power supply.| @@ -862,6 +873,6 @@ Enumerates data role types. | Name | Value | Description | | ------ | ---- | ------------ | -| NONE | 0 | None | +| NONE | 0 | None. | | HOST | 1 | USB host.| | DEVICE | 2 | USB device.| diff --git a/en/application-dev/reference/apis/js-apis-usbManager.md b/en/application-dev/reference/apis/js-apis-usbManager.md index 204318356f38eca412eed855ddff9d0e324a8463..e60bcc7ca5286d9f19ff01cdc1e0e3abbb59d0da 100644 --- a/en/application-dev/reference/apis/js-apis-usbManager.md +++ b/en/application-dev/reference/apis/js-apis-usbManager.md @@ -161,7 +161,7 @@ console.log(`${bool}`); requestRight(deviceName: string): Promise<boolean> -Requests the temporary permission for the application to access a USB device. This API uses a promise to return the result. +Requests the temporary device access permission for the application. This API uses a promise to return the result. System applications are granted the device access permission by default, and you do not need to apply for the permission separately. **System capability**: SystemCapability.USB.USBManager @@ -190,7 +190,7 @@ usb.requestRight(devicesName).then((ret) => { removeRight(deviceName: string): boolean -Removes the permission for the application to access a USB device. +Removes the device access permission for the application. System applications are granted the device access permission by default, and calling this API will not revoke the permission. **System capability**: SystemCapability.USB.USBManager @@ -219,7 +219,7 @@ if (usb.removeRight(devicesName)) { addRight(bundleName: string, deviceName: string): boolean -Adds the permission for the application to access a USB device. +Adds the device access permission for the application. System applications are granted the device access permission by default, and calling this API will not revoke the permission. [requestRight](#usbrequestright) triggers a dialog box to request for user authorization, whereas **addRight** adds the access permission directly without displaying a dialog box. diff --git a/en/application-dev/reference/apis/js-apis-webview.md b/en/application-dev/reference/apis/js-apis-webview.md index adea4c22a9473f43b8092d0314918537ecaa98b6..b98042b08d0f96215b6f6b3a7e1fc5a82f8b9b89 100644 --- a/en/application-dev/reference/apis/js-apis-webview.md +++ b/en/application-dev/reference/apis/js-apis-webview.md @@ -254,20 +254,20 @@ struct WebComponent { .onClick(() => { // Use the local port to send messages to HTML5. try { - console.log("In eTS side send true start"); + console.log("In ArkTS side send true start"); if (this.nativePort) { this.message.setString("helloFromEts"); this.nativePort.postMessageEventExt(this.message); } } catch (error) { - console.log("In eTS side send message catch error:" + error.code + ", msg:" + error.message); + console.log("In ArkTS side send message catch error:" + error.code + ", msg:" + error.message); } }) Web({ src: $rawfile('index.html'), controller: this.controller }) .onPageEnd((e)=>{ - console.log("In eTS side message onPageEnd init mesaage channel"); + console.log("In ArkTS side message onPageEnd init mesaage channel"); // 1. Create a message port. this.ports = this.controller.createWebMessagePorts(true); // 2. Send port 1 to HTML5. @@ -276,10 +276,10 @@ struct WebComponent { this.nativePort = this.ports[0]; // 4. Set the callback. this.nativePort.onMessageEventExt((result) => { - console.log("In eTS side got message"); + console.log("In ArkTS side got message"); try { var type = result.getType(); - console.log("In eTS side getType:" + type); + console.log("In ArkTS side getType:" + type); switch (type) { case web_webview.WebMessageType.STRING: { this.msg1 = "result type:" + typeof (result.getString()); @@ -592,8 +592,8 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | -| 17100002 | Invalid url. | -| 17100003 | Invalid resource path or file type. | +| 17100002 | Invalid url. | +| 17100003 | Invalid resource path or file type. | **Example** @@ -652,71 +652,71 @@ struct WebComponent { There are three methods for loading local resource files: 1. Using $rawfile - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - - @Entry - @Component - struct WebComponent { - controller: web_webview.WebviewController = new web_webview.WebviewController(); - - build() { - Column() { - Button('loadUrl') - .onClick(() => { - try { - // Load a local resource file through $rawfile. - this.controller.loadUrl($rawfile('index.html')); - } catch (error) { - console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); - } - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('loadUrl') + .onClick(() => { + try { + // Load a local resource file through $rawfile. + this.controller.loadUrl($rawfile('index.html')); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` 2. Using the resources protocol - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - - @Entry - @Component - struct WebComponent { - controller: web_webview.WebviewController = new web_webview.WebviewController(); - - build() { - Column() { - Button('loadUrl') - .onClick(() => { - try { - // Load a local resource file through the resource protocol. - this.controller.loadUrl("resource://rawfile/index.html"); - } catch (error) { - console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); - } - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('loadUrl') + .onClick(() => { + try { + // Load local resource files through the resource protocol. + this.controller.loadUrl("resource://rawfile/index.html"); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` 3. Using a sandbox path. For details, see the example of loading local resource files in the sandbox in [Web](../arkui-ts/ts-basic-components-web.md#web). - HTML file to be loaded: - ```html - - - - -

Hello World

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

Hello World

+ + +``` ### loadData @@ -748,7 +748,7 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | -| 17100002 | Invalid url. | +| 17100002 | Invalid url. | **Example** @@ -1773,7 +1773,7 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web compoent. | -| 17100008 | Cannot delete JavaScriptProxy. | +| 17100008 | Cannot delete JavaScriptProxy. | **Example** @@ -1824,7 +1824,7 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web compoent. | -| 17100004 | Function not enable. | +| 17100004 | Function not enable. | **Example** @@ -2361,7 +2361,7 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | -| 17100004 | Function not enable. | +| 17100004 | Function not enable. | **Example** @@ -2405,7 +2405,7 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | -| 17100004 | Function not enable. | +| 17100004 | Function not enable. | **Example** @@ -2804,7 +2804,7 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | -| 17100003 | Invalid resource path or file type. | +| 17100003 | Invalid resource path or file type. | **Example** diff --git a/en/application-dev/reference/arkui-js-lite/figures/lite_line.PNG b/en/application-dev/reference/arkui-js-lite/figures/lite_line.PNG index 664ade98b38a3b6ac2b3e96dc4af8b75b6749a72..6fc94377d0df58e97d531dd11695c105bf161cd8 100644 Binary files a/en/application-dev/reference/arkui-js-lite/figures/lite_line.PNG and b/en/application-dev/reference/arkui-js-lite/figures/lite_line.PNG differ diff --git a/en/application-dev/reference/arkui-js-lite/js-components-basic-chart.md b/en/application-dev/reference/arkui-js-lite/js-components-basic-chart.md index 2c8f4c0550f7794d975eb7014e30506c034e9a1d..fe9c388615090bcc09f42ea162063ea2f2fa0d1b 100644 --- a/en/application-dev/reference/arkui-js-lite/js-components-basic-chart.md +++ b/en/application-dev/reference/arkui-js-lite/js-components-basic-chart.md @@ -165,7 +165,7 @@ Not supported strokeColor: '#0081ff', fillColor: '#cce5ff', data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628, 791, 505, 613, 575, 475, 553, 491, 680, 657, 716], - gradient: true, + gradient: false, } ], lineOps: { diff --git a/en/application-dev/reference/arkui-js-lite/js-components-basic-qrcode.md b/en/application-dev/reference/arkui-js-lite/js-components-basic-qrcode.md index 16ef26d1b4263b0217c9fedfc8f04016fe7175db..5a7c4ea3e8a055c9058821784ac058dfecea3b90 100644 --- a/en/application-dev/reference/arkui-js-lite/js-components-basic-qrcode.md +++ b/en/application-dev/reference/arkui-js-lite/js-components-basic-qrcode.md @@ -28,9 +28,9 @@ Not supported | Name| Parameter| Description| | -------- | -------- | -------- | -| click | - | Triggered when the component is clicked. | -| longpress | - | Triggered when the component is long pressed. | -| swipe5+ | [SwipeEvent](js-common-events.md) | Triggered when a user quickly swipes on the component. | +| click | - | Triggered when the component is clicked.| +| longpress | - | Triggered when the component is long pressed.| +| swipe5+ | [SwipeEvent](js-common-events.md) | Triggered when a user quickly swipes on the component.| ## Styles @@ -39,8 +39,8 @@ Not supported | -------- | -------- | -------- | -------- | -------- | | color | <color> | \#000000 | No| Color of the QR code.| | background-color | <color> | \#ffffff | No| Background color of the QR code.| -| width | <length> \| <percentage>5+ | - | No| Component width.
If this attribute is not set, the default value **0** is used. | -| height | <length> \| <percentage>5+ | - | No| Component height.
If this attribute is not set, the default value **0** is used. | +| width | <length> \| <percentage>5+ | - | No| Component width.
If this attribute is not set, the default value **0** is used.| +| height | <length> \| <percentage>5+ | - | No| Component height.
If this attribute is not set, the default value **0** is used.| | padding | <length> | 0 | No| Shorthand attribute to set the padding for all sides.
The attribute can have one to four values:
- If you set only one value, it specifies the padding for all the four sides.
- If you set two values, the first value specifies the top and bottom padding, and the second value specifies the left and right padding.
- If you set three values, the first value specifies the top padding, the second value specifies the left and right padding, and the third value specifies the bottom padding.
- If you set four values, they respectively specify the padding for top, right, bottom, and left sides (in clockwise order).| | padding-[left\|top\|right\|bottom] | <length> | 0 | No| Left, top, right, and bottom padding.| | margin | <length> \| <percentage>5+ | 0 | No| Shorthand attribute to set the margin for all sides. The attribute can have one to four values:
- If you set only one value, it specifies the margin for all the four sides.
- If you set two values, the first value specifies the top and bottom margins, and the second value specifies the left and right margins.
- If you set three values, the first value specifies the top margin, the second value specifies the left and right margins, and the third value specifies the bottom margin.
- If you set four values, they respectively specify the margin for top, right, bottom, and left sides (in clockwise order).| @@ -49,7 +49,7 @@ Not supported | border-color | <color> | black | No| Shorthand attribute to set the color for all borders.| | border-radius | <length> | - | No| Radius of round-corner borders.| | display | string | flex | No| How and whether to display the box containing an element. Available values are as follows:
- **flex**: flexible layout
- **none**: not rendered| -| [left\|top] | <length> \| <percentage>6+ | - | No| Edge of the element.
- **left**: left edge position of the element. This attribute defines the offset between the left edge of the margin area of a positioned element and left edge of its containing block.
- **top**: top edge position of the element. This attribute defines the offset between the top edge of a positioned element and that of a block included in the element. | +| [left\|top] | <length> \| <percentage>6+ | - | No| Edge of the element.
- **left**: left edge position of the element. This attribute defines the offset between the left edge of the margin area of a positioned element and left edge of its containing block.
- **top**: top edge position of the element. This attribute defines the offset between the top edge of a positioned element and that of a block included in the element.| > **NOTE** > - If the values of **width** and **height** are different, the smaller value is used as the length of the QR code. The generated QR code is center displayed. @@ -63,10 +63,10 @@ Not supported ```html
- - Color - BackgroundColor - Value + + Color + BackgroundColor + Value
``` @@ -93,32 +93,32 @@ Not supported ```javascript // xxx.js export default { - data: { - qr_col: '#87ceeb', - qr_bcol: '#f0ffff', - qr_value: 'value' - }, - changeColor() { - if (this.qr_col == '#87ceeb') { - this.qr_col = '#fa8072'; - } else { - this.qr_col = '#87ceeb'; + data: { + qr_col: '#87ceeb', + qr_bcol: '#f0ffff', + qr_value: 'value' + }, + changeColor() { + if (this.qr_col == '#87ceeb') { + this.qr_col = '#fa8072'; + } else { + this.qr_col = '#87ceeb'; + } + }, + changeBackgroundColor() { + if (this.qr_bcol == '#f0ffff') { + this.qr_bcol = '#ffffe0'; + } else { + this.qr_bcol = '#f0ffff'; + } + }, + changeValue() { + if (this.qr_value == 'value') { + this.qr_value = 'change'; + } else { + this.qr_value = 'value'; + } } - }, - changeBackgroundColor() { - if (this.qr_bcol == '#f0ffff') { - this.qr_bcol = '#ffffe0'; - } else { - this.qr_bcol = '#f0ffff'; - } - }, - changeValue() { - if (this.qr_value == 'value') { - this.qr_value = 'change'; - } else { - this.qr_value = 'value'; - } - } } ``` diff --git a/en/application-dev/reference/arkui-ts/figures/TextInputError.png b/en/application-dev/reference/arkui-ts/figures/TextInputError.png new file mode 100644 index 0000000000000000000000000000000000000000..2738da34ffdf692cbe23ca3ce2033e4e2a640e79 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/TextInputError.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/arkts-progressSmoothEffect.gif b/en/application-dev/reference/arkui-ts/figures/arkts-progressSmoothEffect.gif new file mode 100644 index 0000000000000000000000000000000000000000..65daefb814d4f64f4e85f0d3ef8be14fa04998dc Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/arkts-progressSmoothEffect.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/borderImage.gif b/en/application-dev/reference/arkui-ts/figures/borderImage.gif index dd8d0f1a9f9a786de94abf348130c526ecb09641..b3a316a22239c267af5503df959116dae4614338 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/borderImage.gif and b/en/application-dev/reference/arkui-ts/figures/borderImage.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/list-alignListItem.gif b/en/application-dev/reference/arkui-ts/figures/list-alignListItem.gif new file mode 100644 index 0000000000000000000000000000000000000000..60808894e3410f5c1bb92e4f241fd7b3590c150b Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/list-alignListItem.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/list1.gif b/en/application-dev/reference/arkui-ts/figures/list1.gif deleted file mode 100644 index 3e09842f3905ddf22e145b044238340b07b480ca..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/list1.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/showUnit.png b/en/application-dev/reference/arkui-ts/figures/showUnit.png deleted file mode 100644 index 4b60beda19ba2c6e314dcb0632d5d5953f79a952..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/showUnit.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md b/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md index 5a8f52093e36bc198bb47b5fefdb60f0aac56cfd..732c575f94ea2e5bea7c463eeafadfcc4ad78f51 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md @@ -22,7 +22,7 @@ Since API version 9, this API is supported in ArkTS widgets. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| group | string | No| Group name.| +| group | string | No| Group name.
**NOTE**
If there are multiple check box groups with the same group name, only the first check box group takes effect.| ## Attributes diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-image.md b/en/application-dev/reference/arkui-ts/ts-basic-components-image.md index aad87a6dee2faaacf65c89482b14f35c27e887bd..4edf427bb316099164f08fbd490dd1e002273ae3 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-image.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-image.md @@ -48,11 +48,11 @@ For details about how to use attributes, see [Setting Attributes](../../ui/arkts | matchTextDirection | boolean | Whether to display the image in the system language direction. When this parameter is set to true, the image is horizontally flipped in the right-to-left (RTL) language context.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| | fitOriginalSize | boolean | Whether to fit the component to the original size of the image source when the component size is not set.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| | fillColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color to be superimposed on the image.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute only applies to an SVG image. Once set, the fill color will replace that of the SVG image.| -| autoResize | boolean | Whether to resize the image source used for drawing based on the size of the display area during image decoding. This resizing can help reduce the memory usage. For example, if the size of the original image is 1920 x 1080 and the size of the display area is 200 x 200, you can set this attribute to **true** so that the image is automatically decoded to 200 x 200.
Default value: **true**
Since API version 9, this API is supported in ArkTS widgets.| +| autoResize | boolean | Whether to resize the image source based on the size of the display area during image decoding. This resizing can help reduce the memory usage. For example, if the size of the original image is 1920 x 1080 and the size of the display area is 200 x 200, you can set this attribute to **true** so that the image is automatically decoded to 200 x 200.
Default value: **true**
Since API version 9, this API is supported in ArkTS widgets.| | syncLoad8+ | boolean | Whether to load the image synchronously. By default, the image is loaded asynchronously. During synchronous loading, the UI thread is blocked and the placeholder image is not displayed.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When loading a small image, you are advised to set **syncLoad** to **true** so that the image loading can be quickly completed on the main thread.| | copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether the image can be copied.
When **copyOption** is set to a value other than **CopyOptions.None**, the image can be copied in various manners, such as long pressing, right-clicking, or pressing Ctrl+C.
Default value: **CopyOptions.None**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
SVG images cannot be copied.| | colorFilter9+ | [ColorFilter](ts-types.md#colorfilter9) | Color filter of the image. The input parameter is a 4 x 5 RGBA transformation matrix.
The first row of the matrix represents a vector value of R (red), the second row represents a vector value of G (green), the third row represents a vector value of B (blue), and the fourth row represents a vector value of A (alpha). The four rows represent different RGBA vector values.
The RGBA values are floating-point numbers between 0 and 1. When the diagonal value of the matrix is 1, the original color of the image is retained.
**Calculation rule:**
If the input filter matrix is as follows:
![image-matrix-1](figures/image-matrix-1.jpg)
Wherein the color is [R, G, B, A].
Then the color after filtering is [R', G', B', A'].
![image-matrix-2](figures/image-matrix-2.jpg)
Since API version 9, this API is supported in ArkTS widgets. | -| draggable(deprecated) | boolean | Whether the image is draggable.
This attribute cannot be used together with the [onDragStart](ts-universal-events-drag-drop.md) event.
Default value: **false**
**NOTE**
This API is supported since API version 9 and deprecated since API version 10. You are advised to use the universal attribute [draggable](ts-universal-events-drag-drop.md) instead.| +| draggable(deprecated) | boolean | Whether the image is draggable.
This attribute cannot be used together with the [onDragStart](ts-universal-attributes-drag-drop.md) event.
Default value: **false**
**NOTE**
This API is supported since API version 9 and deprecated since API version 10. You are advised to use the universal attribute [draggable](ts-universal-events-drag-drop.md) instead.| > **NOTE** > @@ -66,7 +66,7 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Description | | ------ | ---------------------------------------------------- | | None | No image interpolation. | -| High | High quality interpolation. This mode produces the highest possible quality scaled images, but may require more image rendering time.| +| High | High quality interpolation. This mode produces scaled images of the highest possible quality, but may require more image rendering time.| | Medium | Medium quality interpolation. | | Low | Low quality interpolation. | diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md b/en/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md index 4bb8b494268a33881eed4810af59ea1984706ec2..57dbedbffe82084f8b9e779ebdc4d23740af8898 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md @@ -45,6 +45,7 @@ struct LoadingProgressExample { Text('Orbital LoadingProgress ').fontSize(9).fontColor(0xCCCCCC).width('90%') LoadingProgress() .color(Color.Blue) + .layoutWeight(1) }.width('100%').margin({ top: 5 }) } } diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md b/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md index b84da89fe1f88e66bc14c57d3df61ec6dde3101d..067179f57ad1147ebdb470f93f047e1820e9bbfc 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md @@ -13,44 +13,54 @@ Supported Since API version 9, it is recommended that this component be used together with the **[\](ts-basic-components-navrouter.md)** component. - ## APIs -**API 1**: Navigation() +### Navigation + +Navigation() + +### Navigation10+ -**API 2**: Navigation(pathInfos: NavPathStack)10+ +Navigation(pathInfos: NavPathStack) Binds a navigation stack to the **\** component. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------------------------------- | ---- | ------------- | -| pathInfos | [NavPathStack](#navpathstack10) | No | Information about the navigation stack.| +| Name | Type | Mandatory | Description | +| --------- | ------------------------------- | ---- | ------ | +| pathInfos | [NavPathStack](#navpathstack10) | No | Information about the navigation stack.| ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name | Type | Description | -| ----------------------------- | ---------------------------------------- | ---------------------------------------- | -| title | [ResourceStr](ts-types.md#resourcestr)10+ \| [CustomBuilder](ts-types.md#custombuilder8)8+ \| [NavigationCommonTitle](#navigationcommontitle)9+ \| [NavigationCustomTitle](#navigationcustomtitle)9+ | Page title.
**NOTE**
When the NavigationCustomTitle type is used to set the height, the **titleMode** attribute does not take effect.
When the title string is too long: (1) If no subtitle is set, the string is scaled down, wrapped in two lines, and then clipped with an ellipsis (...); (2) If a subtitle is set, the subtitle is scaled down and then clipped with an ellipsis (...).| -| subTitle(deprecated) | string | Subtitle of the page. If this attribute is not set, no subtitle is displayed. This attribute is deprecated since API version 9. You are advised to use **title** instead.| -| menus | Array<[NavigationMenuItem](#navigationmenuitem)> \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Menu items in the upper right corner of the page. If this attribute is not set, no menu item is displayed. When the value type is Array\<[NavigationMenuItem](#navigationmenuitem)>, the menu shows a maximum of three icons in portrait mode and a maximum of five icons in landscape mode, with excess icons (if any) placed under the automatically generated **More** icon.| -| titleMode | [NavigationTitleMode](#navigationtitlemode) | Display mode of the page title bar.
Default value: **NavigationTitleMode.Free**| -| toolBar(deprecated) | [object](#object) \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Content of the toolbar. If this attribute is not set, no toolbar is displayed.
**items**: items on the toolbar.
**NOTE**
Items are evenly distributed on the toolbar at the bottom. Text and icons are evenly distributed in each content area. If the text is too long, it is scaled down level by level, wrapped in two lines, and then clipped with an ellipsis (...).
This API is deprecated since API version 10. You are advised to use **toolbarConfiguration** instead.| +| Name | Type | Description | +| ---------------------------------- | ---------------------------------------- | ---------------------------------------- | +| title | [ResourceStr](ts-types.md#resourcestr)10+ \| [CustomBuilder](ts-types.md#custombuilder8)8+ \| [NavigationCommonTitle](#navigationcommontitle)9+ \| [NavigationCustomTitle](#navigationcustomtitle)9+ | Page title.
**NOTE**
When the NavigationCustomTitle type is used to set the height, the **titleMode** attribute does not take effect.
When the title string is too long: (1) If no subtitle is set, the string is scaled down, wrapped in two lines, and then clipped with an ellipsis (...); (2) If a subtitle is set, the subtitle is scaled down and then clipped with an ellipsis (...).| +| subTitle(deprecated) | string | Subtitle of the page. If this attribute is not set, no subtitle is displayed. This attribute is deprecated since API version 9. You are advised to use **title** instead.| +| menus | Array<[NavigationMenuItem](#navigationmenuitem)> \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Menu items in the upper right corner of the page. If this attribute is not set, no menu item is displayed. When the value type is Array<[NavigationMenuItem](#navigationmenuitem)>, the menu shows a maximum of three icons in portrait mode and a maximum of five icons in landscape mode, with excess icons (if any) placed under the automatically generated **More** icon.| +| titleMode | [NavigationTitleMode](#navigationtitlemode) | Display mode of the page title bar.
Default value: **NavigationTitleMode.Free**| +| toolBar(deprecated) | [object](#object) \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Content of the toolbar. If this attribute is not set, no toolbar is displayed.
**items**: all items on the toolbar.
**NOTE**
Items are evenly distributed on the toolbar at the bottom. Text and icons are evenly distributed in each content area. If the text is too long, it is scaled down level by level, wrapped in two lines, and then clipped with an ellipsis (...).
This API is deprecated since API version 10. You are advised to use **toolbarConfiguration** instead.| | toolbarConfiguration10+ | Array<[ToolbarItem](#toolbaritem10)10+> \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Content of the toolbar. If this attribute is not set, no toolbar is displayed.
**NOTE**
When the value type is Array<[ToolbarItem](#ToolbarItem>, the toolbar exhibits the following features:
Items are evenly distributed on the toolbar at the bottom. Text and icons are evenly distributed in each content area.
If any item contains overlong text and there are fewer than five items, the following measures are taken: 1. Increase the item's width to accommodate the text until it is as large as the screen width; 2. Scale down the text level by level; 3. Wrap the text in two lines; 4. Clip the text with an ellipsis (...).
The toolbar shows a maximum of five icons in portrait mode, with excess icons (if any) placed under the automatically generated **More** icon. In landscape mode, this attribute must be used together with Array<[NavigationMenuItem](#navigationmenuitem)> of the **menus** attribute; the toolbar at the bottom is automatically hidden, and all items on the toolbar are moved to the menu in the upper right corner of the screen.
When the value type is [CustomBuilder](ts-types.md#custombuilder8), and the toolbar does not exhibit the preceding features except that items are evenly distributed on the toolbar at the bottom.| -| hideToolBar | boolean | Whether to hide the toolbar.
Default value: **false**
**true**: Hide the toolbar.
**false**: Display the toolbar.| -| hideTitleBar | boolean | Whether to hide the title bar.
Default value: **false**
**true**: Hide the title bar.
**false**: Display the title bar.| -| hideBackButton | boolean | Whether to hide the back button.
Default value: **false**
**true**: Hide the back button.
**false**: Display the back button.
The back button in the title bar of the **\** component cannot be hidden.
**NOTE**
The back button works only when **titleMode** is set to **NavigationTitleMode.Mini**.| -| navBarWidth9+ | [Length](ts-types.md#length) | Width of the navigation bar.
Default value: **240**
Unit: vp
**NOTE**
This attribute is valid only when the **\** component is split.| -| navBarPosition9+ | [NavBarPosition](#navbarposition) | Position of the navigation bar.
Default value: **NavBarPosition.Start**
**NOTE**
This attribute is valid only when the **\** component is split.| -| mode9+ | [NavigationMode](#navigationmode) | Display mode of the navigation bar.
Default value: **NavigationMode.Auto**
At the default settings, the component adapts to a single column or two columns based on the component width.
**NOTE**
Available options are **Stack**, **Split**, and **Auto**.| -| backButtonIcon9+ | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Back button icon on the navigation bar. The back button in the title bar of the **\** component cannot be hidden.| -| hideNavBar9+ | boolean | Whether to hide the navigation bar. This attribute is valid only when **mode** is set to **NavigationMode.Split**.| -| navDestination10+ | builder: (name: string, param: unknown) => void | Creates a **\** component.
**NOTE**
The **builder** function is used, with the **name** and **param** parameters passed in. In the builder, a layer of custom components can be included outside the **\** component. However, no attributes or events can be set for the custom components. Otherwise, only blank components are displayed.| -| navBarWidthRange10+ | [[Dimension](ts-types.md#dimension10), [Dimension](ts-types.md#dimension10)] | Minimum and maximum widths of the navigation bar (valid in dual-column mode).
Default value: **240** for the minimum value; 40% of the component width (not greater than 432) for the maximum value
Unit: vp
Priority rules:
Custom value > Default value
Minimum value > Maximum value
navBar > content
If values conflict, the global value takes precedence, and the local minimum value depends on the container size.| -| minContentWidth10+ | [Dimension](ts-types.md#dimension10) | Minimum width of the navigation bar content area (valid in dual-column mode).
Default value: **360**
Unit: vp
Priority rules:
Custom value > Default value
Minimum value > Maximum value
navBar > content
If values conflict, the global value takes precedence, and the local minimum value depends on the container size.
Breakpoint calculation in Auto mode: default 600 vp = minNavBarWidth (240 vp) + minContentWidth (360 vp)| +| hideToolBar | boolean | Whether to hide the toolbar.
Default value: **false**
**true**: Hide the toolbar.
**false**: Display the toolbar.| +| hideTitleBar | boolean | Whether to hide the title bar.
Default value: **false**
**true**: Hide the title bar.
**false**: Display the title bar.| +| hideBackButton | boolean | Whether to hide the back button.
Default value: **false**
**true**: Hide the back button.
**false**: Display the back button.
The back button in the title bar of the **\** component cannot be hidden.
**NOTE**
The back button works only when **titleMode** is set to **NavigationTitleMode.Mini**.| +| navBarWidth9+ | [Length](ts-types.md#length) | Width of the navigation bar.
Default value: **240**
Unit: vp
**NOTE**
This attribute is valid only when the **\** component is split.| +| navBarPosition9+ | [NavBarPosition](#navbarposition) | Position of the navigation bar.
Default value: **NavBarPosition.Start**
**NOTE**
This attribute is valid only when the **\** component is split.| +| mode9+ | [NavigationMode](#navigationmode) | Display mode of the navigation bar.
Default value: **NavigationMode.Auto**
At the default settings, the component adapts to a single column or two columns based on the component width.
**NOTE**
Available options are **Stack**, **Split**, and **Auto**.| +| backButtonIcon9+ | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Back button icon on the navigation bar. The back button in the title bar of the **\** component cannot be hidden.| +| hideNavBar9+ | boolean | Whether to hide the navigation bar. This attribute is valid only when **mode** is set to **NavigationMode.Split**.| +| navDestination10+ | builder: (name: string, param: unknown) => void | Creates a **\** component.
**NOTE**
The **builder** function is used, with the **name** and **param** parameters passed in. In the builder, a layer of custom components can be included outside the **\** component. However, no attributes or events can be set for the custom components. Otherwise, only blank components are displayed.| +| navBarWidthRange10+ | [[Dimension](ts-types.md#dimension10), [Dimension](ts-types.md#dimension10)] | Minimum and maximum widths of the navigation bar (valid in dual-column mode).
Default value: **240** for the minimum value; 40% of the component width (not greater than 432) for the maximum value
Unit: vp
Priority rules:
Custom value > Default value
Minimum value > Maximum value
navBar > content
If values conflict, the global value takes precedence, and the local minimum value depends on the container size.| +| minContentWidth10+ | [Dimension](ts-types.md#dimension10) | Minimum width of the navigation bar content area (valid in dual-column mode).
Default value: **360**
Unit: vp
Priority rules:
Custom value > Default value
Minimum value > Maximum value
navBar > content
If values conflict, the global value takes precedence, and the local minimum value depends on the container size.
Breakpoint calculation in Auto mode: default 600 vp = minNavBarWidth (240 vp) + minContentWidth (360 vp)| + +## Events + +| Name | Description | +| ---------------------------------------- | ---------------------------------------- | +| onTitleModeChange(callback: (titleMode: NavigationTitleMode) => void) | Called when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls.| +| onNavBarStateChange(callback: (isVisible: boolean) => void) | Called when the navigation bar visibility status changes. The value **true** means that the navigation bar is displayed, and **false** means the opposite.| ## NavPathStack10+ @@ -64,9 +74,9 @@ Pushes the NavDestination page information specified by **info** to the stack. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| info | [NavPathInfo](#navpathinfo10) | Yes | Information about the navigation destination page. | +| Name | Type | Mandatory | Description | +| ---- | ----------------------------- | ---- | -------------------- | +| info | [NavPathInfo](#navpathinfo10) | Yes | Information about the navigation destination page.| ### pushName10+ @@ -76,10 +86,10 @@ Pushes the navigation destination page specified by **name** to the navigation s **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | -| param | unknown | Yes | Parameter information of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ----- | ------- | ---- | --------------------- | +| name | string | Yes | Name of the navigation destination page. | +| param | unknown | Yes | Parameter information of the navigation destination page.| ### pop10+ @@ -89,10 +99,10 @@ Pops the top element out of the navigation stack. **Return value** -| Type | Description | -| ------ | -------- | +| Type | Description | +| ----------- | ------------------------ | | NavPathInfo | Returns the information about the navigation destination page at the top of the stack.| -| undefined | Returns **undefined** if the navigation stack is empty.| +| undefined | Returns **undefined** if the navigation stack is empty. | ### popTo10+ @@ -102,14 +112,14 @@ Returns the navigation stack to the first navigation destination page that match **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------------- | +| name | string | Yes | Name of the navigation destination page.| **Return value** -| Type | Description | -| ------ | -------- | +| Type | Description | +| ------ | ---------------------------------------- | | number | Returns the index of the first navigation destination page that matches the value of **name** if it exists in the navigation stack; returns **-1** otherwise.| ### popToIndex10+ @@ -120,9 +130,9 @@ Returns the navigation stack to the navigation destination page that matches the **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| index | number | Yes | Index of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------- | +| index | number | Yes | Index of the navigation destination page.| ### moveToTop10+ @@ -132,14 +142,14 @@ Moves to the top of the navigation stack the first navigation destination page t **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------------- | +| name | string | Yes | Name of the navigation destination page.| **Return value** -| Type | Description | -| ------ | -------- | +| Type | Description | +| ------ | ---------------------------------------- | | number | Returns the index of the first navigation destination page that matches the value of **name** if it exists in the navigation stack; returns **-1** otherwise.| ### moveIndexToTop10+ @@ -150,9 +160,9 @@ Moves to the top of the navigation stack the navigation destination page that ma **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| index | number | Yes | Index of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------- | +| index | number | Yes | Index of the navigation destination page.| ### clear10+ @@ -168,8 +178,8 @@ Obtains the names of all navigation destination pages in the navigation stack. **Return value** -| Type | Description | -| ------ | -------- | +| Type | Description | +| -------------- | -------------------------- | | Array | Names of all navigation destination pages in the navigation stack.| ### getParamByIndex10+ @@ -180,16 +190,16 @@ Obtains the parameter information of the navigation destination page that matche **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| index | number | Yes | Index of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------- | +| index | number | Yes | Index of the navigation destination page.| **Return value** -| Type | Description | -| ------ | -------- | -| unknown | Returns the parameter information of the matching navigation destination page.| -| undefined | Returns **undefined** if the passed index is invalid.| +| Type | Description | +| --------- | -------------------------- | +| unknown | Returns the parameter information of the matching navigation destination page.| +| undefined | Returns **undefined** if the passed index is invalid. | ### getParamByName10+ @@ -199,15 +209,15 @@ Obtains the parameter information of all the navigation destination pages that m **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------------- | +| name | string | Yes | Name of the navigation destination page.| **Return value** -| Type | Description | -| ------ | -------- | -| Array | Parameter information of all the matching navigation destination pages.| +| Type | Description | +| --------------- | --------------------------------- | +| Array | Parameter information of all the matching navigation destination pages.| ### getIndexByName10+ @@ -217,15 +227,15 @@ Obtains the indexes information of all the navigation destination pages that mat **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------------- | +| name | string | Yes | Name of the navigation destination page.| **Return value** -| Type | Description | -| ------ | -------- | -| Array | Indexes of all the matching navigation destination pages.| +| Type | Description | +| -------------- | --------------------------------- | +| Array | Indexes of all the matching navigation destination pages.| ### size10+ @@ -235,9 +245,9 @@ Obtains the stack size. **Return value** -| Type | Description | -| ------ | -------- | -| number | Stack size.| +| Type | Description | +| ------ | ------ | +| number | Stack size.| ## NavPathInfo10+ @@ -249,52 +259,52 @@ constructor(name: string, param: unknown) **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | -| param | unknown | No | Parameter information of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ----- | ------- | ---- | --------------------- | +| name | string | Yes | Name of the navigation destination page. | +| param | unknown | No | Parameter information of the navigation destination page.| ## NavigationMenuItem -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| value | string | Yes | Text of a menu item. | -| icon | string | No | Icon path of a menu item.| +| Name | Type | Mandatory | Description | +| ------ | ------------- | ---- | --------------- | +| value | string | Yes | Text of a menu item. | +| icon | string | No | Icon path of a menu item.| | action | () => void | No | Callback invoked when a menu item is selected. | ## object -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| value | string | Yes | Text of a toolbar item. | -| icon | string | No | Icon path of a toolbar item.| +| Name | Type | Mandatory | Description | +| ------ | ------------- | ---- | --------------- | +| value | string | Yes | Text of a toolbar item. | +| icon | string | No | Icon path of a toolbar item.| | action | () => void | No | Callback invoked when a toolbar item is selected. | ## ToolbarItem10+ -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------------------- | ---- | ----------------------------------------------------------- | -| value | ResourceStr | Yes | Text of a toolbar item. | -| icon | ResourceStr | No | Icon path of a toolbar item. | -| action | () => void | No | Callback invoked when a toolbar item is selected. | -| status | [ToolbarItemStatus](#toolbaritemstatus10) | No | Status of a toolbar item.
Default value: **ToolbarItemStatus.NORMAL**| -| activeIcon | ResourceStr | No | Icon path of the toolbar item in the active state. | +| Name | Type | Mandatory | Description | +| ---------- | ---------------------------------------- | ---- | ---------------------------------------- | +| value | ResourceStr | Yes | Text of a toolbar item. | +| icon | ResourceStr | No | Icon path of a toolbar item. | +| action | () => void | No | Callback invoked when a toolbar item is selected. | +| status | [ToolbarItemStatus](#toolbaritemstatus10) | No | Status of a toolbar item.
Default value: **ToolbarItemStatus.NORMAL**| +| activeIcon | ResourceStr | No | Icon path of the toolbar item in the active state. | ## ToolbarItemStatus10+ -| Name | Description | -| -------- | ------------------------------------------------------------ | +| Name | Description | +| -------- | ---------------------------------------- | | NORMAL | Normal state. In this state, the toolbar item takes on the default style and can switch to another state-specific style by responding to the hover, press, and focus events.| | DISABLED | Disabled state. In this state, the toolbar item is disabled and does not allow for user interactions.| | ACTIVE | Active state. In this state, the toolbar item can update its icon to the one specified by **activeIcon** by responding to a click event.| ## NavigationTitleMode -| Name| Description | -| ---- | ------------------------------------------------------------ | -| Free | When the content is a scrollable component, the main title shrinks as the content scrolls down (the subtitle fades out with its size remaining unchanged) and restores when the content scrolls up to the top.
**NOTE**
The size linkage effect works only when **title** is set to **ResourceStr** or **NavigationCommonTitle**. If **title** is set to any other value type, the main title changes in mere location when pulled down.| -| Mini | The title is fixed at mini mode. | -| Full | The title is fixed at full mode. | +| Name | Description | +| ---- | ---------------------------------------- | +| Free | When the content is a scrollable component, the main title shrinks as the content scrolls down (the subtitle fades out with its size remaining unchanged) and restores as the content scrolls up to the top.
**NOTE**
The size linkage effect works only when **title** is set to **ResourceStr** or **NavigationCommonTitle**. If **title** is set to any other value type, the main title changes in mere location when pulled down.| +| Mini | The title is fixed at mini mode. | +| Full | The title is fixed at full mode. | ## NavigationCommonTitle @@ -322,7 +332,7 @@ constructor(name: string, param: unknown) | Name | Description | | ----- | ------------------------------------------------------------ | | Stack | The navigation bar and content area are displayed independently of each other, which are equivalent to two pages. | -| Split | The navigation bar and content area are displayed in different columns. | +| Split | The navigation bar and content area are displayed in different columns.
The values of **navBarWidthRange** are represented by [minNavBarWidth,maxNavBarWidth].
1. When the value of **navBarWidth** is beyond the value range specified by **navBarWidthRange**, **navBarWidth** is set according to the following rules:
Value of **navBarWidth** < Value of **minNavBarWidth**: The value of **navBarWidth** is changed to that of **minNavBarWidth**.
Value of **navBarWidth** > Value of **maxNavBarWidth** and Component width - Value of **minContentWidth** - Divider width (1 vp) > Value of **maxNavBarWidth**: The value of **navBarWidth** is changed to that of **maxNavBarWidth**.
Value of **navBarWidth** > Value of **maxNavBarWidth** and Component width - Value of **minContentWidth** - Divider width (1 vp) < Value of **minNavBarWidth**: The value of **navBarWidth** is changed to that of **minNavBarWidth**.
Value of **navBarWidth** > Value of **maxNavBarWidth** and Component width - Value of **minContentWidth** - Divider width (1 vp) is within the value range specified by **navBarWidthRange**: The value of **navBarWidth** is changed to Component width - Value of **minContentWidth** - Divider width (1 vp).
2. When the value of **navBarWidth** is within the value range specified by **navBarWidthRange**, **navBarWidth** is set according to the following rules:
Value of **minNavBarWidth** + Value of **minContentWidth** + Divider width (1 vp) > = Component width: The value of **navBarWidth** is changed to that of **minNavBarWidth**.
Value of **minNavBarWidth** + Value of **minContentWidth** + Divider width (1 vp) < Component width and Value of **navBarWidth** + Value of **minContentWidth** + Divider width (1 vp) > = Component width: The value of **navBarWidth** is changed to Component width - Value of **minContentWidth** - Divider width (1 vp).
Value of **minNavBarWidth** + Value of **minContentWidth** + Divider width (1 vp) < Component width and Value of **navBarWidth** + Value of **minContentWidth** + Divider width (1 vp) < Component width: The value of **navBarWidth** is the set value.
3. When the component size is decreased, the content area is shrunk until its width reaches the value defined by **minContentWidth**, and then the navigation bar is shrunk until its width reaches the value defined by **minNavBarWidth**; if the component size is further decreased, the content area is further shrunk until it disappears, and then navigation bar is shrunk.
4. When the navigation bar is set to a fixed size and the component size is continuously decreased, the navigation bar is shrunk.
5. If only **navBarWidth** is set, the width of the navigation bar is fixed at the value of **navBarWidth**, and the divider cannot be dragged.| | Auto | In API version 9 and earlier versions: When the window width is greater than or equal to 520 vp, the Split mode is used. In other cases, the Stack mode is used.
In API version 10 and later versions: When the window width is greater than or equal to 600 vp, the Split mode is used. In other cases, the Stack mode is used. 600 vp = minNavBarWidth (240 vp) + minContentWidth (360 vp).| ## TitleHeight @@ -334,17 +344,10 @@ constructor(name: string, param: unknown) > **NOTE** +> > Among the scrollable components, only **\** is supported. -## Events - -| Name | Description | -| ---------------------------------------- | ---------------------------------------- | -| onTitleModeChange(callback: (titleMode: NavigationTitleMode) => void) | Called when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls.| -| onNavBarStateChange(callback: (isVisible: boolean) => void) | Called when the navigation bar visibility status changes. The value **true** means that the navigation bar is displayed, and **false** means the opposite.| - - ## Example ```ts diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-progress.md b/en/application-dev/reference/arkui-ts/ts-basic-components-progress.md index 060e00b1e3eca27a007342fe68ae309fe6e3d0b6..752ee317ab75703d1850aeae3320d1aea4f16656 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-progress.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-progress.md @@ -70,6 +70,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | strokeWidth | [Length](ts-types.md#length) | No | Stroke width of the progress indicator. It cannot be set in percentage.
Default value: **4.0vp** | | scaleCount | number | No | Number of divisions on the ring-style process indicator.
Default value: **120** | | scaleWidth | [Length](ts-types.md#length) | No | Scale width of the ring-style progress bar. It cannot be set in percentage. If it is greater than the value of **strokeWidth**, the default scale width is used.
Default value: **2.0vp**| +| enableSmoothEffect10+ | boolean | No| Whether to enable the smooth effect. When this effect is enabled, the progress change to the set value takes place gradually. Otherwise, it takes place immediately.
Default value: **true**| ## CapsuleStyleOptions10+ | Name | Type| Mandatory| Description| @@ -81,6 +82,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | fontColor | [ResourceColor](ts-types.md#resourcecolor) | No| Font color.
Default value: **'\#ff182431'**| | enableScanEffect | boolean | No| Whether to enable the scan effect.
Default value: **false**| | showDefaultPercentage | boolean | No| Whether to show the percentage of the current progress. This attribute does not take effect when the **content** attribute is set.
Default value: **false**| +| enableSmoothEffect10+ | boolean | No| Whether to enable the smooth effect. When this effect is enabled, the progress change to the set value takes place gradually. Otherwise, it takes place immediately.
Default value: **true**| ## RingStyleOptions10+ | Name | Type | Mandatory| Description | @@ -89,12 +91,14 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | shadow | boolean | No | Whether to enable the shadow effect.
Default value: **false** | | status | [ProgressStatus10+](#progressstatus10) | No| Status of the progress indicator. When this parameter is set to **LOADING**, the check update animation is played, and the **value** settings do not take effect. When the value changes from **LOADING** to **PROGRESSING**, the check update animation stops when it has reached the end state.
Default value: **ProgressStatus.PROGRESSING**| | enableScanEffect | boolean | No| Whether to enable the scan effect.
Default value: **false**| +| enableSmoothEffect10+ | boolean | No| Whether to enable the smooth effect. When this effect is enabled, the progress change to the set value takes place gradually. Otherwise, it takes place immediately.
Default value: **true**| ## LinearStyleOptions10+ | Name | Type | Mandatory| Description | | ------------- | ---------------------------- | ---- | ------------------------------------------------------------------------------------------ | | strokeWidth | [Length](ts-types.md#length) | No | Stroke width of the progress indicator. It cannot be set in percentage.
Default value: **4.0vp**| | enableScanEffect | boolean | No| Whether to enable the scan effect.
Default value: **false**| +| enableSmoothEffect10+ | boolean | No| Whether to enable the smooth effect. When this effect is enabled, the progress change to the set value takes place gradually. Otherwise, it takes place immediately.
Default value: **true**| ## ScaleRingStyleOptions10+ | Name | Type | Mandatory| Description | @@ -102,9 +106,12 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | strokeWidth | [Length](ts-types.md#length) | No | Stroke width of the progress indicator. It cannot be set in percentage.
Default value: **4.0vp** | | scaleCount | number | No | Number of divisions on the ring-style process indicator.
Default value: **120** | | scaleWidth | [Length](ts-types.md#length) | No | Scale width of the ring-style progress bar. It cannot be set in percentage. If it is greater than the value of **strokeWidth**, the default scale width is used.
Default value: **2.0vp**| +| enableSmoothEffect10+ | boolean | No| Whether to enable the smooth effect. When this effect is enabled, the progress change to the set value takes place gradually. Otherwise, it takes place immediately.
Default value: **true**| ## EclipseStyleOptions10+ -No parameter available. +| Name | Type | Mandatory| Description | +| ------------ | ---------------------------- | ---- | ------------------------------------------------------------------------------------------ | +| enableSmoothEffect10+ | boolean | No| Whether to enable the smooth effect. When this effect is enabled, the progress change to the set value takes place gradually. Otherwise, it takes place immediately.
Default value: **true**| ## ProgressStatus10+ | Name | Description | @@ -249,3 +256,38 @@ struct ProgressExample { } ``` ![capsuleProgressStyleEffect](figures/arkts-capsuleProgressStyleEffect.png) + +### Example 5 +This example shows the smooth effect. +```ts +@Entry +@Component +struct Index { + @State value: number = 0 + + build() { + Column({space: 10}) { + Text('enableSmoothEffect: true').fontSize(9).fontColor(0xCCCCCC).width('90%').margin(5) + .margin({top: 20}) + Progress({value: this.value, total: 100, type:ProgressType.Linear}) + .style({strokeWidth: 10, enableSmoothEffect: true}) + + Text('enableSmoothEffect: false').fontSize(9).fontColor(0xCCCCCC).width('90%').margin(5) + Progress({value: this.value, total: 100, type:ProgressType.Linear}) + .style({strokeWidth: 10, enableSmoothEffect: false}) + + Button('value +10').onClick(() => { + this.value += 10 + }) + .width(75) + .height(15) + .fontSize(9) + } + .width('50%') + .height('100%') + .margin({left:20}) + } +} + +``` +![progressSmoothEffect](figures/arkts-progressSmoothEffect.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-richeditor.md b/en/application-dev/reference/arkui-ts/ts-basic-components-richeditor.md index e1bc5d28fefe3653ebd05a249952da2f56d35a73..5573b1c91c348dd37c46df0ebb9dc672b74f3fc5 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-richeditor.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-richeditor.md @@ -303,7 +303,7 @@ Provides the text style information. | fontSize | [Length](ts-types.md#length) \| number | No| Font size.
Default value: **16fp**| | fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | No| Font style.
Default value: **FontStyle.Normal**| | fontWeight | [FontWeight](ts-appendix-enums.md#fontweight) \| number \| string | No| Font weight.
For the number type, the value ranges from 100 to 900, at an interval of 100. A larger value indicates a heavier font weight. The default value is **400**.
For the string type, only strings of the number type are supported, for example, **"400"**, **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**, which correspond to the enumerated values in **FontWeight**.
Default value: **FontWeight.Normal**| -| fontFamily | [ResourceStr](ts-types.md#resourcestr) \| number \| string | No| Font family. Default value: **'HarmonyOS Sans'**.
Currently, only the default font is supported.
Default font: **'HarmonyOS Sans'**| +| fontFamily | [ResourceStr](ts-types.md#resourcestr) \| number \| string | No| Font family. The HarmonyOS Sans font and [register custom fonts](../apis/js-apis-font.md) are supported.
Default font: **'HarmonyOS Sans'**| | decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | No| Style and color of the text decorative line.
Default value: {
type: TextDecorationType.None,
color: Color.Black
}| diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-span.md b/en/application-dev/reference/arkui-ts/ts-basic-components-span.md index 41565994b98dbaa17af0697226c1571bdefac2c9..5c9fa5a862602949c3a4d7b578ea6da56ff6a630 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-span.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-span.md @@ -58,6 +58,12 @@ struct SpanExample { build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) { Text('Basic Usage').fontSize(9).fontColor(0xCCCCCC) + Text() { + Span('In Line') + Span(' Component') + Span(' !') + } + Text() { Span('This is the Span component').fontSize(12).textCase(TextCase.Normal) .decoration({ type: TextDecorationType.None, color: Color.Red }) @@ -118,4 +124,4 @@ struct SpanExample { } ``` -![span](figures/span.png) +![Span](figures/span.png) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md index 8b904ffd03ba102894adeec6e8745ab9cdae687d..77e312e896de13e8ea764e57f75cca61cad2f4fa 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md @@ -37,7 +37,7 @@ Among the [universal attributes](ts-universal-attributes-size.md) and [universal | caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box.
Default value: **'#007DFF'** | | inputFilter8+ | {
value: [ResourceStr](ts-types.md#resourcestr),
error?: (value: string) => void
} | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The specified regular expression can match single characters, but not strings.
- **value**: regular expression to set.
- **error**: filtered-out content to return when regular expression matching fails.| | copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
Default value: **CopyOptions.LocalDevice**
If this attribute is set to **CopyOptions.None**, the paste operation is allowed, but the copy and cut operations are not.| -| maxLength10+ | number | Maximum number of characters in the text input.
By default, there is no maximum number of characters.| +| maxLength10+ | number | Maximum number of characters in the text input.
By default, there is no maximum number of characters.
When the maximum number of characters is reached, no more characters can be entered, and the border turns red.| | showCounter10+ | boolean | Whether to show the number of entered characters when **maxLength** is set.
Default value: **false** | | style10+ | [TextContentStyle](ts-appendix-enums.md#textcontentstyle10) | Style of the component.
Default value: **TextContentStyle.DEFAULT** | | enableKeyboardOnFocus10+ | boolean | Whether to enable the input method when the component obtains focus.
Default value: **true** | diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md index 9b9f26950f3a99233bc322e8cde3be23f2736a15..733b0b338c1a62ce6f0c17a0a87233e6109794ab 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md @@ -45,8 +45,8 @@ Among the [universal attributes](ts-universal-attributes-size.md) and [universal | selectedBackgroundColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Background color of the selected text.
If the opacity is not set, the color is opaque. For example, **0x80000000** indicates black with 50% opacity.| | caretStyle10+ | {
width: [Length](ts-types.md#length)
} | Caret style. | | caretPosition10+ | number | Caret position.| -| showUnit10+ | [CustomBuilder](ts-types.md#CustomBuilder8) | Unit for content in the component.
By default, there is no unit.| -| showError10+ | string \| undefined | Error text displayed when an error occurs.
By default, no error text is displayed.| +| showUnit10+ | [CustomBuilder](ts-types.md#CustomBuilder8) | Unit for content in the component.
By default, there is no unit.| +| showError10+ | string \| undefined | Error message displayed when an error occurs.
By default, no error message is displayed.
**NOTE**
If the parameter type is string and the input content does not comply with specifications, the error message is displayed. If the parameter type is undefined, no error message is displayed. See [Example 2](#example-2).| | showUnderline10+ | boolean | Whether to show an underline.
Default value: **false**| | passwordIcon10+ | [PasswordIcon](#passwordicon10) | Password icon to display at the end of the password text box.
By default, the system-provided icon is used.| | enableKeyboardOnFocus10+ | boolean | Whether to enable the input method when the component obtains focus.
Default value: **true** | @@ -129,7 +129,7 @@ Sets the position of the caret. | value | number | Yes | Length from the start of the string to the position where the caret is located.| ### setTextSelection10+ -setTextSelection(selectionStart: number, selectionStart: number): void +setTextSelection(selectionStart: number, selectionEnd: number): void Sets the text selection area, which will be highlighted. @@ -248,17 +248,20 @@ struct TextInputExample { ### Example 2 ```ts -// xxx.ets @Entry @Component struct TextInputExample { - @State PassWordSrc1:Resource=$r('app.media.icon') - @State PassWordSrc2:Resource=$r('app.media.icon') + @State PassWordSrc1: Resource = $r('app.media.onIcon') + @State PassWordSrc2: Resource = $r('app.media.offIcon') + @State TextError: string = undefined + @State Text: string = '' + @State NameText: string = 'test' + @Builder itemEnd() { Select([{ value: 'KB' }, { value: 'MB' }, - { value: 'GB'}, - { value: 'TB',}]) + { value: 'GB' }, + { value: 'TB', }]) .height("48vp") .borderRadius(0) .selected(2) @@ -269,30 +272,49 @@ struct TextInputExample { .selectedOptionFont({ size: 20, weight: 400 }) .optionFont({ size: 20, weight: 400 }) .backgroundColor(Color.Transparent) - .responseRegion({height:"40vp",width:"80%",x:'10%',y:'6vp'}) + .responseRegion({ height: "40vp", width: "80%", x: '10%', y: '6vp' }) .onSelect((index: number) => { console.info('Select:' + index) }) } build() { - Column() { + Column({ space: 20 }) { // Customize the password icon. - TextInput({ placeholder: 'user define password icon' }) + TextInput({ placeholder: 'Custom password icon' }) .type(InputType.Password) - .width(400) + .width(380) .height(60) - .passwordIcon({onIconSrc:this.PassWordSrc1,offIconSrc : this.PassWordSrc2}) + .passwordIcon({ onIconSrc: this.PassWordSrc1, offIconSrc: this.PassWordSrc2 }) // Show an underline. - TextInput({ placeholder: 'underline style' }) + TextInput({ placeholder: 'Underline style' }) .showUnderline(true) - .width(400) + .width(380) .height(60) .showError('Error') .showUnit(this.itemEnd.bind(this)) + + Text (`User name: ${this.Text}`) + .width('95%') + TextInput({ placeholder: 'Enter user name', text: this.Text }) + .showUnderline(true) + .width(380) + .showError(this.TextError) + .onChange((value: string) => { + this.Text = value + }) + .onSubmit(() => {// If the entered user name is incorrect, the text box will be cleared and the error message will be displayed. + if (this.Text == this.NameText) { + this.TextError = undefined + } else { + this.TextError ='Incorrect user name.' + this.Text = '' + } + }) + }.width('100%') } } ``` -![showUnit](figures/showUnit.png) +![TextInputError](figures/TextInputError.PNG) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md b/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md index 1c4f04d875cf51f6868700329791bcd2298c7226..7b3d5620b87e6c945368f0a65a8ced5fa6ce08d0 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md @@ -45,10 +45,12 @@ In addition to the [universal events](ts-universal-events-click.md), the followi ## TimePickerResult -| Name | Type | Description | -| ------ | ------ | ------- | -| hour | number | Hour portion of the selected time.| -| minute | number | Minute portion of the selected time.| +Describes a time in 24-hour format. + +| Name | Type| Description | +| ------ | -------- | ----------------------------------- | +| hour | number | Hour portion of the selected time.
Value range: [0-23]| +| minute | number | Minute portion of the selected time.
Value range: [0-59]| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md b/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md index 13ec25f92964ea6f702626768a41df16498eadb2..a560989fc99950dc7a6d3133e536f63ceebceb29 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md @@ -58,14 +58,14 @@ Since API version 9, child components are supported when **type** is set to **"c > The non-UI logic written internally needs to be encapsulated in one or more functions. ## Attributes -- You can customize the content displayed in the **\**. Depending on the **type** settings, the support for the universal attributes [background](./ts-universal-attributes-background.md), [opacity](./ts-universal-attributes-opacity.md), and [image effects](./ts-universal-attributes-image-effect.md) varies: -- When **type** is set to **SURFACE("surface")**, none of these attributes is supported. For configuration, you are advised to use the APIs provided by EGL/OpenGL ES instead. -- When **type** is set to **COMPONENT("component")**, none of these attributes is supported. For configuration, you are advised to mount child components. -- When **type** is set to **TEXTURE**, only [opacity](./ts-universal-attributes-opacity.md) and **backgroundColor** in [background](./ts-universal-attributes-background.md) are supported. For configuration of other attributes, you are advised to use the APIs provided by EGL/OpenGL ES instead. +- You can customize the content displayed in the **\**. Depending on the **type** settings, the support for the universal attributes [background](ts-universal-attributes-background.md), [opacity](ts-universal-attributes-opacity.md), and [image effects](ts-universal-attributes-image-effect.md) varies. +- When **type** is set to **SURFACE("surface")**, only the **shadow** attribute of [image effects](ts-universal-attributes-image-effect.md). For configuration of other attributes, you are advised to use the APIs provided by EGL/OpenGL ES instead. +- When **type** is set to **COMPONENT("component")**, only the **shadow** attribute of [image effects](ts-universal-attributes-image-effect.md). For configuration of other attributes, you are advised to mount child components. +- When **type** is set to **TEXTURE**, only the **backgroundColor** attribute of [background](ts-universal-attributes-background.md), the **shadow** attribute of [image effects](ts-universal-attributes-image-effect.md), and [opacity](ts-universal-attributes-opacity.md) are supported. For configuration of other attributes, you are advised to use the APIs provided by EGL/OpenGL ES instead. ## Events -When **type** is set to **SURFACE("surface")** or **TEXTURE**, the following events are supported. The [universal events](ts-universal-events-click.md) and gestures (ts-gesture-settings.md) are not supported. +When **type** is set to **SURFACE("surface")** or **TEXTURE**, the following events are supported. The [universal events](ts-universal-events-click.md) are not supported. ### onLoad diff --git a/en/application-dev/reference/arkui-ts/ts-container-list.md b/en/application-dev/reference/arkui-ts/ts-container-list.md index d8bb4a81dc8ab9aecb0fbb946d9cfe2a2c04e869..70136636685e6ce050c9b9d050c5d2e3b111b0eb 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-list.md +++ b/en/application-dev/reference/arkui-ts/ts-container-list.md @@ -286,7 +286,7 @@ struct ListLanesExample { } ``` -![list](figures/list1.gif) +![list](figures/list-alignListItem.gif) ### Example 3 diff --git a/en/application-dev/reference/arkui-ts/ts-container-listitem.md b/en/application-dev/reference/arkui-ts/ts-container-listitem.md index 86b924cdc24f71291ed592877833a14b6d5448b3..68e64c40e5d17e2369d787a605b729f262c9c2bc 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-listitem.md +++ b/en/application-dev/reference/arkui-ts/ts-container-listitem.md @@ -15,7 +15,9 @@ This component can contain a single child component. Since API version 9, this API is supported in ArkTS widgets. -**API 1**: ListItem(value?: ListItemOptions)10+ +### ListItem10+ + +ListItem(value?: ListItemOptions) **Parameters** @@ -23,15 +25,17 @@ Since API version 9, this API is supported in ArkTS widgets. | ------ | --------------------------------------------- | ---- | ------------------------------------------------------------ | | value | [ListItemOptions](#listitemoptions10) | No | Value of the list item, containing the **style** parameter of the **ListItemStyle**enum type.| -**API 2**: ListItem(value?: string)(deprecated) +### ListItem(deprecated) + +ListItem(value?: string) -This API is deprecated since API version 10. You are advised to use API 1 instead. +This API is deprecated since API version 10. You are advised to use [ListItem10+](#listitem10) instead. **Parameters** | Name| Type | Mandatory| Description| | ------ | ----------------------------- | ---- | -------- | -| value | string(deprecated) | No | N/A | +| value | string | No | N/A | ## Attributes @@ -85,7 +89,7 @@ For a list in horizontal layout, it refers to the delete item displayed below (o | Name | Type | Mandatory| Description | | ----- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| style | [ListItemStyle](#listitemstyle10) | No | Style of the list item.
Default value: **ListItemStyle.NONE**
If this parameter is set to **ListItemStyle.NONE**, no style is applied.
If this parameter is set to **ListItemStyle.CARD**, the default card style is applied, but only when **ListItemGroupStyle.CARD** is set for [\](ts-container-listitemgroup.md).
In the default card style, the list item has a 48 vp height and 100% width. It can be in focus, hover, press, selected, or disable style depending on the state.
**NOTE**
In the default card style, the list has its **listDirection** attribute fixed at **Axis.Vertical** and **alignListItem** attribute at **ListItemAlign.Center**. | +| style | [ListItemStyle](#listitemstyle10) | No | Style of the list item.
Default value: **ListItemStyle.NONE**
If this parameter is set to **ListItemStyle.NONE**, no style is applied.
If this parameter is set to **ListItemStyle.CARD**, the default card style is applied, but only when **ListItemGroupStyle.CARD** is set for [\](ts-container-listitemgroup.md).
In the default card style, the list item has a 48 vp height and 100% width. It can be in focus, hover, press, selected, or disable style depending on the state.
**NOTE**
In the default card style, the list has its **listDirection** attribute fixed at **Axis.Vertical** and **alignListItem** attribute at **ListItemAlign.Center**.| ## ListItemStyle10+ @@ -173,7 +177,7 @@ struct ListItemExample2 { this.arr.splice(index, 1) }) }, - actionAreaDistance: 80, + actionAreaDistance: 56, onEnterActionArea: () => { this.enterEndDeleteAreaString = "enterEndDeleteArea" this.exitEndDeleteAreaString = "not exitEndDeleteArea" diff --git a/en/application-dev/reference/arkui-ts/ts-container-panel.md b/en/application-dev/reference/arkui-ts/ts-container-panel.md index b0359c645851f1e28e8f3ab8a3371d3f501df89d..093b3df029ae47cd1a91e5764ff79c176c1baa24 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-panel.md +++ b/en/application-dev/reference/arkui-ts/ts-container-panel.md @@ -38,8 +38,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | fullHeight | string \| number | Panel height in the **PanelMode.Full** mode.
Default value: main axis height of the panel minus 8 vp
**NOTE**
This attribute cannot be set in percentage.| | halfHeight | string \| number | Panel height in the **PanelMode.Half** mode.
Default value: half of the main axis height of the panel
**NOTE**
This attribute cannot be set in percentage.| | miniHeight | string \| number | Panel height in the **PanelMode.Mini** mode.
Default value: **48**
Unit: vp
**NOTE**
This attribute cannot be set in percentage.| -| show | boolean | Whether to show the panel.| -| backgroundMask9+|[ResourceColor](ts-types.md#resourcecolor)|Background mask of the panel.| +| show | boolean | Whether to show the panel.
Default value: **true**| +| backgroundMask9+|[ResourceColor](ts-types.md#resourcecolor)|Background mask of the panel.
Default value: **'#08182431'**| | showCloseIcon10+ | boolean | Whether to display the close icon. The value **true** means to display the close icon, and **false** means the opposite.
Default value: **false**| ## PanelType diff --git a/en/application-dev/reference/arkui-ts/ts-motion-path-animation.md b/en/application-dev/reference/arkui-ts/ts-motion-path-animation.md index fd98aadd3525b1d6d37262125bdc544833e9d129..7220808c63086d39e8fbc37bfad65281a19d4615 100644 --- a/en/application-dev/reference/arkui-ts/ts-motion-path-animation.md +++ b/en/application-dev/reference/arkui-ts/ts-motion-path-animation.md @@ -9,9 +9,9 @@ The motion path animation is used to animate a component along a custom path. ## Attributes -| Name| Type| Default Value| Description| -| -------- | -------- | -------- | -------- | -| motionPath | {
path: string,
from?: number,
to?: number,
rotatable?: boolean
}
**NOTE**
In a path, **start** and **end** can be used to replace the start point and end point. Example:
'Mstart.x start.y L50 50 Lend.x end.y Z'
For more information, see [Path Drawing](../../ui/ui-js-components-svg-path.md).| {
'',
0.0,
1.0,
false
} | Motion path of the component.
- **path**: motion path of the translation animation. The value is an SVG path string.
- **from**: start point of the motion path.
Default value: **0.0**
Value range: [0, 1]
A value less than 0 evaluates to the value **0**. A value greater than 1 evaluates to the value **1**.
- **to**: end point of the motion path.
Default value: **1.0**
Value range: [0, 1]
A value less than 0 evaluates to the value **0**. A value larger than 1 evaluates to the value **1**.
- **rotatable**: whether to rotate along the path. | +| Name| Type| Description| +| -------- | -------- | -------- | +| motionPath | {
path: string,
from?: number,
to?: number,
rotatable?: boolean
} | Motion path of the component.
- **path**: motion path of the translation animation. The value is an SVG path string. In the value, **start** and **end** can be used in place of the start point and end point, for example, **'Mstart.x start.y L50 50 Lend.x end.y Z'**. For details, see [Path Drawing](../../ui/ui-js-components-svg-path.md).
If this parameter is set to an empty string, the path animation is not set.
- **from**: start point of the motion path.
Default value: **0.0**
Value range: [0, 1]
A value less than 0 or greater than 1 evaluates to the default value **0**.
- **to**: end point of the motion path.
Default value: **1.0**
Value range: [0, 1]
A value less than 0 or greater than 1 evaluates to the default value **1**, provided that the value of **to** is greater than or equal to the value of **from**.
- **rotatable**: whether to rotate along the path.
Default value: **false**| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-types.md b/en/application-dev/reference/arkui-ts/ts-types.md index 00799c76b97e399281f1593d182fea925bee3c23..436456b5e4c60d9808fe4b16e5dffba036bccdda 100644 --- a/en/application-dev/reference/arkui-ts/ts-types.md +++ b/en/application-dev/reference/arkui-ts/ts-types.md @@ -158,7 +158,7 @@ The **Font** type is used to set the text style. | ------ | ---------------------------------------- | ---- | ---------------------------------------- | | size | [Length](#length) | No | Font size. If the value is of the number type, the unit fp is used. The value cannot be a percentage.
Default value: **16.0** | | weight | [FontWeight](ts-appendix-enums.md#fontweight) \| number \| string | No | Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. A larger value indicates a thicker font.
Default value: **400** \| **FontWeight.Normal** | -| family | string \| [Resource](#resource) | No | Font family of the text. Use commas (,) to separate multiple fonts. The priority of the fonts is the sequence in which they are placed. An example value is **'Arial, HarmonyOS Sans'**. Currently, only the **'HarmonyOS Sans'** font is supported.| +| family | string \| [Resource](#resource) | No | Font family of the text. Use commas (,) to separate multiple fonts. The priority of the fonts is the sequence in which they are placed. An example value is **'Arial, HarmonyOS Sans'**. The HarmonyOS Sans font and [register custom fonts](../apis/js-apis-font.md) are supported.| | style | [FontStyle](ts-appendix-enums.md#fontstyle) | No | Font style.
Default value: **FontStyle.Normal** | ## Area8+ diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md index 0814773979c1fb7964b4f032a57addd1de6614eb..6191f29c57ebef1ac6280035fd5894aca2fac4d9 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md @@ -16,14 +16,14 @@ You can draw an image around a component. This API is supported in ArkTS widgets. -| Name | Type | Description | -| ------ | ---------------------------------------- | ---------------------------------------- | +| Name | Type | Description | +| ------ | ------------------------------------------------------------ | ------------------------------------------------------------ | | source | string \| [Resource](ts-types.md#resource) \| [linearGradient](ts-universal-attributes-gradient-color.md) | Source or gradient color of the border image.
**NOTE**
The border image source applies only to container components, such as **\**, **\**, and **\**.| -| slice | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Slice width of the border image.
Default value: **0** | -| width | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Width of the border image.
Default value: **0** | -| outset | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Amount by which the border image is extended beyond the border box.
Default value: **0** | -| repeat | [RepeatMode](#repeatmode) | Repeat mode of the border image.
Default value: **RepeatMode.Stretch** | -| fill | boolean | Whether to fill the center of the border image.
Default value: **false** | +| slice | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Slice width of the upper left corner, upper right corner, lower left corner, and lower right corner of the border image.
Default value: **0**
**NOTE**
If this parameter is set to a negative value, the default value is used.
When this parameter is set to a value of the [Length](ts-types.md#length) type, the value applies to the four corners in a unified manner.
When this parameter is set to a value of the [EdgeWidths](ts-types.md#edgewidths9) type:
- **Top**: slice height of the upper left or upper right corner of the image.
- **Bottom**: slice height of the lower left or lower right corner of the image.
- **Left**: slice width of the upper left or lower left corner of the image.
- **Right**: slice width of the upper right or lower right corner of the image.| +| width | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Width of the border image.
Default value: **0**
**NOTE**
If this parameter is set to a negative value, the default value is used.
When this parameter is set to a value of the [Length](ts-types.md#length) type, the value applies to the four corners in a unified manner.
When this parameter is set to a value of the [EdgeWidths](ts-types.md#edgewidths9) type:
- **Top**: width of the top edge of the border image.
- **Bottom**: width of the bottom edge of the border image.
- **Left**: width of the left edge of the border image.
- **Right**: width of the right edge of the border image.
If this parameter is set to a negative value, the value **1** is used.| +| outset | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Amount by which the border image is extended beyond the border box.
Default value: **0**
**NOTE**
If this parameter is set to a negative value, the default value is used.
When this parameter is set to a value of the [Length](ts-types.md#length) type, the value applies to the four corners in a unified manner.
When this parameter is set to a value of the [EdgeWidths](ts-types.md#edgewidths9) type:
- **Top**: amount by which the top edge of the border image is extended beyond the border box.
- **Bottom**: amount by which the bottom edge of the border image is extended beyond the border box.
- **Left**: amount by which the left edge of the border image is extended beyond the border box.
- **Right**: amount by which the right edge of the border image is extended beyond the border box.| +| repeat | [RepeatMode](#repeatmode) | Repeat mode of the source image's slices on the border.
Default value: **RepeatMode.Stretch**| +| fill | boolean | Whether to fill the center of the border image.
Default value: **false** | ## RepeatMode @@ -32,9 +32,9 @@ This API is supported in ArkTS widgets. | Name | Description | | ------- | ----------------------------------- | | Repeat | The source image's slices are tiled. Tiles beyond the border box will be clipped. | -| Stretch | The source image's slices stretched to fill the border box. | +| Stretch | The source image's slices are stretched to fill the border box. | | Round | The source image's slices are tiled to fill the border box. Tiles may be compressed when needed.| -| Space | The source image's slices are tiled to fill the border box. Extra space will be filled in between tiles. | +| Space | The source image's slices are tiled to fill the border box. Extra space will be distributed in between tiles. | ## Example @@ -77,35 +77,88 @@ struct Index { // xxx.ets @Entry @Component -struct Index { - @State outSetValue: number = 40 +struct BorderImage { + @State WidthValue: number = 0 + @State SliceValue: number = 0 + @State OutSetValue: number = 0 + @State RepeatValue: RepeatMode[] = [RepeatMode.Repeat, RepeatMode.Stretch, RepeatMode.Round, RepeatMode.Space] + @State SelectIndex: number = 0 + @State SelectText: string = 'Repeat' + @State FillValue: boolean = false build() { Row() { - Column() { + Column({ space: 20 }) { Row() { Text('This is borderImage.').textAlign(TextAlign.Center).fontSize(50) } .borderImage({ source: $r('app.media.icon'), - slice: `${this.outSetValue}%`, - width: `${this.outSetValue}px`, - outset: '5px', - repeat: RepeatMode.Repeat, - fill: false + slice: this.SliceValue, + width: this.WidthValue, + outset: this.OutSetValue, + repeat: this.RepeatValue[this.SelectIndex], + fill: this.FillValue }) - Slider({ - value: this.outSetValue, - min: 0, - max: 100, - style: SliderStyle.OutSet - }) - .margin({ top: 30 }) - .onChange((value: number, mode: SliderChangeMode) => { - this.outSetValue = value - console.info('value:' + value + 'mode:' + mode.toString()) + Column() { + Text(`borderImageSlice = ${this.SliceValue}px`) + Slider({ + value: this.SliceValue, + min: 0, + max: 100, + style: SliderStyle.OutSet + }) + .onChange((value: number, mode: SliderChangeMode) => { + this.SliceValue = value + }) + } + + Column() { + Text(`borderImageWidth = ${this.WidthValue}px`) + Slider({ + value: this.WidthValue, + min: 0, + max: 100, + style: SliderStyle.OutSet + }) + .onChange((value: number, mode: SliderChangeMode) => { + this.WidthValue = value + }) + } + + Column() { + Text(`borderImageOutSet = ${this.OutSetValue}px`) + Slider({ + value: this.OutSetValue, + min: 0, + max: 100, + style: SliderStyle.OutSet }) + .onChange((value: number, mode: SliderChangeMode) => { + this.OutSetValue = value + }) + } + + Row() { + Text('borderImageRepeat: ') + Select([{ value: 'Repeat' }, { value: 'Stretch' }, { value: 'Round' }, { value: 'Space' }]) + .value(this.SelectText) + .selected(this.SelectIndex) + .onSelect((index: number, text: string) => { + this.SelectIndex = index + this.SelectText = text + }) + } + + Row() { + Text(`borderImageFill: ${this.FillValue} `) + Toggle({ type: ToggleType.Switch, isOn: this.FillValue }) + .onChange((isOn: boolean) => { + this.FillValue = isOn + }) + } + } .width('100%') } @@ -114,4 +167,4 @@ struct Index { } ``` -![zh-cn_image_borderImage](figures/borderImage.gif) +![borderImage](figures/borderImage.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md index 3344dfa1bbd18b706c1a2318e907063555800c7e..160a2b9608ba5ca045f3e946efbbeccc2e3a8f1f 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md @@ -17,8 +17,8 @@ Universal text attributes include text style attributes applicable to text conta | fontSize | [Length](ts-types.md#length) | Font size. If the value is of the number type, the unit fp is used. The default font size is 16. This attribute cannot be set in percentage.
Since API version 9, this API is supported in ArkTS widgets.| | fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | Font style.
Default value: **FontStyle.Normal**
Since API version 9, this API is supported in ArkTS widgets.| | fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight. The string type supports only the string of the number type, for example, **400**, **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**, which correspond to the enumerated values in **FontWeight**.
Default value: **FontWeight.Normal**
Since API version 9, this API is supported in ArkTS widgets.| -| fontFamily | string \| [Resource](ts-types.md#resource) | Font family.
Default value: **'HarmonyOS Sans'**. Currently, only the default font is supported.
Since API version 9, this API is supported in ArkTS widgets.| -| lineHeight | string \| number \| [Resource](ts-types.md#resource) | Text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value of the number type, the unit fp is used.
Since API version 9, this API is supported in ArkTS widgets.| +| fontFamily | string \| [Resource](ts-types.md#resource) | Font family.
The HarmonyOS Sans font and [register custom fonts](../apis/js-apis-font.md) are supported.
Since API version 9, this API is supported in ArkTS widgets.| +| lineHeight | string \| number \| [Resource](ts-types.md#resource) | Text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value is of the number type, the unit fp is used.
Since API version 9, this API is supported in ArkTS widgets.| | decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | Style and color of the text decorative line.
Default value: {
type: TextDecorationType.None,
color: Color.Black
}
Since API version 9, this API is supported in ArkTS widgets.| diff --git a/en/application-dev/ui/arkts-layout-development-create-list.md b/en/application-dev/ui/arkts-layout-development-create-list.md index 32c4322ae5247bbf8ac79b29667593d660795806..cbb633c5d19bda73a973fff66574dd537dd51f2c 100644 --- a/en/application-dev/ui/arkts-layout-development-create-list.md +++ b/en/application-dev/ui/arkts-layout-development-create-list.md @@ -299,7 +299,7 @@ List() { }) ``` -This example draws a divider with a stroke thickness of 1 vp from a position 60 vp away from the start edge of the list to a position 10 vp away from the end edge of the list. The effect is shown in Figure 8. +This example draws a divider with a stroke thickness of 1 vp from a position 60 vp away from the start edge of the list to a position 10 vp away from the end edge of the list. The effect is shown in Figure 9. >**NOTE** > @@ -653,8 +653,6 @@ The following describes the implementation of the pull-and-refresh feature: 3. Listen for the finger lift event. If the movement reaches the maximum value, trigger data loading and display the refresh view. After the loading is complete, hide the view. - You can also use the third-party component [PullToRefresh](https://gitee.com/openharmony-sig/PullToRefresh) to implement this feature. - ## Editing a List diff --git a/en/application-dev/ui/arkts-layout-development-flex-layout.md b/en/application-dev/ui/arkts-layout-development-flex-layout.md index 8edf0f371708c81e4497025b14ae4cede434d010..a3bd3ba2950485e907252c521c6dadfd5ec7f6ce 100644 --- a/en/application-dev/ui/arkts-layout-development-flex-layout.md +++ b/en/application-dev/ui/arkts-layout-development-flex-layout.md @@ -532,7 +532,7 @@ When the size of the container in the flex layout is not large enough, the follo Text('flexBasis(100)') .flexBasis(100) - .width(200) // When width is set to 200 and flexBasis 100, the width is 100 vp, which means that the settings of flexBasis take precedence. + .width(200) // When both width and flexBasis are set, flexBasis take precedence, and the width is 100 vp. .height(100) .backgroundColor(0xD2B48C) }.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE) @@ -546,7 +546,7 @@ When the size of the container in the flex layout is not large enough, the follo ```ts Flex() { Text('flexGrow(1)') - .flexGrow(2) + .flexGrow(1) .width(100) .height(100) .backgroundColor(0xF5DEB3) diff --git a/en/application-dev/ui/arkts-routing.md b/en/application-dev/ui/arkts-routing.md index 5ccf781293c12b40eedfb6949b0ef268c79d4699..ef6b72ab27dbd5847ceb16f9b732aadbff1ec402 100644 --- a/en/application-dev/ui/arkts-routing.md +++ b/en/application-dev/ui/arkts-routing.md @@ -11,23 +11,26 @@ Page redirection is an important part of the development process. When using an **Figure 1** Page redirection ![router-jump-to-detail](figures/router-jump-to-detail.gif) -The **Router** module provides two redirection modes: [router.pushUrl()](../reference/apis/js-apis-router.md#routerpushurl9) and [router.replaceUrl()](../reference/apis/js-apis-router.md#routerreplaceurl9). The two modes determine whether the target page will replace the current page. +The **Router** module provides two redirection modes: [router.pushUrl()](../reference/apis/js-apis-router.md#routerpushurl9) and [router.replaceUrl()](../reference/apis/js-apis-router.md#routerreplaceurl9). Whether the target page will replace the current page depends on the mode used. -- **router.pushUrl()**: The target page does not replace the current page. Instead, it is pushed into the [page stack](../application-models/page-mission-stack.md). In this way, the state of the current page can be retained, and users can return to the current page by pressing the back button or calling the [router.back()](../reference/apis/js-apis-router.md#routerback) API. +- **router.pushUrl()**: The target page is pushed into the [page stack](../application-models/page-mission-stack.md) and does not replace the current page. In this mode, the state of the current page is retained, and users can return to the current page by pressing the back button or calling the [router.back()](../reference/apis/js-apis-router.md#routerback) API. -- **router.replaceUrl()**: The target page replaces the current page and destroys the current page. In this way, the resources of the current page can be released, and users cannot return to the current page. +- **router.replaceUrl()**: The target page replaces and destroys the current page. In this mode, the resources of the current page can be released, and users cannot return to the current page. >**NOTE** > ->The maximum capacity of a page stack is 32 pages. If this limit is exceeded, the [router.clear()](../reference/apis/js-apis-router.md#routerclear) API can be called to clear the historical page stack and free the memory. +>- When creating a page, configure the route to this page by following instructions in [Building the Second Page](../quick-start/start-with-ets-stage.md). +> +> +>- The maximum capacity of a page stack is 32 pages. If this limit is exceeded, the [router.clear()](../reference/apis/js-apis-router.md#routerclear) API can be called to clear the historical page stack and free the memory. -The **Router** module also provides two instance modes: **Standard** and **Single**. The two modes determine whether the target URL corresponds to multiple instances. +The **Router** module also provides two instance modes: **Standard** and **Single**. Depending on the mode, the target URL is mapped to one or more instances. -- **Standard**: standard instance mode, which is the default instance mode. Each time this API is called, a target page is created and pushed to the top of the stack. +- **Standard**: multi-instance mode. It is the default instance mode. In this mode, the target page is added to the top of the page stack, regardless of whether a page with the same URL exists in the stack. -- **Single**: singleton mode. If the URL of the target page already exists in the page stack, the page with the same URL closest to the top of the stack is moved to the top of the stack and reloaded. If the URL of the target page does not exist in the page stack, the page is redirected in standard mode. +- **Single**: singleton mode. In this mode, if the URL of the target page already exists in the page stack, the page closest to the top of the stack with the same URL is moved to the top of the stack and becomes the new page. If the URL of the target page does not exist in the page stack, the page is redirected in standard mode. -Before using the **Router** module, you need to import it to the code. +Before using the **Router** module, import it first. ```ts @@ -54,7 +57,7 @@ import router from '@ohos.router'; >**NOTE** > - >In **Standard** instance mode, the **router.RouterMode.Standard** parameter can be omitted. + >In standard (multi-instance) mode, the **router.RouterMode.Standard** parameter can be omitted. - Scenario 2: There is a login page (**Login**) and a personal center page (**Profile**). After a user successfully logs in from the **Login** page, the **Profile** page is displayed. At the same time, the **Login** page is destroyed, and the application exits when the back button is pressed. In this scenario, you can use the **replaceUrl()** API and use the Standard instance mode (which can also be omitted). @@ -76,7 +79,7 @@ import router from '@ohos.router'; >**NOTE** > - >In **Standard** instance mode, the **router.RouterMode.Standard** parameter can be omitted. + >In standard (multi-instance) mode, the **router.RouterMode.Standard** parameter can be omitted. - Scenario 3: There is a setting page (**Setting**) and a theme switching page (**Theme**). You want to click a theme option on the **Setting** page to go to the **Theme** page. In addition, you want to ensure that only one **Theme** page exists in the page stack at a time. When the back button is clicked on the **Theme** page, the **Setting** page is displayed. In this scenario, you can use the **pushUrl()** API and use the **Single** instance mode. @@ -115,7 +118,7 @@ import router from '@ohos.router'; The preceding scenarios do not involve parameter transfer. -If you need to transfer some data to the target page during redirection, you can add a **params** attribute and specify an object as a parameter when invoking an API of the **Router** module. Example: +If you need to transfer data to the target page during redirection, you can add a **params** attribute and specify an object as a parameter when invoking an API of the **Router** module. Example: ```ts @@ -150,11 +153,11 @@ function onJumpClick(): void { } ``` -On the target page, you can call the [getParams()](../reference/apis/js-apis-router.md#routergetparams) API of the **Router** module to obtain the transferred parameters. Example: +On the target page, you can call the [getParams()](../reference/apis/js-apis-router.md#routergetparams) API of the **Router** module to obtain the passed parameters. Example: ```ts -const params = router.getParams(); // Obtain the transferred parameter object. +const params = router.getParams(); // Obtain the passed parameters. const id = params['id']; // Obtain the value of the id attribute. const age = params['info'].age; // Obtain the value of the age attribute. ``` @@ -162,13 +165,13 @@ const age = params['info'].age; // Obtain the value of the age attribute. ## Page Return -After a user completes an operation on a page, the user usually needs to return to the previous page or a specified page. In this case, the page return function is required. During the return process, the data may need to be transferred to the target page, which requires the data transfer function. +Implement the page return feature so that users can return to the previous page or a specified page. You can pass parameters to the target page during the return process. **Figure 2** Page return ![router-back-to-home](figures/router-back-to-home.gif) -Before using the **Router** module, you need to import it to the code. +Before using the **Router** module, import it first. ```ts @@ -195,7 +198,7 @@ You can use any of the following methods to return to a page: }); ``` - This method allows you to return to a specified page. You need to specify the path of the target page. For this method to work, the target page must it exist in the page stack. + This method allows uesrs to return to a page with the specified path. For this method to work, the target page must exist in the page stack. - Method 3: Return to the specified page and transfer custom parameter information. @@ -209,14 +212,14 @@ You can use any of the following methods to return to a page: }); ``` - This method not only allows you to return to the specified page, but also transfer custom parameter information when returning. The parameter information can be obtained and parsed by invoking the **router.getParams()** API on the target page. + This method not only allows you to return to the specified page, but also pass in custom parameter information during the return process. The parameter information can be obtained and parsed by invoking the **router.getParams()** API on the target page. On the target page, call the **router.getParams()** API at the position where parameters need to be obtained, for example, in the **onPageShow()** lifecycle callback: ```ts onPageShow() { - const params = router.getParams(); // Obtain the transferred parameter object. + const params = router.getParams(); // Obtain the passed parameters. const info = params['info']; // Obtain the value of the info attribute. } ``` @@ -243,7 +246,7 @@ Such a dialog box can be in the [default style](#default-confirmation-dialog-box To implement this function, you can use the [router.showAlertBeforeBackPage()](../reference/apis/js-apis-router.md#routershowalertbeforebackpage9) and [router.back()](../reference/apis/js-apis-router.md#routerback) APIs provided by the **Router** module. -Before using the **Router** module, you need to import it to the code. +Before using the **Router** module, import it first. ```ts @@ -272,17 +275,16 @@ function onBackClick(): void { The **router.showAlertBeforeBackPage()** API receives an object as a parameter. The object contains the following attributes: -- **message**: content of the dialog box. The value is of the string type. - If the API is successfully called, the confirmation dialog box is displayed on the target page. Otherwise, an exception is thrown and the error code and error information is obtained through **err.code** and **err.message**. - - When the user clicks the back button, a confirmation dialog box is displayed, prompting the user to confirm their operation. If the user selects Cancel, the application stays on the current page. If the user selects OK, the **router.back()** API is triggered and the redirection is performed based on the parameters. +**message**: content of the dialog box. The value is of the string type. +If the API is successfully called, the confirmation dialog box is displayed on the target page. Otherwise, an exception is thrown and the error code and error information is obtained through **err.code** and **err.message**. +When the user clicks the back button, a confirmation dialog box is displayed, prompting the user to confirm their operation. If the user selects Cancel, the application stays on the current page. If the user selects OK, the **router.back()** API is triggered and the redirection is performed based on the parameters. ### Custom Confirmation Dialog Box To implement a custom confirmation dialog box, use APIs in the [PromptAction](../reference/apis/js-apis-promptAction.md#promptactionshowdialog) module or customize a popup window. This topic uses the APIs in the **PromptAction** module an example to describe how to implement a custom confirmation dialog box. -Before using the **Router** module, you need to import it to the code. +Before using the **Router** module, import it first. ```ts @@ -324,3 +326,63 @@ function onBackClick() { ``` When the user clicks the back button, the custom confirmation dialog box is displayed, prompting the user to confirm their operation. If the user selects Cancel, the application stays on the current page. If the user selects OK, the **router.back()** API is triggered and the redirection is performed based on the parameters. + +## Named Route + +To redirect to a [page in a shared package](../quick-start/shared-guide.md), you can use [router.pushNamedRoute()](../reference/apis/js-apis-router.md#routerpushnamedroute10). + +Before using the **Router** module, import it first. + + +```ts +import router from '@ohos.router'; +``` + +In the target page in the [shared package](../quick-start/shared-guide.md), name the [@Entry decorated custom component](../quick-start/arkts-create-custom-components.md#entryoptions10). + +```ts +// library/src/main/ets/pages/Index.ets +@Entry({ routeName : 'myPage' }) +@Component +struct MyComponent { +} +``` + +When the configuration is successful, import the named route page to the page from which you want to redirect. + +```ts +// entry/src/main/ets/pages/Index.ets +import router from '@ohos.router'; +import 'library/src/main/ets/Index.ets' // Import the named route page from the shared package library. + +@Entry +@Component +struct Index { + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text('Hello World') + .fontSize(50) + .fontWeight(FontWeight.Bold) + .margin({ top: 20 }) + .backgroundColor('#ccc') + .onClick(() => { // Click to go to a page in another shared package. + try { + router.pushNamedRoute({ + name: 'myPage', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + } + } + }) + } catch (err) { + console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); + } + }) + } + .width('100%') + .height('100%') + } +} +``` diff --git a/en/application-dev/ui/figures/relative-layout.png b/en/application-dev/ui/figures/relative-layout.png index a790ca8d5e78d1f659b61175a4e2d424522dec51..3299c95ebda23dcf7fd0364a05dbbc02f86fd57f 100644 Binary files a/en/application-dev/ui/figures/relative-layout.png and b/en/application-dev/ui/figures/relative-layout.png differ diff --git a/en/device-dev/device-test/developer_test.md b/en/device-dev/device-test/developer_test.md index a3d699e62c32a222ab10d8a8c24cf0babd48267d..d31659033970f2d9750776724a54e3857dbb5172 100644 --- a/en/device-dev/device-test/developer_test.md +++ b/en/device-dev/device-test/developer_test.md @@ -95,7 +95,7 @@ Click [here](https://gitee.com/openharmony/docs/blob/master/en/device-dev/get-co 6. Install the NFS server if the device outputs results only through the serial port. - > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > **NOTE** > > This operation applies to small-system or mini-system devices, not standard-system devices. @@ -260,7 +260,7 @@ The test framework supports multiple types of tests and provides different test { // Set a teardown function, which will be called after all test cases. } - ``` + ``` 5. Add implementation of the test cases, including test case comments and logic. ``` @@ -279,11 +279,11 @@ The test framework supports multiple types of tests and provides different test EXPECT_EQ(4, actual); } ``` - > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** - > - > The value of **@tc.require** must start with AR/SR or issue, for example, **issueI56WJ7**. + > **NOTE** + > + > The value of **@tc.require** must start with AR/SR or issue, for example, **issueI56WJ7**. -- The following uses base_object_test.cpp as an example to describe how to compile a multi-thread test case: +- The following uses **base_object_test.cpp** as an example to describe how to compile a multi-thread test case: ``` // The test case file header comment and test case comment are the same as those in the single-thread test case example. @@ -345,16 +345,17 @@ The test framework supports multiple types of tests and provides different test The procedure is as follows: 1. Add comment information to the test case file header. - > **NOTE**
The standard is the same as that of the single-thread test case. + > **NOTE** + > + > The standard is the same as that of the single-thread test case. - 2. Add the test framework header file and namespace. ``` #include #include #include using namespace testing::ext; - using namespace testing::mt; - ``` + using namespace testing::mt; + ``` 3. Add the header file of the test class. ``` #include "base_object.h" @@ -364,9 +365,11 @@ The test framework supports multiple types of tests and provides different test class AAFwkBaseObjectTest : public testing::Test {......} ``` - > **NOTE**
The standard is the same as that of the single-thread test case. + - 5. Add implementation of the test cases, including test case comments and logic. + > **NOTE** + > + > The standard is the same as that of the single-thread test case. ``` // Step 1 Set the function to be tested to return the factorial result. @@ -379,7 +382,7 @@ The test framework supports multiple types of tests and provides different test printf("Factorial Function Result : %d! = %d\n", n, result); return result; } - + // Step 2 Use an assertion to compare the obtained result with the expected result. void factorial_test() { @@ -388,13 +391,13 @@ The test framework supports multiple types of tests and provides different test std::ostringstream oss; oss << this_id; std::string this_id_str = oss.str(); - long int thread_id = atol(this_id_str.c_str()); - printf("running thread...: %ld\n", thread_id); // Output the ID of the running thread. + long int thread_id = atol(this_id_str.c_str()); + printf("running thread...: %ld\n", thread_id); // Output the ID of the running thread. EXPECT_EQ(ret, 6); } // GTEST_RUN_TASK(TestFunction) is a multi-thread startup function. The parameter is a custom function. - // If SET_THREAD_NUM() is not called, the default value 10 will be used. + // If SET_THREAD_NUM() is not called, the default value 10 will be used. HWTEST_F(AAFwkBaseObjectTest, Factorial_test_001, TestSize.Level1) { SET_THREAD_NUM(4); // Set the number of threads. It can be dynamically set in the same test suite. @@ -404,7 +407,7 @@ The test framework supports multiple types of tests and provides different test } // HWMTEST_F(TEST_SUITE, TEST_TC, TEST_LEVEL, THREAD_NUM) - // THREAD_NUM can be used to set the number of threads for executing a test case. + // THREAD_NUM can be used to set the number of threads for executing a test case. // HWMTEST_F creates a specified number of threads and executes the tested function. HWMTEST_F(AAFwkBaseObjectTest, Factorial_test_002, TestSize.Level1, 6) { @@ -412,12 +415,14 @@ The test framework supports multiple types of tests and provides different test factorial_test(); printf("Factorial_test_002 END\n"); } - // Add the multi-thread API MTEST_ADD_TASK(THREAD_ID,ThreadTestFunc). Multiple threads are registered but are not executed in this test case. Instead, they are executed later in a unified manner. This API is applicable to the multi-thread test in the scenario where multiple test cases are combined. - // THREAD_ID is used to distinguish threads and starts from 0. You can also use a random thread ID by passing in RANDOM_THREAD_ID. In this scenario, each thread ID is unique. - // Add the multi-thread API MTEST_POST_RUN() to execute the previously registered threads in a unified manner. + // Add the multi-thread API MTEST_ADD_TASK(THREAD_ID,ThreadTestFunc). Multiple threads are registered but are not executed in this test case. Instead, they are executed later in a unified manner. This API is applicable to the multi-thread test in the scenario where multiple test cases are combined. + // THREAD_ID is used to distinguish threads and starts from 0. You can also use a random thread ID by passing in RANDOM_THREAD_ID. In this scenario, each thread ID is unique. + // Add the multi-thread API MTEST_POST_RUN() to execute the previously registered threads in a unified manner. ``` - > **NOTE**
The comments for multi-thread test cases are the same as those of single-thread test cases. - + > **NOTE** + > + > The comments for multi-thread test cases are the same as those of single-thread test cases. + - About C++ test case templates: The following test case templates are provided for your reference. @@ -590,7 +595,7 @@ The test framework supports multiple types of tests and provides different test expect(info != null).assertEqual(true) }) ``` - > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > **NOTE** > > The value of **@tc.require** must start with AR/SR or issue, for example, **issueI56WJ7**. @@ -660,7 +665,7 @@ The following provides templates for different languages for your reference. ``` module_output_path = "developertest/calculator" ``` - > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > **NOTE** > > The output path is the *Part name*/*Module name*. @@ -673,7 +678,7 @@ The following provides templates for different languages for your reference. include_dirs = [ "../../../include" ] } ``` - > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > **NOTE** > > Generally, the dependency directories are configured here and directly referenced in the build script of the test case. @@ -698,7 +703,7 @@ The following provides templates for different languages for your reference. } ``` - > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > **NOTE** > > Set the test type based on actual requirements. The following test types are available: > - **ohos_unittest**: unit test @@ -719,7 +724,7 @@ The following provides templates for different languages for your reference. deps = [":CalculatorSubTest"] } ``` - > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > **NOTE** > > Grouping test cases by test type allows you to execute a specific type of test cases when required. @@ -764,7 +769,7 @@ The following provides templates for different languages for your reference. ``` module_output_path = "developertest/app_info" ``` - > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > **NOTE** > > The output path is the *Part name*/*Module name*. @@ -774,7 +779,7 @@ The following provides templates for different languages for your reference. ohos_js_unittest("GetAppInfoJsTest") { } ``` - > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > **NOTE** > > - Use the **ohos_js_unittest** template to define the JavaScript test suite. Pay attention to the difference between JavaScript and C++. > - The file generated for the JavaScript test suite must be in .hap format and named after the test suite name defined here. The test suite name must end with **JsTest**. @@ -861,7 +866,7 @@ The following provides templates for different languages for your reference. deps = [ ":GetAppInfoJsTest" ] } ``` - > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > **NOTE** > > Grouping test cases by test type allows you to execute a specific type of test cases when required. @@ -924,7 +929,7 @@ The following provides templates for different languages for your reference. ``` want_output_path = "developertest/stage_test" ``` - > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > **NOTE** > > The output path is the *Part name*/*Module name*. @@ -934,7 +939,7 @@ The following provides templates for different languages for your reference. ohos_js_stage_unittest("ActsBundleMgrStageEtsTest") { } ``` - > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > **NOTE** > > Use the **ohos_js_stage_unittest** template to define the ArkTS test suite for the stage model. @@ -979,7 +984,7 @@ The following provides templates for different languages for your reference. deps = [ ":GetAppInfoJsTest" ] } ``` - > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > **NOTE** > > Grouping test cases by test type allows you to execute a specific type of test cases when required. @@ -1010,7 +1015,7 @@ Configure the part build file to associate with specific test cases. "//test/testfwk/developer_test/examples/calculator/test:fuzztest" } ``` -> ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** > > **test_list** contains the test cases of the corresponding module. @@ -1043,7 +1048,7 @@ Perform the following steps: resource_config_file = "//system/subsystem/partA/test/resource/calculator/ohos_test.xml" } ``` - > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > **NOTE** > >- **target_name** indicates the test suite name defined in the **BUILD.gn** file in the **test** directory. **preparer** indicates the action to perform before the test suite is executed. >- **src="res"** indicates that the test resources are in the **resource** directory under the **test** directory. **src="out"** indicates that the test resources are in the **out/release/$(*part*)** directory. @@ -1103,7 +1108,7 @@ Before executing test cases, you need to modify the configuration in **developer ``` -> ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** > > If HDC is connected to the device before the test cases are executed, you only need to configure the device IP address and port number, and retain the default settings for other parameters. @@ -1115,7 +1120,7 @@ Test cases cannot be built on Windows. You need to run the following command to ./build.sh --product-name {product_name} --build-target make_test ``` -> ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** > >- **product-name**: specifies the name of the product to be compiled. >- **build-target**: specifies the test case to build. **make_test** indicates all test cases. You can specify the test cases based on requirements. @@ -1127,7 +1132,7 @@ When the build is complete, the test cases are automatically saved in **out/ohos 2. Copy **developertest** and **xdevice** from the Linux environment to the **Test** directory on Windows, and copy the test cases to the **testcase** directory. - > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > **NOTE** > > Port the test framework and test cases from the Linux environment to the Windows environment for subsequent execution. @@ -1142,7 +1147,7 @@ When the build is complete, the test cases are automatically saved in **out/ohos D:\Test\testcase\tests ``` - > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > **NOTE** > > **\** indicates whether to build test cases. **\** indicates the path for searching for test cases. @@ -1206,7 +1211,7 @@ To enable test cases to be executed on a remote Linux server or a Linux VM, map hdc_std kill hdc_std -m -s 0.0.0.0:8710 ``` - > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > **NOTE** > > The IP address and port number are default values. @@ -1214,7 +1219,7 @@ To enable test cases to be executed on a remote Linux server or a Linux VM, map ``` hdc_std -s xx.xx.xx.xx:8710 list targets ``` - > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > **NOTE** > > Enter the IP address of the device to test. @@ -1347,7 +1352,7 @@ You can obtain the test result in the following directory: ``` test/developertest/reports/xxxx_xx_xx_xx_xx_xx ``` -> ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** > > The test report folder is automatically generated. @@ -1355,9 +1360,9 @@ The folder contains the following files: | Type | Description | | ------------------------------------ | ------------------ | | result/ | Test cases in standard format.| -| log/plan_log_xxxx_xx_xx_xx_xx_xx.log | Test case logs. | -| summary_report.html | Test report summary. | -| details_report.html | Detailed test report. | +| log/plan_log_xxxx_xx_xx_xx_xx_xx.log | Test case logs. | +| summary_report.html | Test report summary. | +| details_report.html | Detailed test report. | @@ -1372,6 +1377,7 @@ When GCDA data is available, you can execute the test cases as follows for subsy run -tp partname run -tp partname1 partname2 + 2. Before compiling the version, modify the compilation options. Add **-- coverage** to the **cflags**, **cflags_cc**, and **ldflags** options in the **build.gn** file of the involved subsystem. ldflags = [ "--coverage" ] @@ -1379,6 +1385,7 @@ When GCDA data is available, you can execute the test cases as follows for subsy C++: cflags_cc = [ "--coverage" ] **Recommended**: You can also refer to the mode for the window subsystem. For details, see the files in this [pull request](https://gitee.com/openharmony/window_window_manager/pulls/1274/files). + 3. To execute coverage test cases, perform the following to install the dependencies: 1. Run the **sudo apt install lcov** command to install lcov. @@ -1403,7 +1410,9 @@ When GCDA data is available, you can execute the test cases as follows for subsy run -t UT -ss *Subsystem name* -tp **Part name** -cov coverage run -t UT MST ST -tp *Part name* -cov coverage - Note: The **-cov coverage** parameter must be added to the preceding commands. + > **NOTE** + > + > The **-cov coverage** parameter must be added to the preceding commands. 6. Obtain the coverage report from the following paths: diff --git a/en/device-dev/quick-start/quickstart-pkg-install-tool.md b/en/device-dev/quick-start/quickstart-pkg-install-tool.md index f06b229fb12e02e5733326fca06658d50101ca1f..04bcc544ce87e7d9a9c669655f43ff4fbfad35be 100644 --- a/en/device-dev/quick-start/quickstart-pkg-install-tool.md +++ b/en/device-dev/quick-start/quickstart-pkg-install-tool.md @@ -14,51 +14,37 @@ Perform the following steps on Ubuntu. 1. Run the following command to install hb and update it to the latest version: - ``` - pip3 install --user build/lite + ```shell + python3 -m pip install --user build/hb ``` 2. Set an environment variable. - - ``` + + ```shell vim ~/.bashrc ``` Copy the following command to the last line of the .bashrc file, save the file, and exit. - - ``` + + ```shell export PATH=~/.local/bin:$PATH ``` Update the environment variable. - - ``` + + ```shell source ~/.bashrc ``` -3. Run the **hb -h** command in the source code directory. If the following information is displayed, the installation is successful: - - ``` - usage: hb - - OHOS build system - - positional arguments: - {build,set,env,clean} - build Build source code - set OHOS build settings - env Show OHOS build env - clean Clean output - - optional arguments: - -h, --help show this help message and exit - ``` +3. Run the **hb help** command in the source code directory. If the following information is displayed, the installation is successful: + + ![hb_help](figures/hb_help.png) > ![icon-notice.gif](public_sys-resources/icon-notice.gif) **NOTICE** > - To uninstall hb, run the following command: -> -> ``` -> pip3 uninstall ohos-build +> +> ```shell +> python3 -m pip uninstall ohos-build > ``` > > - If any issue occurs during the hb installation, see [FAQs](quickstart-pkg-common-hberr.md). @@ -77,26 +63,26 @@ Perform the following steps on Ubuntu. 2. [Download LLVM](https://repo.huaweicloud.com/harmonyos/compiler/clang/9.0.0-36191/linux/llvm-linux-9.0.0-36191.tar). 3. Decompress the LLVM installation package to **~/llvm**. - - ``` + + ```shell tar -zxvf llvm.tar -C ~/ ``` 4. Set an environment variable. - - ``` + + ```shell vim ~/.bashrc ``` Copy the following command to the last line of the .bashrc file, save the file, and exit. - - ``` + + ```shell export PATH=~/llvm/bin:$PATH ``` 5. Validate the environment variable. - - ``` + + ```shell source ~/.bashrc ``` diff --git a/en/release-notes/changelogs/v3.2-beta4/changelogs-multimodalinput.md b/en/release-notes/changelogs/v3.2-beta4/changelogs-multimodalinput.md new file mode 100644 index 0000000000000000000000000000000000000000..282c3ed99578e7fd1406c68a185e23585a6a7baf --- /dev/null +++ b/en/release-notes/changelogs/v3.2-beta4/changelogs-multimodalinput.md @@ -0,0 +1,103 @@ +# Multimodal Input Changelog + +## cl.multimodalinput.1 Error Information Return Method Change of APIs + +The internal APIs of the following modules used service logic return values to indicate error information, which did not comply with the error code specifications of OpenHarmony. Therefore, they are modified in API version 9 and later. + - Input device management module (**@ohos.multimodalInput.inputDevice.d.ts**): third-party APIs + + - Input consumer module (**@ohos.multimodalInput.inputConsumer.d.ts**): system APIs + + - Screen hopping module (**@ohos.multimodalInput.inputDeviceCooperate.d.ts**): system APIs + + - Key injection module (**@ohos.multimodalInput.inputEventClient.d.ts**): system APIs + + - Input listening module (**@ohos.multimodalInput.inputMonitor.d.ts**): system APIs + + - Mouse pointer module (**@ohos.multimodalInput.pointer.d.ts**): system APIs and third-party APIs + +Asynchronous APIs in the preceding modules have the following changes: A parameter check error is returned synchronously; a service logic error is returned via **AsyncCallback** or the **error** object of **Promise**. No change is made to synchronous APIs. + +**Change Impacts** + +The application developed based on earlier versions needs to adapt the method for returning API error information. Otherwise, the original service logic will be affected. + +**Key API/Component Changes** + + - supportKeys(deviceId: number, keys: Array<KeyCode>, callback: AsyncCallback<Array<boolean>>): void; + - supportKeys(deviceId: number, keys: Array<KeyCode>): Promise<Array<boolean>>; + - getKeyboardType(deviceId: number, callback: AsyncCallback<KeyboardType>): void; > + - getKeyboardType(deviceId: number): Promise<KeyboardType>; + - setPointerSpeed(speed: number, callback: AsyncCallback<void>): void; + - setPointerSpeed(speed: number): Promise<void>; + - getPointerSpeed(callback: AsyncCallback<number>): void; + - getPointerSpeed(): Promise<number>; + - setPointerStyle(windowId: number, pointerStyle: PointerStyle, callback: AsyncCallback<void>): void; + - setPointerStyle(windowId: number, pointerStyle: PointerStyle): Promise<void>; + - getPointerStyle(windowId: number, callback: AsyncCallback<PointerStyle>): void; + - getPointerStyle(windowId: number): Promise<PointerStyle>; + - setPointerVisible(visible: boolean, callback: AsyncCallback<void>): void; + - setPointerVisible(visible: boolean): Promise<void>; + - isPointerVisible(callback: AsyncCallback<boolean>): void; + - isPointerVisible(): Promise<boolean>; + - on(type:"touch", receiver:TouchEventReceiver):void; + - on(type:"mouse", receiver:Callback<MouseEvent>):void; + - off(type:"touch", receiver?:TouchEventReceiver):void; + - off(type:"mouse", receiver?:Callback<MouseEvent>):void; + - injectEvent({KeyEvent: KeyEvent}): void; + - enable(enable: boolean, callback: AsyncCallback<void>): void; + - enable(enable: boolean): Promise<void>; + - start(sinkDeviceDescriptor: string, srcInputDeviceId: number, callback: AsyncCallback<void>): void; + - start(sinkDeviceDescriptor: string, srcInputDeviceId: number): Promise<void>; + - stop(callback: AsyncCallback<void>): void; + - stop(): Promise<void>; + - getState(deviceDescriptor: string, callback: AsyncCallback<{ state: boolean }>): void; + - getState(deviceDescriptor: string): Promise<{ state: boolean }>; + - on(type: 'cooperation', callback: AsyncCallback<{ deviceDescriptor: string, eventMsg: EventMsg }>): void; + - off(type: 'cooperation', callback?: AsyncCallback<void>): void; + - on(type: "key", keyOptions: KeyOptions, callback: Callback<KeyOptions>): void; + - off(type: "key", keyOptions: KeyOptions, callback?: Callback<KeyOptions>): void; + +Deprecated APIs: + - getDeviceIds(callback: AsyncCallback<Array<number>>): void; + - getDeviceIds(): Promise<Array<number>>; + - getDevice(deviceId: number, callback: AsyncCallback<InputDeviceData>): void; + - getDevice(deviceId: number): Promise<InputDeviceData>; + +Substitute APIs: + - getDeviceList(callback: AsyncCallback<Array<number>>): void; + - getDeviceList(): Promise<Array<number>>; + - getDeviceInfo(deviceId: number, callback: AsyncCallback<InputDeviceData>): void; + - getDeviceInfo(deviceId: number): Promise<InputDeviceData>; + +Changed APIs: + +Before change: + - supportKeys(deviceId: number, keys: Array<KeyCode>, callback: Callback<Array<boolean>>): void; + - getKeyboardType(deviceId: number, callback: Callback<KeyboardType>): void; + +After change: + - supportKeys(deviceId: number, keys: Array<KeyCode>, callback: AsyncCallback<Array<boolean>>): void; + - getKeyboardType(deviceId: number, callback: AsyncCallback<KeyboardType>): void; + +**Adaptation Guide** + +The following uses **setPointerVisible** as an example: + +```ts +import pointer from '@ohos.multimodalInput.pointer'; +pointer.setPointerVisible(true, (error) => { + console.log(`Set pointer visible success`); + }); + +try { + pointer.setPointerVisible(true, (error) => { + if (error) { + console.log(`Set pointer visible failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Set pointer visible success`); + }); +} catch (error) { + console.log(`Set pointer visible failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` diff --git a/zh-cn/application-dev/IDL/idl-guidelines.md b/zh-cn/application-dev/IDL/idl-guidelines.md index 16a79625eb9cad0e890761f5e245759622603a0c..421cb2f00de52978dc6fea3865f126bf61e4940f 100644 --- a/zh-cn/application-dev/IDL/idl-guidelines.md +++ b/zh-cn/application-dev/IDL/idl-guidelines.md @@ -343,11 +343,10 @@ export default { #### 客户端调用IPC方法 -客户端调用connectAbility()以连接服务时,客户端的onAbilityConnectDone中的onConnect回调会接收服务的onConnect()方法返回的IRemoteObject实例。由于客户端和服务在不同应用内,所以客户端应用的目录内必须包含.idl文件(SDK工具会自动生成Proxy代理类)的副本。客户端的onAbilityConnectDone中的onConnect回调会接收服务的onConnect()方法返回的IRemoteObject实例,使用IRemoteObject创建IdlTestServiceProxy类的实例对象testProxy,然后调用相关IPC方法。示例代码如下: +客户端调用connectServiceExtensionAbility()以连接服务时,客户端的onAbilityConnectDone中的onConnect回调会接收服务的onConnect()方法返回的IRemoteObject实例。由于客户端和服务在不同应用内,所以客户端应用的目录内必须包含.idl文件(SDK工具会自动生成Proxy代理类)的副本。客户端的onAbilityConnectDone中的onConnect回调会接收服务的onConnect()方法返回的IRemoteObject实例,使用IRemoteObject创建IdlTestServiceProxy类的实例对象testProxy,然后调用相关IPC方法。示例代码如下: ```ts import IdlTestServiceProxy from './idl_test_service_proxy' -import featureAbility from '@ohos.ability.featureAbility'; function callbackTestIntTransaction(result: number, ret: number): void { if (result == 0 && ret == 124) { @@ -392,13 +391,13 @@ var onAbilityConnectDone = { } }; -function connectAbility: void { +function connectAbility(): void { let want = { bundleName: 'com.example.myapplicationidl', abilityName: 'com.example.myapplicationidl.ServiceAbility' }; let connectionId = -1; - connectionId = featureAbility.connectAbility(want, onAbilityConnectDone); + connectionId = this.context.connectServiceExtensionAbility(want, onAbilityConnectDone); } diff --git a/zh-cn/application-dev/application-models/application-component-configuration-stage.md b/zh-cn/application-dev/application-models/application-component-configuration-stage.md index 7bc5c21d3cfb0d2f780dc84e8923399dd2437d12..620f7d76d0d88460471b16981d689e5518fd8d96 100644 --- a/zh-cn/application-dev/application-models/application-component-configuration-stage.md +++ b/zh-cn/application-dev/application-models/application-component-configuration-stage.md @@ -96,7 +96,7 @@ - **Module支持的设备类型配置** - Module支持的设备类型需要在[module.json5配置文件](../quick-start/module-configuration-file.md)中配置deviceTypes标签,如果deviceTypes标签中添加了某种设备,则表明当前的Module支持在该设备上运行。 + Module支持的设备类型需要在[module.json5配置文件](../quick-start/module-configuration-file.md)中配置[deviceTypes标签](../quick-start/module-configuration-file.md#devicetypes标签),如果deviceTypes标签中添加了某种设备,则表明当前的Module支持在该设备上运行。 - **Module权限配置** diff --git a/zh-cn/application-dev/application-models/component-startup-rules-fa.md b/zh-cn/application-dev/application-models/component-startup-rules-fa.md index 05339c898e390eacd48f90d0f83b19a8186a0dc5..a7a24fe6222f903e95a428197a898083f82d6e03 100644 --- a/zh-cn/application-dev/application-models/component-startup-rules-fa.md +++ b/zh-cn/application-dev/application-models/component-startup-rules-fa.md @@ -28,6 +28,9 @@ - [组件visible配置参考](../quick-start/module-configuration-file.md#abilities标签) - **位于后台的应用,启动组件需校验BACKGROUND权限** +> **说明:** +> 基于API 8或更早版本SDK开发的应用在启动ServiceAbility组件或DataAbility组件时不受此限制的约束。 + - 应用前后台判断标准:若应用进程获焦或所属的UIAbility位于前台则判定为前台应用,否则为后台应用 - 需校验`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 diff --git a/zh-cn/application-dev/application-models/data-share-via-want.md b/zh-cn/application-dev/application-models/data-share-via-want.md index edb540ff52f1a964bf3d7447a364b1452c0aa8a8..64b63aa9ca8496c883bcacbcde686294e96a2b8a 100644 --- a/zh-cn/application-dev/application-models/data-share-via-want.md +++ b/zh-cn/application-dev/application-models/data-share-via-want.md @@ -1,132 +1,3 @@ # 应用间使用Want分享数据 -在应用使用场景中,用户经常需要将应用内的数据(如文字、图片等)分享至其他应用以供进一步处理。以分享PDF文件为例,本文将介绍如何使用Want来实现应用间的数据分享。 - -数据分享需要使用两个UIAbility组件(分享方和被分享方)以及一个系统组件(应用分享框)。当分享方使用`startAbility()`方法发起数据分享时,系统会隐式匹配所有支持接收分享数据类型的应用,并将其展示给用户以供选择。用户选择应用后,系统将启动该应用来完成数据分享操作。 - -在本文中,我们将使用按钮的形式触发分享操作,但实际开发中并不限于此。本文主要介绍如何配置Want以实现数据分享的功能。 - -本文中涉及的两个Action为: - -- `ohos.want.action.select`:用于启动应用分享框。 -- `ohos.want.action.sendData`:用于发送单个数据记录。此Action用于将数据传递给分享方应用。 - -## 分享方 - -为了实现数据分享功能,分享方需要先拉起应用分享框并将要分享的数据传递给被分享方应用。因此,在分享方的代码中需要嵌套使用两层Want。在第一层中,使用隐式Want和`ohos.want.action.select`的action来启动应用分享框。在第二层Want中,声明要传递给被分享方应用的数据。 - -具体来说,可以将要分享的数据放在自定义字段`parameters`中,然后将包含`ohos.want.action.sendData`的action和`parameters`字段的Want作为第二层Want传递给应用分享框。被分享方应用可以通过获取参数`parameters`来获取分享的数据。 - -```ts -import common from '@ohos.app.ability.common'; - -let fileType = 'application/pdf'; -let fileName = 'TestFile.pdf'; -let fileFd = -1; // 需要获取被分享文件的FD -let fileSize; // 需要获取被分享文件的大小 - -function implicitStartAbility() { - let context = getContext(this) as common.UIAbilityContext; - let wantInfo = { - // This action is used to implicitly match the application selctor. - action: 'ohos.want.action.select', - // This is the custom parameter in the first layer of want - // which is intended to add info to application selector. - parameters: { - // The MIME type of pdf - 'ability.picker.type': fileType, - 'ability.picker.fileNames': [fileName], - 'ability.picker.fileSizes': [fileSize], - // This a nested want which will be directly send to the user selected application. - 'ability.want.params.INTENT': { - 'action': 'ohos.want.action.sendData', - 'type': 'application/pdf', - 'parameters': { - 'keyFd': { 'type': 'FD', 'value': fileFd } - } - } - } - } - context.startAbility(wantInfo).then(() => { - ... - }).catch((err) => { - ... - }) -} -``` - -> **说明:** -> -> 目前仅支持使用文件描述符(FD)格式分享数据。获取被分享文件的文件描述符和文件名,请参考[文件管理](../reference/apis/js-apis-file-fs.md)相关接口。 - -在以上代码中,使用了自定义字段`parameters`。其中,一级参数`parameters`中的字段`ability.picker.*`用于向应用选择器传递展示信息,具体字段如下: - -- `ability.picker.type`:用于渲染相应的文件类型图标。 -- `ability.picker.fileNames`:用于展示文件名。 -- `ability.picker.fileSizes`:用于展示文件大小,单位为字节。 -- `ability.picker.fileNames`和`ability.picker.fileSizes`是数组,两者一一对应。 - -效果示意如下图所示。 -![](figures/ability-startup-with-implicit-want2.png) - -## 被分享方 - -为了使分享的内容能够在被分享方识别,需要在被分享方UIAbility的[module.json5配置文件](../quick-start/module-configuration-file.md)中的skills标签进行相应的配置。其中,`actions`字段和`uris`内的`type`字段分别与分享方Want参数中`ability.want.params.INTENT`内的`action`和`type`字段进行匹配。 - -```json -{ - "module": { - ... - "abilities": [ - { - ... - "skills": [ - { - ... - "actions": [ - "action.system.home", - "ohos.want.action.sendData" - ... - ], - "uris": [ - { - "type": "application/pdf" - }, - ] - } - ] - } - ] - } -} -``` - -当用户选择分享的应用后,嵌套在`ability.want.params.INTENT`字段中的Want参数将会传递给所选应用。被分享方的UIAbility被启动后,可以在其[`onCreate()`](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate)或者[`onNewWant()`](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonnewwant)回调中获取传入的Want参数信息。 - -获取到的Want参数信息示例如下,可以使用被分享文件的文件描述符(FD)进行相应操作。 - -```json -{ - "deviceId": "", - "bundleName": "com.example.myapplication", - "abilityName": "EntryAbility", - "moduleName": "entry", - "uri": "", - "type": "application/pdf", - "flags": 0, - "action": "ohos.want.action.sendData", - "parameters": { - "component.startup.newRules": true, - "keyFd": { - "type": "FD", - "value": 36 - }, - "mime-type": "application/pdf", - "moduleName": "entry", - "ohos.aafwk.param.callerPid": 3488, - "ohos.aafwk.param.callerToken": 537379209, - "ohos.aafwk.param.callerUid": 20010014 - }, - "entities": [] -} -``` +在应用使用场景中,用户经常需要将应用内的数据(如文字、图片等)分享至其他应用以供进一步处理。Want支持实现应用间的数据分享,具体指导请参见[应用文件分享](../file-management/share-app-file.md)。 diff --git a/zh-cn/application-dev/application-models/page-mission-stack.md b/zh-cn/application-dev/application-models/page-mission-stack.md index f3150704394f9bf7735de6fa789ebba1eaba6a96..426ee7d501a30ed68f3f64f8ce41eaf1c98e31bb 100644 --- a/zh-cn/application-dev/application-models/page-mission-stack.md +++ b/zh-cn/application-dev/application-models/page-mission-stack.md @@ -47,5 +47,5 @@ MissionList任务链记录了任务之间的拉起关系,但是这个任务链 - 进入任务列表,把任务链中间某个任务清理掉。 ![mission-chain2](figures/mission-chain2.png) -- 单实例UIAbility的任务,被不同的任务反复拉起(AbilityB为单例)。 +- 单实例UIAbility的任务,被不同的任务(包括Ability或桌面)反复拉起(AbilityB为单例)。 ![mission-chain3](figures/mission-chain3.png) diff --git a/zh-cn/application-dev/application-models/service-widget-overview.md b/zh-cn/application-dev/application-models/service-widget-overview.md index 82b8937b2bde227090ef1eee9084553ce988b28f..b5fff770009696deb006cb9ef63102f5dc797d11 100644 --- a/zh-cn/application-dev/application-models/service-widget-overview.md +++ b/zh-cn/application-dev/application-models/service-widget-overview.md @@ -60,12 +60,12 @@ ArkTS卡片与JS卡片具备不同的实现原理及特征,在场景能力上 针对Stage模型卡片提供方的开发,有以下相关实例可供参考: -- [ArkTS音乐卡片(ArkTS)(Full SDK)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Beta2/code/SuperFeature/Widget/ArkTSCard/MusicControl) +- [ArkTS音乐卡片(ArkTS卡片)(Full SDK)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Beta2/code/SuperFeature/Widget/ArkTSCard/MusicControl) -- [Stage模型卡片(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Beta2/code/SuperFeature/Widget/FormExtAbility) +- [Stage模型卡片(JS卡片)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Beta2/code/SuperFeature/Widget/FormExtAbility) -- [Stage模型卡片JS与C++通信(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Beta2/code/SuperFeature/Widget/FormGame) +- [Stage模型卡片JS与C++通信(JS卡片)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Beta2/code/SuperFeature/Widget/FormGame) -- [ArkTS卡片Canvas小游戏(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Beta2/code/SuperFeature/Widget/ArkTSCard/CanvasGame) +- [ArkTS卡片Canvas小游戏(ArkTS卡片)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Beta2/code/SuperFeature/Widget/ArkTSCard/CanvasGame) -- [ArkTS卡片计算器(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Beta2/code/SuperFeature/Widget/ArkTSCard/Calculator) +- [ArkTS卡片计算器(ArkTS卡片)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Beta2/code/SuperFeature/Widget/ArkTSCard/Calculator) diff --git a/zh-cn/application-dev/connectivity/net-mdns.md b/zh-cn/application-dev/connectivity/net-mdns.md index e1171c3aa2953e6bf3ba41798a5e8a2e1eee3d6d..5a68ec8de3cb157d3b0c5729d6e53a3098a3d1bd 100644 --- a/zh-cn/application-dev/connectivity/net-mdns.md +++ b/zh-cn/application-dev/connectivity/net-mdns.md @@ -28,13 +28,13 @@ MDNS管理的典型场景有: | ohos.net.mdns.DiscoveryService | startSearchingMDNS(): void | 开始搜索局域网内的mDNS服务。 | | ohos.net.mdns.DiscoveryService | stopSearchingMDNS(): void | 停止搜索局域网内的mDNS服务。 | | ohos.net.mdns.DiscoveryService | on(type: 'discoveryStart', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MdnsError}>): void | 订阅开启监听mDNS服务的通知。 | -| ohos.net.mdns.DiscoveryService | off(type: 'discoveryStart', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MdnsError}>): void | 取消开启监听mDNS服务的通知。 | +| ohos.net.mdns.DiscoveryService | off(type: 'discoveryStart', callback?: Callback<{ serviceInfo: LocalServiceInfo, errorCode?: MdnsError }>): void | 取消开启监听mDNS服务的通知。 | | ohos.net.mdns.DiscoveryService | on(type: 'discoveryStop', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MdnsError}>): void | 订阅停止监听mDNS服务的通知。 | -| ohos.net.mdns.DiscoveryService | off(type: 'discoveryStop', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MdnsError}>): void | 取消停止监听mDNS服务的通知。 | +| ohos.net.mdns.DiscoveryService | off(type: 'discoveryStop', callback?: Callback<{ serviceInfo: LocalServiceInfo, errorCode?: MdnsError }>): void | 取消停止监听mDNS服务的通知。 | | ohos.net.mdns.DiscoveryService | on(type: 'serviceFound', callback: Callback\): void | 订阅发现mDNS服务的通知。 | -| ohos.net.mdns.DiscoveryService | off(type: 'serviceFound', callback: Callback\): void | 取消发现mDNS服务的通知。 | +| ohos.net.mdns.DiscoveryService | off(type: 'serviceFound', callback?: Callback\): void | 取消发现mDNS服务的通知。 | | ohos.net.mdns.DiscoveryService | on(type: 'serviceLost', callback: Callback\): void | 订阅移除mDNS服务的通知。 | -| ohos.net.mdns.DiscoveryService | off(type: 'serviceLost', callback: Callback\): void | 取消移除mDNS服务的通知。 | +| ohos.net.mdns.DiscoveryService | off(type: 'serviceLost', callback?: Callback\): void | 取消移除mDNS服务的通知。 | ## 管理本地服务 @@ -158,4 +158,4 @@ discoveryService.off('serviceFound', (data) => { discoveryService.off('serviceLost', (data) => { console.log(JSON.stringify(data)); }); -``` \ No newline at end of file +``` diff --git a/zh-cn/application-dev/device/location-guidelines.md b/zh-cn/application-dev/device/location-guidelines.md index d5c971342f8e0addd94d828ff86fd0054adeed09..09754cbab4fd89372169cd2e33f6f9ab2442f4e0 100644 --- a/zh-cn/application-dev/device/location-guidelines.md +++ b/zh-cn/application-dev/device/location-guidelines.md @@ -40,7 +40,7 @@ 针对位置服务,有以下相关实例可供参考: -- [`Location`:位置服务(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Beta2/code/BasicFeature/DeviceManagement/Location) +- [`Location`:位置服务(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DeviceManagement/Location) ## 申请位置权限开发指导 @@ -149,7 +149,7 @@ 以导航场景为例,实例化方式如下: ```ts - let requestInfo = {'scenario': geoLocationManager.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; + let requestInfo:geoLocationManager.LocationRequest = {'scenario': geoLocationManager.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; ``` **方式二:** @@ -179,14 +179,14 @@ 以定位精度优先策略为例,实例化方式如下: ```ts - let requestInfo = {'priority': geoLocationManager.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; + let requestInfo:geoLocationManager.LocationRequest = {'priority': geoLocationManager.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; ``` 4. 实例化Callback对象,用于向系统提供位置上报的途径。 应用需要自行实现系统定义好的回调接口,并将其实例化。系统在定位成功确定设备的实时位置结果时,会通过该接口上报给应用。应用程序可以在接口的实现中完成自己的业务逻辑。 ```ts - let locationChange = (location) => { + let locationChange = (location:geoLocationManager.Location):void => { console.log('locationChanger: data: ' + JSON.stringify(location)); }; ``` @@ -209,10 +209,11 @@ ```ts import geoLocationManager from '@ohos.geoLocationManager'; + import BusinessError from "@ohos.base"; try { let location = geoLocationManager.getLastLocation(); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -259,10 +260,11 @@ ```ts import geoLocationManager from '@ohos.geoLocationManager'; + import BusinessError from "@ohos.base"; try { let isAvailable = geoLocationManager.isGeocoderAvailable(); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -270,7 +272,7 @@ - 调用getAddressesFromLocation,坐标转化地理位置信息。 ```ts - let reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; + let reverseGeocodeRequest:geoLocationManager.ReverseGeoCodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; try { geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { if (err) { @@ -280,7 +282,7 @@ } }); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -288,7 +290,7 @@ - 调用getAddressesFromLocationName位置描述转化坐标。 ```ts - let geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; + let geocodeRequest:geoLocationManager.GeoCodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; try { geoLocationManager.getAddressesFromLocationName(geocodeRequest, (err, data) => { if (err) { @@ -298,7 +300,7 @@ } }); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -332,11 +334,12 @@ 1. 使用地理围栏功能,需要有权限ohos.permission.APPROXIMATELY_LOCATION,位置权限申请的方法和步骤见[申请位置权限开发指导](#申请位置权限开发指导)。 -2. 导入[geoLocationManager](../reference/apis/js-apis-geoLocationManager.md)模块和[wantAgent](../reference/apis/js-apis-app-ability-wantAgent.md)模块。 +2. 导入[geoLocationManager](../reference/apis/js-apis-geoLocationManager.md)模块、[wantAgent](../reference/apis/js-apis-app-ability-wantAgent.md)模块和[BusinessError](../reference/apis/js-apis-base.md)模块。 ```ts import geoLocationManager from '@ohos.geoLocationManager'; - import wantAgent from '@ohos.app.ability.wantAgent'; + import wantAgent, {WantAgent as _wantAgent} from '@ohos.app.ability.wantAgent'; + import BusinessError from "@ohos.base"; ``` 3. 创建[WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md)信息。 @@ -344,10 +347,10 @@ 场景一:创建拉起Ability的WantAgentInfo信息。 ```ts - let wantAgentObj = null; // 用于保存创建成功的wantAgent对象,后续使用其完成触发的动作。 + let wantAgentObj:_wantAgent|null = null; // 用于保存创建成功的wantAgent对象,后续使用其完成触发的动作。 // 通过WantAgentInfo的operationType设置动作类型 - let wantAgentInfo = { + let wantAgentInfo:wantAgent.WantAgentInfo = { wants: [ { deviceId: '', @@ -368,10 +371,10 @@ 场景二:创建发布[公共事件](../application-models/common-event-overview.md)的WantAgentInfo信息。 ```ts - let wantAgentObj = null; // 用于保存创建成功的WantAgent对象,后续使用其完成触发的动作。 + let wantAgentObj:_wantAgent|null = null; // 用于保存创建成功的WantAgent对象,后续使用其完成触发的动作。 // 通过WantAgentInfo的operationType设置动作类型 - let wantAgentInfo = { + let wantAgentInfo:wantAgent.WantAgentInfo = { wants: [ { action: 'event_name', // 设置事件名 @@ -397,11 +400,11 @@ } console.info('getWantAgent success'); wantAgentObj = data; - let requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; + let requestInfo:geoLocationManager.GeofenceRequest = {'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; try { geoLocationManager.on('gnssFenceStatusChange', requestInfo, wantAgentObj); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } }); ``` @@ -412,4 +415,4 @@ 针对位置开发,有以下相关实例可供参考: -- [位置服务(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Beta2/code/BasicFeature/DeviceManagement/Location) \ No newline at end of file +- [位置服务(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DeviceManagement/Location) \ No newline at end of file diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/Readme-CN.md b/zh-cn/application-dev/key-features/multi-device-app-dev/Readme-CN.md index ba597dd6a8c060715b1606aba66d18f0965dc4e9..41f4c8584b5d5fd39b9e85f3af820b5e98f4de79 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/Readme-CN.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/Readme-CN.md @@ -3,31 +3,7 @@ - [前言](foreword.md) - [简介](introduction.md) - [从一个例子开始](start-with-a-example.md) -- 应用UX设计 - - [设计原则和要点](design-principles.md) - - 应用架构设计 - - [应用导航结构设计要求](navigation-design.md) - - [应用页面结构设计](page-design.md) - - 界面布局 - - [概述](interface-layout-design-intro.md) - - 布局基础 - - [栅格系统](design-grid.md) - - [自适应布局](design-adaptive-layout.md) - - [响应式布局](design-responsive-layout.md) - - [布局基础运用案例](design-layout-cases.md) - - 人机交互 - - [交互基础](interaction-basics.md) - - [常见输入方式](common-input-modes.md) - - [交互事件归一](design-interaction-event-normalization.md) - - 视觉风格 - - [视觉基础](visual-basics.md) - - [色彩](visual-style-color.md) - - [字体](visual-style-font.md) - - [图标](visual-style-icon.md) - - [多态控件](design-polymorphic-controls.md) - - [设计自检表](design-checklist.md) - - [设计交付](design-delivery.md) - - [资源](design-resources.md) +- [应用UX设计](design-principles.md) - [工程管理](ide-using.md) - 页面开发的一多能力介绍 - [简介](page-development-intro.md) diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/common-input-modes.md b/zh-cn/application-dev/key-features/multi-device-app-dev/common-input-modes.md deleted file mode 100644 index 11f707ede0a1b66df1724b7584859b282a8296ff..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/common-input-modes.md +++ /dev/null @@ -1,54 +0,0 @@ -# 常见输入方式 - - -## 输入类型 - -**基于触控的交互** - -很多设备的屏幕都支持多点触控,允许用户通过手指或手写笔进行交互。它们与屏幕的接触状态、数量以及运动行为被识别成触控手势和操作,可以支持多种交互功能和体验(例如点击、滑动、缩放、旋转)。在多数情况下,应将触控交互作为用户首要的交互方式。 - -以下是基础的手势操作: - - | **手势操作** | **功能描述** | **图示** | -| -------- | -------- | -------- | -| 点击 | 用户通过点击某个元素触发功能或访问界面。 | ![zh-cn_image_0000001291916533](figures/zh-cn_image_0000001291916533.png) | -| 长按 | 用户通过长按某个元素触发菜单或特定模式或进入界面。长按手势发现性差,常用功能不要使用长按来触发。
场景:
- 长按操作显示弹出菜单。例如,在联系人列表中长按某个联系人。
- 长按操作显示快捷菜单。例如,长按某个桌面图标。
- 长按操作进入多选。一般用于列表或宫格界面。例如,长按信息的列表界面,长按图库的宫格界面。
- 长按操作进入编辑模式或可排序模式,并伴随振动。例如,长按闹钟的列表界面,长按桌面的空白处。
- 长按操作选择文本。例如,在文本框中长按已经输入的文字。
- 长按图标进入该图标对应的功能详情。例如,在通知面板上长按功能开关图标。 | ![zh-cn_image_0000001245596752](figures/zh-cn_image_0000001245596752.png) | -| 滑动 | 用户通过滑动来滚动列表或平移界面内容。
场景:
- 通过滑动滚动列表。
- 在内容区横向滑动切换页签。
- 通过滑动平移地图。 | ![zh-cn_image_0000001245437476](figures/zh-cn_image_0000001245437476.png) | -| 拖动 | 用户将元素从一个位置移动到另外一个位置。 | ![zh-cn_image_0000001291557665](figures/zh-cn_image_0000001291557665.png) | -| 双击 | 用户快速点击两下以放大/缩小内容、选择文字或触发特定的功能。 | ![zh-cn_image_0000001245277712](figures/zh-cn_image_0000001245277712.png) | -| 捏合 | 用户使用两个手指按住屏幕向外展开以放大内容。
使用两个手指按住屏幕向内收拢以缩小内容。
场景:
- 放大/缩小图片。例如,在查看图片界面。
- 放大/缩小内容。例如,浏览页面或者相机取景界面。 | ![zh-cn_image_0000001291677093](figures/zh-cn_image_0000001291677093.png) | - -**基于光标的交互** - -当用户使用指向设备(鼠标、触摸板、AR/VR手柄、隔空手势等)与应用程序进行间接交互时,光标指向的对象和光标本身应提供适当的视觉反馈以表达对象的可交互性和到达的准确性。同时,应考虑利用光标支持精细化操作和悬浮状态的特性(相比手指触摸),以提升应用生产力、简化交互任务和增强信息展示。 - -基于光标的交互设计亦可推广至AR/VR手柄和隔空手势等空间交互场景。 - -**基于焦点的交互** - -当用户使用键盘、智慧屏遥控器、车机摇杆/旋钮等非指向性输入方式与应用程序进行间接交互时,基于焦点的导航和交互是重要的输入手段。 - - -## 典型输入方式 - -**鼠标** - -鼠标是一种典型的基于光标的、具备像素级精度的指向型输入方式,最为适用于对用户交互具有较高精度要求的生产力应用和高密度UI的场景。 - -一般地,鼠标由左键、右键和滚轮键组成,这些按键的交互应遵循业界标准的规范功能和用户的既有使用习惯。鼠标也可以通过和不同的键盘按键进行结合,提供额外的快捷操作体验。 - -**触控板** - -触控板同时具备多指触控手势输入(触屏)和精细化指向型输入(鼠标)的特性,使得触控板既适合用于基于触摸交互优化的用户界面,也适合用于对指点精度有较高要求的生产力应用。 - -**键盘** - -键盘是一种重要的生产力输入方式,优秀的键盘使用体验应允许用户快速准确地进行文本输入、双手无需离开键盘即可在系统和应用内进行导航、访问所有的功能、以及支持无障碍体验。 - -**手写笔** - -在触屏上,手写笔是手指精细化操作的延伸,是一种像素级精度的指点设备。手写笔提供了一种直接的、自然的方式来进行数字内容书写、绘图和标注。 - -**隔空手势** - -隔空手势(非接触手势)是一种人与设备交互的新方式,用户可以在无需手持或接触设备的情况下与设备进行便捷的交互。随着技术的发展,隔空手势在默认设备、平板、车机、智慧屏、音箱、AR/VR等设备上都有一定的应用。通常情况下,隔空手势通常是符合用户直觉、文化习惯或者容易操作的动作。 diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/design-adaptive-layout.md b/zh-cn/application-dev/key-features/multi-device-app-dev/design-adaptive-layout.md deleted file mode 100644 index 3e9538789ead02d02b62eed756e1e53e6dfd49d6..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/design-adaptive-layout.md +++ /dev/null @@ -1,72 +0,0 @@ -# 自适应布局 - - -自适应布局是通过设定元素与外部容器的相对关系实现的。当外部容器大小、位置等发生变化时,元素即可以根据相对关系自动变化以适应外部环境的变化。通常自适应布局能根据vp/px变化进行无级连续的变化。 - - -## 自适应拉伸 - -某单个内容或某组内容的显示宽度不是固定值,而是通过相对参照物的方式来确定其显示宽度。当参照物的宽度发生变化时,内容或内容间距的宽度随之发生自适应拉伸。 - -左右拉伸:例如,列表开关组合中,在窗口宽度变化时,开关控件固定宽度并相对列表的右边缘位置固定,整个组合与文本宽度均自适应变化。 - -![拉伸能力](figures/拉伸能力.gif) - -均分拉伸:例如,在图标型网格中,当窗口宽度变化时,入口图标间距与图标离左右边缘间距同时均等变化。 - -![均分能力](figures/均分能力.gif) - -自适应拉伸适用于文字、普通按钮、间距等展示宽度灵活,对宽高比不敏感的内容和内容组合。 - -当可能出现的拉伸宽度不足以显示默认内容时,应根据场景选择优先保证内容完整或者优先保证其他内容的屏效,并进行截断或换行等组合适配。 - -![拉伸注意场景](figures/拉伸注意场景.png) - - -## 自适应缩放 - -组件的显示大小是固定比例,通过相对参照物的方式来确定其宽或高。当参照物的大小发生变化时,元素的大小随之发生自适应缩放。 - -完整缩放:例如,在宽度或高度变化时,时钟始终保证表盘完整展示并根据较短边决定宽高。 - -![zh-cn_image_0000001291675753](figures/zh-cn_image_0000001291675753.gif) - -占比缩放:例如,带主体和背景的插画,画面内容根据宽度变化裁切,根据高度变化按50%比例缩放。 - -![缩放案例](figures/缩放案例.gif) - -自适应缩放适用于图片、圆形按钮、banner、反应真实物体形状的图像等必须保证宽高比的内容。 - -不推荐将所有元素同时缩放、或某内容放大过大超过屏幕50%。这将导致获取信息量不增反减,不符合用户预期。 - -![4.3-2](figures/4.3-2.png) - - -## 自适应延伸 - -组件的显示数量不是固定的,而是通过相对参照物的方式来确定其显示数量。当参照物的宽度发生变化时,组件随之发生自适应延伸显示更多数量。 - -同功能内容延伸:例如,子页签和可滑动宫格在默认宽度下通过露出最后内容,提示右方有更多入口,在宽度变化时,可在每个元素宽度不变、保持滑动交互时显示更多数量。 - -![延长能力](figures/延长能力.gif) - -不同功能内容延伸或隐藏:例如,默认处于同一排的不同音乐播放按钮优先级不同,在宽度变化时可延伸或隐藏低优先级的按钮,最大化适应不同窗口尺寸。 - -![隐藏能力](figures/隐藏能力.gif) - -自适应延伸/隐藏适用于页签、操作块、推荐栏目等具有相同交互层级且有更多数据可以填充的内容。 - -注意:需要判断因隐藏而不展示的内容对功能完整性是否有影响,并考虑通过滑动或“更多”按钮提供查看使用该内容的方式。 - - -## 自适应折行 - -定义了折行能力的组件,可以根据组件容器的可用空间,体现纵向布局或者横向布局。 - -例如,在宽度足够时,操作块位于同一行,在宽度变小时,可根据内容能显示的宽度纵向排布。 - -![折行案例分镜](figures/折行案例分镜.png) - -自适应折行适用于页签、操作块、内容流等具有相同交互层级,且希望保证类型和数量完整性的内容。 - -自适应布局对应OpenHarmony系统提供的自适应布局能力中的拉伸、均分、缩放、占比、延伸、隐藏、折行。自适应布局能力详见本文“[自适应布局](adaptive-layout.md)”相关介绍。 diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/design-checklist.md b/zh-cn/application-dev/key-features/multi-device-app-dev/design-checklist.md deleted file mode 100644 index 17347db703ba3b961afa0d390d58e3b2b16ca8ef..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/design-checklist.md +++ /dev/null @@ -1,27 +0,0 @@ -# 设计自检表 - - -设计自检表详细列举出了在全场景设备设计和开发过程中应当注意的设计规则,这将帮助应用减少用户舆情且提升用户体验的一致性。 - - -自检表的要求范围分为“必须”与“推荐”两个类别。必须类一般为已总结出的较优解决方案或效果,表示相关设计需要按照此原则统一执行;推荐类指可能受应用品牌风格或业务特殊性影响,可适量做出修改。 - - -请参考以下表格范围内提出的要求对应用进行检查。 - -| **类型** | **条目** | **说明** | **类别** | -| -------- | ------------------ | ------------------------------------------------------------ | ------ | -| 应用架构 | 导航结构 | 在各设备上页面导航结构保持一致(同时出多个设备的UX设计)。 | 推荐 | -| 布局 | 拉通设计 | 拉通各设备的布局设计,保证在不同尺寸和分辨率的设备上能够无错位/不截断/不变形/不过多空白(50%以上)/不过于拥挤(间距小于16vp,明显截断)/无大图大字体地正常显示。 | 必须 | -| | 响应式设计 | 栅格布局只能占N列以及N列内部的Gutter,不包含N列两侧的Gutter。 | 必须 | -| | 响应式设计 | 明确标注使用什么类型的栅格、给出在不同断点下栅格三要素取值。 | 推荐 | -| | 响应式设计 | 按容器去对齐栅格,而不是内部子元素对齐栅格。 | 必须 | -| | 响应式设计 | 栅格除了页面布局设计外,在做局部栅格设计时,需要通过明显方式如颜色等进行标注区分,避免混淆。 | 推荐 | -| | 响应式设计 | 禁止出现标注了栅格但实际没有通过栅格进行布局设计,避免混淆。 | 必须 | -| | 自适应设计 | 非栅格设计场景下,明确标注自适应布局能力。自适应布局能力有:拉伸、均分、占比、缩放、延伸、隐藏、折行。 | 推荐 | -| 人机交互 | 输入方式 | 需保证在各设备上完整支持触摸、鼠标、触控、键盘、遥控器、摇杆等交互方式,并符合标准定义。 | 推荐 | -| | 交互归一 | 应使用系统提供的控件以达到一致的交互体验。如有定制,需保证在各场景下,不同输入设备上的操作与指南要求一致。需特别注意鼠标行为。 | 推荐 | -| 视觉风格 | 单位 | 用于界面布局的单位应全部使用vp。只针对严格控制元素尺寸的场景使用px。 | 必须 | -| | 色彩 | 用于色彩的赋值应使用分层参数。推荐支持深色模式,需保证界面在系统切换色彩模式时没有识别性问题。 | 推荐 | -| | 字体 | 使用fp为文字大小单位,需要响应系统大字体模式,确保系统调节字体大小后,界面字体能响应变化大小,并且界面布局没有出现布局错乱问题。 | 必须 | -| 多态控件 | 支持常用的控件状态 | 确保控件不同状态下的视觉效果没有缺失。控件的常用状态有:正常态、不可用态、点击态、获焦态、激活态、悬停态。 | 推荐 | \ No newline at end of file diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/design-delivery.md b/zh-cn/application-dev/key-features/multi-device-app-dev/design-delivery.md deleted file mode 100644 index 49f29e94a09f65410f508301464bebca900c51dc..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/design-delivery.md +++ /dev/null @@ -1,109 +0,0 @@ -# 设计交付 - - -## 概述 - -为了将UX设计详尽准确地实现并传递给开发者,设计师需向开发者提供必要的设计交付件,包括但不限于:应用规格说明、交互流程、视觉效果、视觉标注、视觉规格说明、切图资源、动效参数资源、音效资源等内容。 - -面向多设备多尺寸的应用UX设计交付件,以完整说明界面布局与视觉设计为主要目的,至少应包含:效果图、标注图、规格说明和切图资源。 - -下面将分别介绍不同交付内容的用途与规范。 - -![4.8-交付4件套](figures/4.8-交付4件套.png) - - -## 效果图 - -效果图是表达UX设计的关键内容,用于直观呈现目标体验的静态效果,并作为开发者与测试工程师的实现与验收依据。效果图一般为jpg或png格式。 - -在优秀的设计交付件中,针对不同前置条件下,各交互流程所途经的每个界面都应匹配效果图。对于大量重复使用的组件元素,如弹窗和即时反馈,亦可配合规格统一说明,不做过多重复设计。 - -在多设备设计中,为了清晰表达设计效果,设计师仍需要针对不同尺寸的关键界面提供符合规范的效果图。关键界面包括且不限于: - -- 应用的首页 - -- 可以从首页直接进入的各二级界面 - -- 核心使用流程途经的各界面 - -- 能体现多数界面的自适应与响应式规格的典型界面 - -不同尺寸的效果图,至少应包含小设备、中设备、大设备。根据业务涉及的设备特点,可补充超小尺寸效果,及不同设备的横竖屏效果,提前充分验证并优化UX设计体现的差异性、一致性、灵活性、兼容性。 - -对应不同设备效果图的设计画板尺寸推荐如下: - - | 设备类型 | 屏幕宽度 | 画板尺寸(vp) | -| -------- | -------- | -------- | -| 超小设备 | [0, 320) | 240\*320 | -| 小设备 | [320, 600) | 360\*780 | -| 中设备 | [600, 840) | 677\*763 | -| 大设备 | [840, +) | 1280\*800 | - -多设备效果示意图 - -![4.8-效果示意图](figures/4.8-效果示意图.png) - -> **说明:** -> - 画板尺寸为不同宽度断点下的典型设备屏幕尺寸,可根据业务具体针对的设备选择其他画板尺寸。 -> -> - 画板尺寸以vp为单位提供,根据实际设计所需精度,可统一把设计文档中所有画板设置为1倍或多倍的px尺寸。 -> -> - 当效果图需要展示一屏以上的内容,如列表内容较长时,建议保持宽度不变并增加画板高度以容纳更多内容。 - - -## 标注图 - -标注图是向开发者传递界面上每个元素详细属性,以指导代码完整实现UX设计的图像化文档。界面元素的属性包括:色彩、尺寸、字体、圆角、间距、阴影、模糊、缩放、所用的组件、自适应布局、响应式布局等。标注图一般为jpg或png格式。 - -在优秀的设计交付件中,不同类型属性的标注文本大小一致、色彩不一、互不重叠,并与效果图内容在视觉上良好区隔。标注图数量与关键界面效果图一一对应,如遇到较复杂的界面,为了更清晰说明规格,也有多张标注图对应一张效果图的情况。 - -随着设计与开发工具的演进,一些业界工具支持界面元素属性的自动识别并创建标注,也可导出支持动态展示标注的效果图文档,一般为html格式。OpenHarmony应用的设计交付同样可以借助这些工具作为标注图的补充内容,但必选的分层参数仍需设计师专门确认并手动完成标注。 - -除了尺寸、间距等强依赖于业务具体设计的参数,色彩、字体、圆角、阴影、模糊等属性应尽可能使用分层参数完成标注。 - -标注示意图 - -![4.8-标注图](figures/4.8-标注图.png) - -> **说明:** -> - 如遇到分层参数覆盖不到的属性值,可按照具体设计效果标注。此时必须详细考虑不同场景下该元素的效果。 - - -## 规格说明 - -规格说明是一份专门编写的文档,用于更完整清晰地说明界面间的通用元素与变化规则,一般为pdf格式。规格说明不是UX设计交付件中的必选项,但它能帮助设计师节省很多重复性工作,帮助开发者快速理解UX设计规格,在面向多设备的应用设计交付中非常推荐。 - -在多设备设计中,规格说明常用于并排展示同一界面在不同尺寸下的效果,并说明栅格变化规则。 - -一多规范栅格图 - -![4.8-栅格标注](figures/4.8-栅格标注.png) - - -## 切图资源 - -包含在设计效果中的素材,如图标、图片、序列帧等,应根据实际需要输出为合适的格式提供开发者置入界面内。 - -为了更好在多设备上根据设备dpi展示清晰的图像,一分优秀的应用应含有多套同名的切图资源,它们分别存放在mdpi、ldpi、xldpi、xxldpi的文件夹目录下,最终会存放到应用资源包的同名路径中。 - -多套同名切图文件夹示意图 - -![4.8-切图资源对应文件夹](figures/4.8-切图资源对应文件夹.png) - -图标资源可以是png、jpg、webp、svg等格式。推荐在多设备设计中使用svg图标资源,因为能充分利用矢量图片体积较小、可以自由缩放且不出现锯齿、可根据色彩参数实时赋色的特点,仅用一套资源即可满足复杂场景的UX规范。如使用其他位图格式如png、jpg、webp,则需分别交付各dpi下的切图资源,以达到边缘像素清晰的体验。 - -图片资源可以是png、jpg、webp等格式。与图标资源类似,一般应提供各dpi下的图片资源。在不同dpi下对边缘像素要求不高的图片如背景图,则推荐按照更高dpi提供一张资源复用到各dpi,以减少应用包大小。 - -在多设备设计中,图片也可根据设计效果,在不同宽度断点使用同一个资源,或分别交付: - -- 当图片所在组件接口提供的缩放显示机制满足UX设计效果,可以用同一个资源 - -- 当图片所在组件接口提供的缩放显示机制不满足、且不可通过简单的自定义规则实现UX效果,则推荐使用不同资源 - -夜晚单张适配多设备宽度示意图 - -![4.8-夜晚单张适配多设备](figures/4.8-夜晚单张适配多设备.png) - -晴天多张适配多设备宽度示意图 - -![4.8-晴天多张适配](figures/4.8-晴天多张适配.png) diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/design-grid.md b/zh-cn/application-dev/key-features/multi-device-app-dev/design-grid.md deleted file mode 100644 index 7f1173fafc4c356a142c37d3766f814237142789..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/design-grid.md +++ /dev/null @@ -1,20 +0,0 @@ -# 栅格系统 - - -栅格系统是一个多设备下通用的辅助定位系统,适用于应用窗口的整体布局,也支持界面局部内容使用。栅格系统由 Margin,Gutter,Column 三个属性构成。Margin是相对屏幕、窗口等父容器左右边缘的距离,决定了内容可展示的整体宽度;Gutter是每个Column的间距,决定内容间的紧密程度; Column是内容的占位元素,其数量决定了内容的布局复杂度。Margin大小、Gutter大小、Column数量综合决定Column的具体宽度。 - - -通过栅格系统进行布局,可以更好达到多设备下布局的一致性。 - - -![zh-cn_image_0000001224173302](figures/zh-cn_image_0000001224173302.png) - - -Margin、Gutter的大小、Column的数量均可自定义,界面内容跟据Column的边缘定位。通过采用不同数值调整内容信息量和紧密程度,一般推荐使用4或8的倍数。例如Margin 32vp、Gutter 16vp、Column数量为4,或Margin 40vp、Gutter 24vp、Column数量为8。 - - -![栅格系统例](figures/栅格系统例.png) - - -栅格系统对应OpenHarmony系统提供的布局能力中的栅格布局,详见本文 “[栅格布局](responsive-layout.md#栅格布局)”相关介绍。 - diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/design-interaction-event-normalization.md b/zh-cn/application-dev/key-features/multi-device-app-dev/design-interaction-event-normalization.md deleted file mode 100644 index 21d43d67cacb5fbaf07ea6c6f645dd416b65844f..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/design-interaction-event-normalization.md +++ /dev/null @@ -1,54 +0,0 @@ -# 交互事件归一 - - -本章节描述了在多种交互任务或场景下,应用在触屏上和其它常用的输入方式(例如鼠标、触摸板、键盘)上分别对应的正确的交互规则。**设计师和开发者应保证在当前输入方式下应用能够以正确的、符合用户习惯的交互规则进行响应。** - - -![zh-cn_image_0000001224333656](figures/zh-cn_image_0000001224333656.png) - - -## 打开/切换对象 - -用户通过点击某个元素触发功能、访问新页面、或改变自身状态。 - -| **输入方式** | **交互行为** | **示意** | -| -------- | -------- | -------- | -| 触屏 | 单指单击 | ![zh-cn_image_0000001280472681](figures/zh-cn_image_0000001280472681.png) | -| 鼠标 | 左键单击 / 左键双击 | ![zh-cn_image_0000001236472600](figures/zh-cn_image_0000001236472600.png) | -| 触摸板 | 单指单击 / 单指双击 | ![zh-cn_image_0000001280232265](figures/zh-cn_image_0000001280232265.png) | -| 键盘 | 移动焦点到对象上后按下Space键 | ![zh-cn_image_0000001280472701](figures/zh-cn_image_0000001280472701.png) | - -一般地,触屏手指的按下/抬起行为对应于光标的按下/抬起行为。 - -在一些特殊场景,可能会存在使用鼠标/触摸板双击打开对象的交互方案,例如打开桌面应用或文件。此类情况需由应用单独特殊处理,且同一功能不能同时支持单击和双击两种交互方式。 - - -## 显示菜单 - -某个元素上显示弹出菜单或快捷方式菜单。 - -![zh-cn_image_0000001268533753](figures/zh-cn_image_0000001268533753.jpg) - -| **输入方式** | **交互行为** | -| -------- | -------- | -| 触屏 | 单指长按 | -| 鼠标 | 右键单击/左键长按(保留触屏习惯) | -| 触摸板 | 双指轻单击/重单击/单指重长按(保留触屏习惯) | -| 键盘 | (无通用操作) | - -这里的菜单指的是广义的菜单,即用于展示用户可执行的操作的临时性弹出窗口。 - -凡是在触屏上通过长按显示的菜单,都需要支持鼠标右键单击和触摸板双指单击的触发方式。 - - -## 拖拽对象 - -直接指向某个元素并移动到界面其他位置 - -![zh-cn_image_0000001268653953](figures/zh-cn_image_0000001268653953.png) - - | **输入方式** | **交互行为** | -| -------- | -------- | -| 触屏 | 长按某对象后触发可拖拽状态,然后移动手指改变对象位置。 | -| 鼠标 / 触摸板 | 鼠标左键或触摸板单指按下即可拖拽对象(无需长按等待)。 | -| 键盘 | (无通用操作) | diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/design-layout-cases.md b/zh-cn/application-dev/key-features/multi-device-app-dev/design-layout-cases.md deleted file mode 100644 index 3a0e6ac6caccbd319aa4bda045073c6535e5366f..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/design-layout-cases.md +++ /dev/null @@ -1,66 +0,0 @@ -# 布局基础运用案例 - - -## 平级导航的复合网格视图 - -平级导航的复合网格视图常出现在同时展示多种不同内容的界面。 - -例如,市场类应用作为典型的平级导航,其首页不同板块采用了不同布局能力。 - -![一多-布局1](figures/一多-布局1.png) - -- 标题栏与搜索栏:因元素单一、位置固定在顶部,因此适合采用自适应拉伸,并在大尺寸界面中从纵排变为横排,充分利用顶部区域。 - -- 运营横幅:在小设备上默认为多张轮播展示,随宽度变化采用自适应缩放,在中尺寸界面通过重复布局变为并排多张。 - -- 图标型网格:对于数量固定、且子内容重要程度相同的网格,需保证完全展示,可采用均分拉伸。对于数量不限的网格,则采用自适应延伸,在更大宽度上展示更多数量。 - -- 底部导航栏:导航类控件本身综合了均分和折行,在宽度变化时能占用均等宽度并在足够宽度下并排,当在大尺寸界面中,挪移到左边,使不同页签距离更近、同时符合视觉走向。 - -在横竖屏切换时,也保持了一致的布局能力,实际上完成了大尺寸和中尺寸的切换。 - -![一多-布局2](figures/一多-布局2.png) - -当界面出现在智慧屏上,虽然同是大尺寸界面,为了符合设备样式和遥控器交互规则,搜索栏转化为图标入口,导航栏挪移到页面上部。 - -![一多-布局3](figures/一多-布局3.png) - - -## 层级导航的列表视图 - -层级导航的列表视图常出现在多类简单信息并列或多入口业务入口的界面。 - -例如,设置类应用作为典型的层级导航,其列表控件采用自适应拉伸。 - -![布局基础案例-层级导航-设置](figures/布局基础案例-层级导航-设置.png) - -在中尺寸设备中,为避免中间区域空白过大,采用缩进布局,大尺寸设备中,为充分利用横向空间,建议采用栅格系统形成分栏效果,并让列表元素在各自区域保持拉伸。 - - -## 专辑详情页面 - -专辑详情不限于展示音乐内容,也用于展示视频、短视频、电台、书本等内容类合集。 - -例如,歌单类界面作为典型的内容垂类页面,其总体分为标题栏、歌单信息、歌单操作、歌单列表、播放栏几个板块。 - -- 标题栏:采用自适应拉伸。 - -- 歌单信息:采用自适应缩放,并在中尺寸界面进行缩进处理使内容呈现协调。 - -- 歌单操作:板块内部采用均分拉伸,在小尺寸设备上利用纵向空间、中尺寸设备上挪移到歌单封面右边。 - -- 歌单列表:板块内部采用左右拉伸,在中尺寸设备上可与歌单信息使用相同缩进布局。 - -- 播放栏:固定在界面底部,保持左右拉伸即可。 - -![页面布局-布局基础案例-歌单详情页面布局能力360-800vp](figures/页面布局-布局基础案例-歌单详情页面布局能力360-800vp.png) - -在横竖屏切换时,完成了中尺寸和大尺寸的切换。歌单列表板块进行挪移的同时,内部采用了重复布局。 - -歌单信息和歌单操作板块因较小宽高比,挪移到上下排布。 - -![页面布局-布局基础案例-歌单详情页面布局能力800-1280vp](figures/页面布局-布局基础案例-歌单详情页面布局能力800-1280vp.png) - -当界面出现在智慧屏上,为了符合沉浸简约的设备信息和遥控器交互规则,将部分歌单信息替代原来标题栏的位置,并取消播放栏。同时歌单列表居左,更方便遥控器选择。 - -![页面布局-布局基础案例-歌单详情页面布局能力1280-1920vp](figures/页面布局-布局基础案例-歌单详情页面布局能力1280-1920vp.png) diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/design-polymorphic-controls.md b/zh-cn/application-dev/key-features/multi-device-app-dev/design-polymorphic-controls.md deleted file mode 100644 index 6693a67912b6d6afb7ec199c54cdfef44422a7ec..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/design-polymorphic-controls.md +++ /dev/null @@ -1,36 +0,0 @@ -# 多态控件 - - -为了支持多设备,应用需要能够在不同的设备上运行,控件作为应用的基础组成部分,需要支持不同的设备,且在视觉、交互、动效等表现形式上针对设备进行必要的调整,达到最佳体验。因此,同一控件在不同的设备上会呈现出不同的形态,称为多态控件。 - - -![zh-cn_image_0000001268129090](figures/zh-cn_image_0000001268129090.png) - - -多态控件应该具备以下特点: - - -- 覆盖默认设备、平板,兼顾智慧屏、车机、智能穿戴等终端。 - -- 场景一致性。在对应的使用场景下,其交互、视觉、动效要保持一致,在设计上属性参数保持一致或差异化。 - -- 针对设备做优化。多态控件在不同的设备上的呈现应该是该设备下的最佳效果,因此在保证一致性的同时,还需要针对设备的特点进行优化。 - - -## 控件的状态 - -- 控件的状态是一种视觉呈现,用于展示控件当前处于何种交互阶段。不同控件的相同状态应该保持一致的视觉风格,且应该清晰可见。 - -- 应用可能部署在不同设备上供用户使用,有些设备会支持多种输入方式。例如平板可以连接蓝牙键盘和鼠标来做文字编辑工作,此时控件需要同时满足键盘和鼠标交互,需要支持获焦态和悬停态,如果控件没有支持这两种状态,在使用键盘走焦时或鼠标悬停时,控件就无法通过呈现出相应的状态为用户提供正确的视觉引导。OpenHarmony默认提供多种交互方式的控件实现,方便开发者支持多种输入方式和交互归一。 - -常见的状态类型: - -| | | | -| -------- | -------- | -------- | -| ![zh-cn_image_0000001268288974](figures/zh-cn_image_0000001268288974.gif)
**正常态**
表明当前控件可交互。 | ![zh-cn_image_0000001268608890](figures/zh-cn_image_0000001268608890.gif)
**不可用态**
表明当前控件不可交互。一般使用灰显的方式呈现。 | ![zh-cn_image_0000001317208945](figures/zh-cn_image_0000001317208945.gif)
**点击态**
表明当前控件当前处于点击状态。
操作:手指或鼠标按下且未释放。 | -| ![zh-cn_image_0000001317488873](figures/zh-cn_image_0000001317488873.gif)
**获焦态**
表明当前控件处于焦点状态。操作:
- 键盘或遥控器通过方向键将焦点从一个控件移动到另外一个控件。
- 通过语音操作,使得控件获得焦点。 | ![zh-cn_image_0000001317089061](figures/zh-cn_image_0000001317089061.gif)
**激活态**
表明当前控件处于激活的状态。用于有多个元素可获焦的控件
操作:焦点处在页签控件的某个页签上时,该页签获焦。点击此页签,该页签被激活。 | ![zh-cn_image_0000001317328893](figures/zh-cn_image_0000001317328893.gif)
**悬停态**
表明当前控件处于鼠标悬停的状态。
操作:将鼠标悬停在控件之上。 | - - -## 弹出框 - -弹出框是一种模态窗口,在弹出框消失之前,用户无法操作其他界面内容,干扰性比较强。通常用来展示用户当前需要的或用户必须关注的信息或操作,其他情况不建议使用弹出框,可考虑通知等其他非模态窗口。 弹出框的内容通常是不同控件进行组合布局。例如文本(可带格式,如缩进、链接、粗体等)、列表、输入框、网格、图标或图片等,常用于选择或确认信息。 diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/design-principles.md b/zh-cn/application-dev/key-features/multi-device-app-dev/design-principles.md index 9b2af2b3c312ec3c47d1d2abf9b165f97eaa52a5..ed54906c14ded2f11790cbf51952a14093be0a27 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/design-principles.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/design-principles.md @@ -1,88 +1,3 @@ -# 设计原则和要点 +# 应用UX设计 -## 设计原则 - -当为多种不同的设备开发应用时,有如下设计原则: - -**差异性** - -充分了解所要支持的设备,包括屏幕尺寸、交互方式、使用场景、用户人群等,对设备的特性进行针对性的设计。 - -**一致性** - -除了要考虑每个设备的特性外,还需要考虑不同设备的共性,并使用通用性设计方法提供既符合设备差异性,又具有跨设备一致性的设计,从而减少用户学习的难度,降低应用开发的成本。 - -**灵活性** - -在硬件能力、交互方式、使用场景类似的设备上,应主要考虑布局位置、内容宽度、横向组件数量的调整,避免出现因横竖屏切换、窗口尺寸变化造成的界面元素不合理空白、模糊、变形、截断的问题。 - -**兼容性** - -在硬件能力、交互方式、使用场景差异较大的设备上,除了考虑布局位置、内容宽度、横向组件数量,还需支持不同的输入方式、考虑功能架构的调整,避免出现输入不识别、功能不可用、使用困难的问题。 - -## 设计要点 - -很多用户的多设备体验以默认设备为核心或从默认设备往外延伸,因此,围绕全场景体验的OpenHarmony UX设计,将优先确保用户在不同的设备上获得跟使用默认设备类似的体验,同时充分利用设备的优势使体验最大化。 - -在进行OpenHarmony的多设备应用设计时,需考虑应用以下内容: - -### 自适应应用架构 - -使用自适应应用架构,可以确保应用在不同终端上,以最佳的导航形式来访问应用。OpenHarmony 在开发SDK上提供了便利,开发者可以通过简单配置轻松完成,无需从0开始构建。 - -例如:默认设备上的底Tab的结构,在Pad上一般使用侧边Tab来代替,在大屏上则是顶部Tab。 - -![一多-1-1](figures/一多-1-1.png) - -更多应用架构的设计内容,详见:应用架构下的[应用导航结构设计要求](navigation-design.md)和[应用页面结构设计](page-design.md)。 - -### 响应式界面布局 - -应用会在不同的场景下使用,常见的有横竖屏切换、分屏。这些场景会导致界面的尺寸和长宽比例发生变化。因此需要考虑内容的响应式布局,确保在各种场景下都有最佳的显示效果。 - -OpenHarmony 提供了多种布局能力,开发者通过组合运用使内容布局更符合业务需要与用户预期。 - -例如:默认设备上的滚动banner,在其他设备上可进行延伸,平板上露出更多banner,大屏上完全显示两张。 - -![一多-概述-界面布局-banner例图](figures/一多-概述-界面布局-banner例图.png) - -在不同类型的设备上,界面的尺寸和比例更为多样,再加上使用上的差异,导致设计上更为复杂。为此,可以考虑使用分栏布局、重复布局、挪移布局、缩进布局,进一步解决内容的显示问题。 - -例如:默认设备上上下排布的大图与列表,在长宽比例更大的设备上可挪移到左右展示。 - -![概述-界面布局-歌单详情高保真](figures/概述-界面布局-歌单详情高保真.png) - -更多界面布局的设计内容,详见:[界面布局](interface-layout-design-intro.md)。 - -### 交互归一 - -交互归一描述了在多种交互任务或场景下,应用在触屏上和其它常用的输入方式(例如鼠标、触摸板、键盘)上分别对应的正确的交互规则。设计师和开发者应保证在当前输入方式下应用能够以正确的、符合用户习惯的交互规则进行响应。通常情况下,系统已经做好了这些事情,开发者只需正确调用。如果您的操作比较特别,您需要考虑多端上的交互归一,以确保用户体验的一致。 - -更多交互归一的设计内容,详见:[人机交互](interaction-basics.md)。 - -### 视觉参数化 - -通过参数,方便的调整各端的视觉,使得各端具备该设备特有的风格。在OpenHarmony中,边距、圆角、阴影、字体大小等,都可以通过参数来进行调整。 - -![画板copy](figures/画板copy.png) - -更多视觉参数化的设计内容,详见:[视觉风格](visual-basics.md)。 - -### 多态控件 - -应用在多设备上运行,设备也可在不同交互方式下使用。控件作为应用的基础组成部分,需要支持不同的设备,且在视觉、交互、动效等表现形式上针对设备进行必要的调整,达到最佳体验。因此,同一控件在不同的设备上会呈现出不同的形态,称为多态控件。 - -OpenHarmony默认提供支持多设备的控件,开发者可以直接使用并对不同状态进行自定义。例如平板可以连接蓝牙键盘和鼠标来做文字编辑工作,此时控件需要同时满足键盘和鼠标交互,需要支持获焦态和悬停态。 - -### 针对性优化 - -在上述设计内容以外,在具体设备上,推荐针对性地进行特殊的操作和布局优化,使之符合当前设备的使用习惯。 - -例如:在以键鼠操作的界面上,为确保用户的使用习惯,需要提供额外的设计。 - -| **以触控为主** | **以键鼠操作为主** | -| -------- | -------- | -| 下拉刷新 | 界面上提供“刷新”图标或适配F5快捷键 | -| 滑动多选 | 鼠标框选 | -| 下拉关闭 | 界面上提供“关闭”图标 | -| 长按浮起拖拽 | 鼠标直接拖拽 | +应用UX设计:一多的应用UX设计需遵循通用设计规则,应该考虑多设备的“差异性”、“一致性”、“灵活性”和“兼容性。详细规范请参见[应用UX设计原则](../../../design/ux-design/app-ux-design.md) \ No newline at end of file diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/design-resources.md b/zh-cn/application-dev/key-features/multi-device-app-dev/design-resources.md deleted file mode 100644 index 672ea89fa456f30e8da8c63255f44b44ee489595..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/design-resources.md +++ /dev/null @@ -1,30 +0,0 @@ -# 资源 - - -为方便UX设计师以及开发者参考使用,本文特提供: - - -- [分层参数](visual-basics.md)的场景、id、参数详细对照表,[OpenHarmony_系统资源分层设计表_V1.0.xlsm](OpenHarmony_系统资源分层设计表_V1.0.xlsm) - -- 符合规范的[设计交付件](design-delivery.md)样例,[OpenHarmony_天气应用UX设计交付件_V1.0.zip](OpenHarmony_天气应用UX设计交付件_V1.0.zip) - - -系统资源分层设计表列出了当前OpenHarmony中可用系统资源id及其在不同类型设备上的取值,它由六张子表组成,各个子表的含义如下所示。 - - -| 表格 | 简介 | -| -------- | -------- | -| 应用色彩参数 | 在**应用开发**过程中可以使用的**色彩**相关的系统资源。 | -| 应用圆角参数 | 在**应用开发**过程中可以使用的**圆角**相关的系统资源。 | -| 应用字体参数 | 在**应用开发**过程中可以使用的**字体**相关的系统资源。 | -| 应用间距参数 | 在**应用开发**过程中可以使用的**间距**相关的系统资源。 | -| 服务卡片参数 | 在**服务卡片开发**过程中可以使用的系统资源。 | -| 不透明度数值速查表 | 用于将不透明度在**百分比表示形式**和**十六进制表示形式**之间快速转换的速查表。 | - - -> **说明:** -> - 推荐应用相关系统参数仅在应用开发场景中使用,卡片相关系统参数仅在卡片开发场景中使用。 -> -> - 同一系统参数在不同类型的设备上有不同的取值,当前仅提供了系统参数在默认设备上的取值,后续会针对不同设备类型做补充。 -> -> - 颜色可以用“RGB”或“ARGB”形式表示,采用“RGB”表示的颜色,完全不透明;采用“ARGB”表示的颜色,其不透明度由“A”(Alpha通道)确定。如“\#7FFF0000”代表不透明度为50%的红色,“\#FFFF0000”和“\#FF0000”都表示不透明度为100%(即完全不透明)的红色。 diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/design-responsive-layout.md b/zh-cn/application-dev/key-features/multi-device-app-dev/design-responsive-layout.md deleted file mode 100644 index 6ce7b3c598b1881d36f34fdd397e8291bf87283d..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/design-responsive-layout.md +++ /dev/null @@ -1,51 +0,0 @@ -# 响应式布局 - - -当基本的自适应布局无法满足多终端上屏幕的体验要求时,我们需要针对不同终端的屏幕特点,设定容器与栅格的关系达到响应式的布局。通常响应式布局能根据栅格断点变化进行有级变化。 - - -## 栅格断点系统 - -根据设备的水平宽度,OpenHarmony提供了断点系统,覆盖超小、小、中、大 四种屏幕类型,并结合栅格系统默认提供了对应 Column 的数量关系。不同的设备根据自身屏幕水平宽度,在不同的断点范围,系统将自动匹配不同数量的栅格。应用也可针对具体界面自定义栅格。 - -![删格](figures/删格.png) - -栅格断点系统与日常使用的设备屏幕类型有一定的对应关系,例如:超小对应智能穿戴设备,小对应默认设备,中对应平板竖屏,大对应智慧屏与平板横屏。设计师可面向希望运行的设备进行所属屏幕类型的适配。 - -随着智能设备种类的增加,越来越多产品在四种屏幕类型上具备不同的交互能力,如支持触摸的运动相机(小)、仅支持遥杆的手持云台(小-中)、不可移动的智能台灯(中-大)等,需结合具体设备交互进行对应设计,不可一概而论。 - - -## 缩进布局 - -为了在宽屏上内容显示有更好的效果,在不同宽度的设备上进行不同缩进效果。 - -![缩进布局](figures/缩进布局.gif) - -缩进适用于,因宽度明显变大,内容拉伸以后导致屏幕空白内容超过50%,或文本内容过长(每行大于30字),但没有上下级界面可供同时展示或上下级界面不适合同时显示的场景。 - -OpenHarmony提供的默认实现为,当栅格为8column或12column时可以响应6column和8column的缩进布局。 - - -## 挪移布局 - -利用屏幕的宽度优势,将原先的上下布局切换成左右布局。 - -例如,上下排布的插画和文字,横屏后左右排布。 - -![挪移布局](figures/挪移布局.gif) - -挪移布局适用于横竖屏切换,以及类似的宽高比明显变化(大于200%)同时希望保证内容完整的场景。 - - -## 重复布局 - -利用屏幕的宽度优势,将相同属性的组件横向并列排布。 - -![重复布局](figures/重复布局.gif) - -重复布局适用于对宽高比敏感的图片和及组合内容,当内容缩放以后导致原图放大超过150%的场景。 - -OpenHarmony栅格系统提供的分栏实现为,当栅格为8column或12column时可以将默认4栅格的页面整体进行重复布局。 - - -响应式布局对应OpenHarmony系统提供的布局能力中的栅格断点系统和媒体查询,详见本文 “[响应式布局](responsive-layout.md)”相关介绍。 diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/4.3-2.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/4.3-2.png deleted file mode 100644 index 61a66c3ba854dd98176ed31a3d247c744427de85..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/4.3-2.png and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/4.8-\344\272\244\344\273\2304\344\273\266\345\245\227.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/4.8-\344\272\244\344\273\2304\344\273\266\345\245\227.png" deleted file mode 100644 index fb7fbc7d9357e2f6ffe5adaf8925bb6095df1764..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/4.8-\344\272\244\344\273\2304\344\273\266\345\245\227.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/4.8-\345\210\207\345\233\276\350\265\204\346\272\220\345\257\271\345\272\224\346\226\207\344\273\266\345\244\271.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/4.8-\345\210\207\345\233\276\350\265\204\346\272\220\345\257\271\345\272\224\346\226\207\344\273\266\345\244\271.png" deleted file mode 100644 index cf778edbe43256248a3b4aa3c67bf7ae5b6414e6..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/4.8-\345\210\207\345\233\276\350\265\204\346\272\220\345\257\271\345\272\224\346\226\207\344\273\266\345\244\271.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/4.8-\345\244\234\346\231\232\345\215\225\345\274\240\351\200\202\351\205\215\345\244\232\350\256\276\345\244\207.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/4.8-\345\244\234\346\231\232\345\215\225\345\274\240\351\200\202\351\205\215\345\244\232\350\256\276\345\244\207.png" deleted file mode 100644 index e85a902f41ff00fa408d7c340bdc8ba7371c5ddc..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/4.8-\345\244\234\346\231\232\345\215\225\345\274\240\351\200\202\351\205\215\345\244\232\350\256\276\345\244\207.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/4.8-\346\225\210\346\236\234\347\244\272\346\204\217\345\233\276.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/4.8-\346\225\210\346\236\234\347\244\272\346\204\217\345\233\276.png" deleted file mode 100644 index 04326bb88829e18cb51cd564e007b65809f7e5f3..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/4.8-\346\225\210\346\236\234\347\244\272\346\204\217\345\233\276.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/4.8-\346\231\264\345\244\251\345\244\232\345\274\240\351\200\202\351\205\215.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/4.8-\346\231\264\345\244\251\345\244\232\345\274\240\351\200\202\351\205\215.png" deleted file mode 100644 index 520a1c1d2db2f5877619b027db9d2229797c7d77..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/4.8-\346\231\264\345\244\251\345\244\232\345\274\240\351\200\202\351\205\215.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/4.8-\346\240\205\346\240\274\346\240\207\346\263\250.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/4.8-\346\240\205\346\240\274\346\240\207\346\263\250.png" deleted file mode 100644 index 858d077aefe1055217b5b922a9b68dfb579037c3..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/4.8-\346\240\205\346\240\274\346\240\207\346\263\250.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/4.8-\346\240\207\346\263\250\345\233\276.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/4.8-\346\240\207\346\263\250\345\233\276.png" deleted file mode 100644 index b221e88e4a0b2132fa2002dccc43e6f5690c40d8..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/4.8-\346\240\207\346\263\250\345\233\276.png" and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/8vp.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/8vp.png deleted file mode 100644 index 951b9a878b421e9e23f1bd704aec024af0485485..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/8vp.png and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/basic_guester.jpg b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/basic_guester.jpg index fc34f6fc746ab1a775a3ff35e4734dc403f415ea..ccf2a4827a3281edee68e10643c7e8ecb59e2b43 100644 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/basic_guester.jpg and b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/basic_guester.jpg differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/custom_dialog_sm.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/custom_dialog_sm.png index 1cf3cff5e48e373d057bf4dca8f48cf2689d0dcc..331059acfc254ace6883b3624280252134ef1b83 100644 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/custom_dialog_sm.png and b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/custom_dialog_sm.png differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001224053150.jpg b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001224053150.jpg deleted file mode 100644 index 64dc2aee0d2c3c6631f861734fce1c2ea97737a9..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001224053150.jpg and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001224173138.jpg b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001224173138.jpg deleted file mode 100644 index f2c88c18b5191a67acb9ae4c375afbba008585c9..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001224173138.jpg and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001224293580.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001224293580.png deleted file mode 100644 index 456e9a393d069a2ac76545934c706768e08d3add..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001224293580.png and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001224333656.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001224333656.png deleted file mode 100644 index 391334048db2a5f8458f8aad1826b3fd50c62e37..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001224333656.png and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001224333864.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001224333864.png deleted file mode 100644 index aeb5af2c3bfea0ba3f10be4eba47e5b9d36ea815..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001224333864.png and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001236472600.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001236472600.png deleted file mode 100644 index b4efa612755c454ff33042987af4b91bfd1e1d7d..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001236472600.png and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001245277712.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001245277712.png deleted file mode 100644 index 0fbfa9f68ecfbde50397bf52e3ef1a5e17fd7fa0..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001245277712.png and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001245437476.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001245437476.png deleted file mode 100644 index 92eb37a883701ae84a8da0bf7d7f0ecac2478c6e..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001245437476.png and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001245596752.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001245596752.png deleted file mode 100644 index 43702f3339678462904335adc7b57eecc8a5c8ec..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001245596752.png and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001268129090.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001268129090.png deleted file mode 100644 index c7b4c0caf6a3c3e912af36215c2daf97d4c3a689..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001268129090.png and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001268288974.gif b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001268288974.gif deleted file mode 100644 index 490d85b1ebf172261f2dc4f9611431a46cb1edb2..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001268288974.gif and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001268334113.jpg b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001268334113.jpg deleted file mode 100644 index 1d0b0ee8d91f47f840be81d80798b32bc709407f..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001268334113.jpg and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001268533753.jpg b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001268533753.jpg deleted file mode 100644 index 0af1f5691391ae1b5db4950e491c38ff64fcf738..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001268533753.jpg and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001268608890.gif b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001268608890.gif deleted file mode 100644 index 25e5d6d2c6c4585780f5582dbcf1bb0f1c22b4b0..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001268608890.gif and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001268653317.jpg b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001268653317.jpg deleted file mode 100644 index c47351b3533e10b0956e55045df63694dc255c60..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001268653317.jpg and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001268653953.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001268653953.png deleted file mode 100644 index e0a3c29e84781332429008d9ac90c237c39eb611..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001268653953.png and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001280232265.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001280232265.png deleted file mode 100644 index b4efa612755c454ff33042987af4b91bfd1e1d7d..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001280232265.png and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001280472681.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001280472681.png deleted file mode 100644 index 41ec455049452d6955ca1acbb95ce97eedf5bf7b..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001280472681.png and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001280472701.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001280472701.png deleted file mode 100644 index a27b306ab5457819b1a57599e2a7a95d81faf5c3..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001280472701.png and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001291557665.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001291557665.png deleted file mode 100644 index aa538be715eff5bd5981d295777f652e2e63e081..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001291557665.png and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001291675753.gif b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001291675753.gif deleted file mode 100644 index d529c69c2ce4d9a5ca1d0db48ffb14ef3e2df8b5..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001291675753.gif and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001291677093.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001291677093.png deleted file mode 100644 index 19d0d553aa67ebfc29d912d408be690da29f5c16..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001291677093.png and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001291916533.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001291916533.png deleted file mode 100644 index 90e33ca0fc7af77a6e70b133cfc3305014256004..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001291916533.png and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001317089061.gif b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001317089061.gif deleted file mode 100644 index 59255a0deba2b34c79bacfa0a62b5495fc7c85c5..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001317089061.gif and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001317208945.gif b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001317208945.gif deleted file mode 100644 index 3044f716955b93f859d3b4a8fb0b38a6672508a1..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001317208945.gif and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001317328893.gif b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001317328893.gif deleted file mode 100644 index ea2726ae830aa8e98f65029f394d50e0b5c77e50..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001317328893.gif and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001317488873.gif b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001317488873.gif deleted file mode 100644 index 93287e0284e3e6a8037584c5bb42b07252f0b925..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001317488873.gif and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001350234552.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001350234552.png deleted file mode 100644 index 56a37a8a5b73c7c99b49679b1115bcd49bdb3f58..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001350234552.png and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001400554657.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001400554657.png deleted file mode 100644 index 3935521c46b58203780dee1b40c48c4616ca98f2..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001400554657.png and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001400674189.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001400674189.png deleted file mode 100644 index 056005af6c69515a30885ac9a1cddc9c6bfbc3f7..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001400674189.png and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001400874297.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001400874297.png deleted file mode 100644 index dd0f81fc8098faeebce7f31ed90b3e31a47f5aae..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001400874297.png and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-1-1.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-1-1.png" deleted file mode 100644 index 51da8c08c80dcca391fe78c1dbe82297a9b95fbb..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-1-1.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-2-2.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-2-2.png" deleted file mode 100644 index 19275436de6099ee3093464e0fee633dfceb9889..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-2-2.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-2-3.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-2-3.png" deleted file mode 100644 index 16f9b507b3496e0e76ecbb335367cb46c62ededd..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-2-3.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-2-5.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-2-5.png" deleted file mode 100644 index db8ccf59a454ddb288a5648ac70b93f9a4c4758a..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-2-5.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-2-6.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-2-6.png" deleted file mode 100644 index 03b9523816970b463f2cf90a4c2935502eb54076..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-2-6.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\270\203\345\261\2001.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\270\203\345\261\2001.png" deleted file mode 100644 index 18b188b5f346fc7e23893de476a7c815dd0848ec..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\270\203\345\261\2001.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\270\203\345\261\2002.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\270\203\345\261\2002.png" deleted file mode 100644 index c0da558257c63f2aebd94b36e91fb8f84f6dc406..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\270\203\345\261\2002.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\270\203\345\261\2003.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\270\203\345\261\2003.png" deleted file mode 100644 index 4102ee5e69b9629a839c8b5eaf7739b1d47a9911..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\270\203\345\261\2003.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\345\205\263\344\272\216.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\345\205\263\344\272\216.png" deleted file mode 100644 index f283a02af83a43d1231acc661b7f2385ba3e93df..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\345\205\263\344\272\216.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\345\210\227\350\241\250\350\247\206\350\247\211\345\233\276.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\345\210\227\350\241\250\350\247\206\350\247\211\345\233\276.png" deleted file mode 100644 index bec6e793e08f1660dc19b0e08e0167aae8ea53ea..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\345\210\227\350\241\250\350\247\206\350\247\211\345\233\276.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\345\220\257\345\212\250\351\241\265.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\345\220\257\345\212\250\351\241\265.png" deleted file mode 100644 index 7f9bac84a38ea1883d725d8bc72cc7ef80f1503f..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\345\220\257\345\212\250\351\241\265.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\346\210\221\347\232\204\351\241\265\351\235\242.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\346\210\221\347\232\204\351\241\265\351\235\242.png" deleted file mode 100644 index 4a23c72f05ba6a52cf2e1cc7ba8c200a14ec3eb7..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\346\210\221\347\232\204\351\241\265\351\235\242.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\347\251\272\351\241\265\351\235\242.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\347\251\272\351\241\265\351\235\242.png" deleted file mode 100644 index e7832259c74132d40a0d0b1f8662ddd2bd94736a..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\347\251\272\351\241\265\351\235\242.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\347\275\221\346\240\274\350\247\206\345\233\276.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\347\275\221\346\240\274\350\247\206\345\233\276.png" deleted file mode 100644 index f936d1c5869dbb3ebcba9ffcc3a701f3cc3b07e3..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\347\275\221\346\240\274\350\247\206\345\233\276.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\350\247\206\351\242\221\346\222\255\346\224\276.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\350\247\206\351\242\221\346\222\255\346\224\276.png" deleted file mode 100644 index 40ddaebd21d31f71a2c081ec8d5bbd50b4125a5f..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\350\247\206\351\242\221\346\222\255\346\224\276.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\350\247\206\351\242\221\350\257\246\346\203\205.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\350\247\206\351\242\221\350\257\246\346\203\205.png" deleted file mode 100644 index e0b7b4a1195908d99f18c19ba8829fbf1aa15707..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\350\247\206\351\242\221\350\257\246\346\203\205.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\350\256\276\347\275\256.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\350\256\276\347\275\256.png" deleted file mode 100644 index 6d32ffb6f0042f042cf33553f865168b5f75f4cf..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\270\200\345\244\232-\345\272\224\347\224\250\346\236\266\346\236\204-\350\256\276\347\275\256.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\275\215\345\233\27621.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\275\215\345\233\27621.png" deleted file mode 100644 index 1bbb297c46f4edee9c5f1c3a7e12f94e57d8f8aa..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\344\275\215\345\233\27621.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\210\240\346\240\274.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\210\240\346\240\274.png" deleted file mode 100644 index 44bfdddd65ed6e3d183df3a4fcc1d35bc42ece42..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\210\240\346\240\274.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\235\207\345\210\206\350\203\275\345\212\233.gif" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\235\207\345\210\206\350\203\275\345\212\233.gif" deleted file mode 100644 index dd5d14e1f4ddee5dc04dd1de4ff13d2396d9b8c7..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\235\207\345\210\206\350\203\275\345\212\233.gif" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\255\227\344\275\223copy2.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\255\227\344\275\223copy2.png" deleted file mode 100644 index f9b14acc9d2fe68f16d897d0bddf5b3c29075188..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\255\227\344\275\223copy2.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\270\203\345\261\200\345\237\272\347\241\200\346\241\210\344\276\213-\345\261\202\347\272\247\345\257\274\350\210\252-\350\256\276\347\275\256.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\270\203\345\261\200\345\237\272\347\241\200\346\241\210\344\276\213-\345\261\202\347\272\247\345\257\274\350\210\252-\350\256\276\347\275\256.png" deleted file mode 100644 index 0e979c39f9da92afb881fc56e49c08f7f4125317..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\270\203\345\261\200\345\237\272\347\241\200\346\241\210\344\276\213-\345\261\202\347\272\247\345\257\274\350\210\252-\350\256\276\347\275\256.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\272\224\347\224\250\346\236\266\346\236\204-\345\270\270\347\224\250\351\241\265\351\235\242\347\273\223\346\236\204-\345\236\202\347\261\273\351\241\265\351\235\242\347\273\223\346\236\204-\346\255\214\345\215\225\350\257\246\346\203\205\344\275\216\344\277\235\347\234\237.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\272\224\347\224\250\346\236\266\346\236\204-\345\270\270\347\224\250\351\241\265\351\235\242\347\273\223\346\236\204-\345\236\202\347\261\273\351\241\265\351\235\242\347\273\223\346\236\204-\346\255\214\345\215\225\350\257\246\346\203\205\344\275\216\344\277\235\347\234\237.png" deleted file mode 100644 index 5282c8cd042e4856e767c862e4970908e442e930..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\272\224\347\224\250\346\236\266\346\236\204-\345\270\270\347\224\250\351\241\265\351\235\242\347\273\223\346\236\204-\345\236\202\347\261\273\351\241\265\351\235\242\347\273\223\346\236\204-\346\255\214\345\215\225\350\257\246\346\203\205\344\275\216\344\277\235\347\234\237.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\272\224\347\224\250\346\236\266\346\236\204-\345\270\270\347\224\250\351\241\265\351\235\242\347\273\223\346\236\204-\345\236\202\347\261\273\351\241\265\351\235\242\347\273\223\346\236\204-\351\237\263\344\271\220\346\222\255\346\224\276\344\275\216\344\277\235\347\234\237.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\272\224\347\224\250\346\236\266\346\236\204-\345\270\270\347\224\250\351\241\265\351\235\242\347\273\223\346\236\204-\345\236\202\347\261\273\351\241\265\351\235\242\347\273\223\346\236\204-\351\237\263\344\271\220\346\222\255\346\224\276\344\275\216\344\277\235\347\234\237.png" deleted file mode 100644 index b921fc54e358962b483ee9980d96266bb7d21796..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\272\224\347\224\250\346\236\266\346\236\204-\345\270\270\347\224\250\351\241\265\351\235\242\347\273\223\346\236\204-\345\236\202\347\261\273\351\241\265\351\235\242\347\273\223\346\236\204-\351\237\263\344\271\220\346\222\255\346\224\276\344\275\216\344\277\235\347\234\237.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\272\224\347\224\250\346\236\266\346\236\204-\345\270\270\347\224\250\351\241\265\351\235\242\347\273\223\346\236\204-\351\200\232\347\224\250\351\241\265\351\235\242\347\273\223\346\236\204-\345\244\232\351\200\211\351\241\265\351\235\242\344\275\216\344\277\235\347\234\237.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\272\224\347\224\250\346\236\266\346\236\204-\345\270\270\347\224\250\351\241\265\351\235\242\347\273\223\346\236\204-\351\200\232\347\224\250\351\241\265\351\235\242\347\273\223\346\236\204-\345\244\232\351\200\211\351\241\265\351\235\242\344\275\216\344\277\235\347\234\237.png" deleted file mode 100644 index 05c9ba829b851e507f805b65e2a46ed4f87fb8eb..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\272\224\347\224\250\346\236\266\346\236\204-\345\270\270\347\224\250\351\241\265\351\235\242\347\273\223\346\236\204-\351\200\232\347\224\250\351\241\265\351\235\242\347\273\223\346\236\204-\345\244\232\351\200\211\351\241\265\351\235\242\344\275\216\344\277\235\347\234\237.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\272\224\347\224\250\346\236\266\346\236\204-\345\270\270\347\224\250\351\241\265\351\235\242\347\273\223\346\236\204-\351\200\232\347\224\250\351\241\265\351\235\242\347\273\223\346\236\204-\350\257\246\346\203\205\351\241\265\351\235\242\344\275\216\344\277\235\347\234\237.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\272\224\347\224\250\346\236\266\346\236\204-\345\270\270\347\224\250\351\241\265\351\235\242\347\273\223\346\236\204-\351\200\232\347\224\250\351\241\265\351\235\242\347\273\223\346\236\204-\350\257\246\346\203\205\351\241\265\351\235\242\344\275\216\344\277\235\347\234\237.png" deleted file mode 100644 index fac64e55253fae7c05be9d33e0fc89317285138d..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\272\224\347\224\250\346\236\266\346\236\204-\345\270\270\347\224\250\351\241\265\351\235\242\347\273\223\346\236\204-\351\200\232\347\224\250\351\241\265\351\235\242\347\273\223\346\236\204-\350\257\246\346\203\205\351\241\265\351\235\242\344\275\216\344\277\235\347\234\237.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\273\266\351\225\277\350\203\275\345\212\233.gif" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\273\266\351\225\277\350\203\275\345\212\233.gif" deleted file mode 100644 index 17c971e4dc223c3960215db3f1fa0f98a864d29d..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\345\273\266\351\225\277\350\203\275\345\212\233.gif" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\346\212\230\350\241\214\346\241\210\344\276\213\345\210\206\351\225\234.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\346\212\230\350\241\214\346\241\210\344\276\213\345\210\206\351\225\234.png" deleted file mode 100644 index 915391a917cf5bfb1f49ac28eb7dac137c8ef6bb..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\346\212\230\350\241\214\346\241\210\344\276\213\345\210\206\351\225\234.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\346\213\211\344\274\270\346\263\250\346\204\217\345\234\272\346\231\257.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\346\213\211\344\274\270\346\263\250\346\204\217\345\234\272\346\231\257.png" deleted file mode 100644 index cf2de1d9bc8446cee411fa6348459c6775bcfb54..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\346\213\211\344\274\270\346\263\250\346\204\217\345\234\272\346\231\257.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\346\213\211\344\274\270\350\203\275\345\212\233.gif" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\346\213\211\344\274\270\350\203\275\345\212\233.gif" deleted file mode 100644 index 50ff0346cb6bc0f8cabdfcb1e996d52dc17005ff..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\346\213\211\344\274\270\350\203\275\345\212\233.gif" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\346\214\252\347\247\273\345\270\203\345\261\200.gif" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\346\214\252\347\247\273\345\270\203\345\261\200.gif" deleted file mode 100644 index b771ea9534e6ee309306433d727d3bbf60d8413b..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\346\214\252\347\247\273\345\270\203\345\261\200.gif" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\346\240\205\346\240\274\347\263\273\347\273\237\344\276\213.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\346\240\205\346\240\274\347\263\273\347\273\237\344\276\213.png" deleted file mode 100644 index 00cc68c8f4be86be6a19c3371cdd63f3f26e7b8f..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\346\240\205\346\240\274\347\263\273\347\273\237\344\276\213.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\346\246\202\350\277\260-\347\225\214\351\235\242\345\270\203\345\261\200-\346\255\214\345\215\225\350\257\246\346\203\205\351\253\230\344\277\235\347\234\237.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\346\246\202\350\277\260-\347\225\214\351\235\242\345\270\203\345\261\200-\346\255\214\345\215\225\350\257\246\346\203\205\351\253\230\344\277\235\347\234\237.png" deleted file mode 100644 index 0c1466fbf81b839efa4579ab693345dffeeb89a4..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\346\246\202\350\277\260-\347\225\214\351\235\242\345\270\203\345\261\200-\346\255\214\345\215\225\350\257\246\346\203\205\351\253\230\344\277\235\347\234\237.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\346\267\267\345\220\210\345\257\274\350\210\252.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\346\267\267\345\220\210\345\257\274\350\210\252.png" deleted file mode 100644 index 629203b475294a6894e453767799ead1e14edcba..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\346\267\267\345\220\210\345\257\274\350\210\252.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\347\211\271\346\256\212\351\241\265\351\235\242\347\273\223\346\236\204.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\347\211\271\346\256\212\351\241\265\351\235\242\347\273\223\346\236\204.png" deleted file mode 100644 index 81622e36f148233010cdbd0a905a388593451416..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\347\211\271\346\256\212\351\241\265\351\235\242\347\273\223\346\236\204.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\347\224\273\346\235\277copy.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\347\224\273\346\235\277copy.png" deleted file mode 100644 index 71ff9d4c145e248b5e17a06e931c9678c286de50..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\347\224\273\346\235\277copy.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\347\274\251\346\224\276\346\241\210\344\276\213.gif" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\347\274\251\346\224\276\346\241\210\344\276\213.gif" deleted file mode 100644 index 352a442beaade47d893eabc95679e98aaff95c54..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\347\274\251\346\224\276\346\241\210\344\276\213.gif" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\347\274\251\350\277\233\345\270\203\345\261\200.gif" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\347\274\251\350\277\233\345\270\203\345\261\200.gif" deleted file mode 100644 index da5c50be4aa9f1bc9b9858c1476bc821f42cbe19..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\347\274\251\350\277\233\345\270\203\345\261\200.gif" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\351\207\215\345\244\215\345\270\203\345\261\200.gif" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\351\207\215\345\244\215\345\270\203\345\261\200.gif" deleted file mode 100644 index 1e2414aabfd95aefd953f2a14a0f3f0032ec3537..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\351\207\215\345\244\215\345\270\203\345\261\200.gif" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\351\232\220\350\227\217\350\203\275\345\212\233.gif" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\351\232\220\350\227\217\350\203\275\345\212\233.gif" deleted file mode 100644 index 0e8cb21243a7610d8076d08ae0d8d8dbaf1dbbba..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\351\232\220\350\227\217\350\203\275\345\212\233.gif" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\351\241\265\351\235\242\345\270\203\345\261\200-\345\270\203\345\261\200\345\237\272\347\241\200\346\241\210\344\276\213-\346\255\214\345\215\225\350\257\246\346\203\205\351\241\265\351\235\242\345\270\203\345\261\200\350\203\275\345\212\2331280-1920vp.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\351\241\265\351\235\242\345\270\203\345\261\200-\345\270\203\345\261\200\345\237\272\347\241\200\346\241\210\344\276\213-\346\255\214\345\215\225\350\257\246\346\203\205\351\241\265\351\235\242\345\270\203\345\261\200\350\203\275\345\212\2331280-1920vp.png" deleted file mode 100644 index 5fdd581c45463ea4aa53236358bd02fec0f1d198..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\351\241\265\351\235\242\345\270\203\345\261\200-\345\270\203\345\261\200\345\237\272\347\241\200\346\241\210\344\276\213-\346\255\214\345\215\225\350\257\246\346\203\205\351\241\265\351\235\242\345\270\203\345\261\200\350\203\275\345\212\2331280-1920vp.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\351\241\265\351\235\242\345\270\203\345\261\200-\345\270\203\345\261\200\345\237\272\347\241\200\346\241\210\344\276\213-\346\255\214\345\215\225\350\257\246\346\203\205\351\241\265\351\235\242\345\270\203\345\261\200\350\203\275\345\212\233360-800vp.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\351\241\265\351\235\242\345\270\203\345\261\200-\345\270\203\345\261\200\345\237\272\347\241\200\346\241\210\344\276\213-\346\255\214\345\215\225\350\257\246\346\203\205\351\241\265\351\235\242\345\270\203\345\261\200\350\203\275\345\212\233360-800vp.png" deleted file mode 100644 index 2d1e85d22361ca8806c40794bd5589fb5e703c12..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\351\241\265\351\235\242\345\270\203\345\261\200-\345\270\203\345\261\200\345\237\272\347\241\200\346\241\210\344\276\213-\346\255\214\345\215\225\350\257\246\346\203\205\351\241\265\351\235\242\345\270\203\345\261\200\350\203\275\345\212\233360-800vp.png" and /dev/null differ diff --git "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\351\241\265\351\235\242\345\270\203\345\261\200-\345\270\203\345\261\200\345\237\272\347\241\200\346\241\210\344\276\213-\346\255\214\345\215\225\350\257\246\346\203\205\351\241\265\351\235\242\345\270\203\345\261\200\350\203\275\345\212\233800-1280vp.png" "b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\351\241\265\351\235\242\345\270\203\345\261\200-\345\270\203\345\261\200\345\237\272\347\241\200\346\241\210\344\276\213-\346\255\214\345\215\225\350\257\246\346\203\205\351\241\265\351\235\242\345\270\203\345\261\200\350\203\275\345\212\233800-1280vp.png" deleted file mode 100644 index c8a3650fbadbde3d091c3cc3dcd8f9c47ecaf79d..0000000000000000000000000000000000000000 Binary files "a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/\351\241\265\351\235\242\345\270\203\345\261\200-\345\270\203\345\261\200\345\237\272\347\241\200\346\241\210\344\276\213-\346\255\214\345\215\225\350\257\246\346\203\205\351\241\265\351\235\242\345\270\203\345\261\200\350\203\275\345\212\233800-1280vp.png" and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/foreword.md b/zh-cn/application-dev/key-features/multi-device-app-dev/foreword.md index 8f2e9a395ee62ac1c95abd5c7783ba24f6a82526..36ec9c56bdc51e84efc51d85c584d7a107fded0b 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/foreword.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/foreword.md @@ -27,13 +27,9 @@ - 第3章[从一个例子开始](start-with-a-example.md)通过示例介绍“一多”应用的开发过程,让读者对“一多”有个直观认识。 -- 第4章[应用UX设计](design-principles.md)介绍了应用UX设计理念。主要阐述了应用设计之初UX设计的原则和要点。该章节主要面向应用的UX设计师。 +- 第4章[应用UX设计](../../../design/ux-design/app-ux-design.md)介绍了应用UX设计理念。主要阐述了应用设计之初UX设计的原则和要点。该章节主要面向应用的UX设计师。 UX设计原则应该考虑多设备的“差异性” 、“一致性”、“灵活性”和“兼容性”。 - UX设计要点则从6个方面阐述如何进行多设备应用设计,分别是“自适应应用架构”、“响应式界面布局”、“交互归一”、“视觉参数化”、“多态控件”和“针对性优化”。 - - 最后,给出设计自检表,用于检查应用UX设计是否合理 。 - - 第5章[工程管理](ide-using.md)介绍了从工程角度如何开始开发应用,让读者可以直接上手创建多设备应用的工程,是后面学习“一多”能力的上手基础。 - 第6章[页面开发的一多能力介绍](page-development-intro.md)和第7章[功能开发的一多能力介绍](development-intro.md)介绍了OpenHarmony提供的“一多”能力,其中每个能力都提供了代码示例和UX效果,让读者可以快速学习“一多”能力。 diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/interaction-basics.md b/zh-cn/application-dev/key-features/multi-device-app-dev/interaction-basics.md deleted file mode 100644 index e5bb158ab07baeb0044cff3d0fe32eea331f9026..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/interaction-basics.md +++ /dev/null @@ -1,23 +0,0 @@ -# 交互基础 - - -在全场景的数字体验中,越来越多类型的智能终端设备分布在用户的日常生活中,可交互的用户界面广泛存在于默认设备、平板、智能穿戴设备、智慧屏、车机、虚拟现实(VR)和增强现实(AR)等设备上。应用可能在多种设备上运行或在单一设备上被用户通过多种输入方式操控,也可能在多种距离上被用户操控。这需要其用户界面能够识别和支持不同的交互场景,以便用户以习惯的、舒适的方法与其进行交互。 - - -![zh-cn_image_0000001224293580](figures/zh-cn_image_0000001224293580.png) - - -## 输入方式 - -典型的输入方式包括但不限于触屏上手指/手写笔等直接交互、鼠标/触摸板/键盘/表冠/遥控器/车机摇杆/旋钮/手柄/隔空手势等间接交互、以及语音交互。 - -设计和开发应用时,**设计师和开发者应考虑到应用具有使用多种输入方式的可能性**,并实现相应的功能,保证在当前输入方式下应用能够以正确的、符合用户习惯的方式进行响应。 - - -## 交互距离 - -典型的设备交互距离包括但不限于15cm(智能穿戴设备)、30cm(默认设备)、60cm(桌面设备)、260cm(大屏),具体距离会在用户使用过程中产生一定范围的变化。 - -设计和开发应用时,设计师和开发者应考虑到多种距离下使用的可能性,保证界面元素的大小、展示信息的密度符合用户的预期。 - -![位图 21](figures/位图21.png) diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/interaction-event-normalization.md b/zh-cn/application-dev/key-features/multi-device-app-dev/interaction-event-normalization.md index d6dfbe141b2eda726e828874f167adfcab56cb47..d60d78f86cf6d1864a30faf7f1b6d3e6b6e3fa30 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/interaction-event-normalization.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/interaction-event-normalization.md @@ -12,15 +12,18 @@ 基础输入对应的开发接口,以及当前支持情况如下表所示。 - | 输入 | 开发接口 | 触控屏 | 鼠标 | 触控板 | + | 输入 | 开发接口 | 触控屏 | 触控板 | 鼠标 | -------- | -------- | -------- | -------- | -------- | +| 悬浮 | [onHover](../../reference/arkui-ts/ts-universal-attributes-hover-effect.md) | NA | √ | √ | | 点击 | [onClick](../../reference/arkui-ts/ts-universal-events-click.md) | √ | √ | √ | -| 长按 | [LongPressGesture](../../reference/arkui-ts/ts-basic-gestures-longpressgesture.md) | √ | √ | × | | 双击 | [TapGesture](../../reference/arkui-ts/ts-basic-gestures-tapgesture.md) | √ | √ | √ | +| 长按 | [LongPressGesture](../../reference/arkui-ts/ts-basic-gestures-longpressgesture.md) | √ | × | √ | +| 上下文菜单 | [ContentMenu](../../reference/arkui-ts/ts-universal-attributes-menu.md) | √ | √ | √ | +| 拖拽 | [Drag](../../reference/arkui-ts/ts-universal-attributes-drag-drop.md) | √ | √ | √ | | 轻扫 | [SwipeGesture](../../reference/arkui-ts/ts-basic-gestures-swipegesture.md) | √ | √ | √ | | 滚动及平移 | [PanGesture](../../reference/arkui-ts/ts-basic-gestures-pangesture.md) | √ | √ | √ | | 缩放 | [PinchGesture](../../reference/arkui-ts/ts-basic-gestures-pinchgesture.md) | √ | √ | √ | -| 旋转 | [RotationGesture](../../reference/arkui-ts/ts-basic-gestures-rotationgesture.md) | √ | NA | √ | +| 旋转 | [RotationGesture](../../reference/arkui-ts/ts-basic-gestures-rotationgesture.md) | √ | √ | NA | > **说明:** > - 点击事件(onClick)其实是点击手势(TapGesture)的一个特殊场景(单指单次点击)。该场景使用的非常广泛,为了方便开发者使用及符合传统开发习惯,所以专门提供了开发接口。 @@ -48,4 +51,4 @@ | onDragEnter | 绑定B组件,触控屏手指、鼠标移动进入B组件瞬间触发 | | onDragMove | 绑定B组件,触控屏手指、鼠标在B组件内移动触发 | | onDragLeave | 绑定B组件,触控屏手指、鼠标移动退出B组件瞬间触发 | -| onDrop | 绑定B组件,在B组件内,触控屏手指抬起、鼠标左键松开时触发 | +| onDrop | 绑定B组件,在B组件内,触控屏手指抬起、鼠标左键松开时触发 | \ No newline at end of file diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/interface-layout-design-intro.md b/zh-cn/application-dev/key-features/multi-device-app-dev/interface-layout-design-intro.md deleted file mode 100644 index 3748dc26332ca137cf7516e9b141be075606efc5..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/interface-layout-design-intro.md +++ /dev/null @@ -1,7 +0,0 @@ -# 概述 - - -布局不是静态固定的,当显示环境发生变化时,如横竖屏切换、调节字体大小、应用分屏,要及时调整内容的布局方式以适应变化。本章提供了布局基础的概念和介绍。详见[布局基础](design-grid.md)。 - - -了解布局的基础概念后,通过调用栅格系统、自适应布局和响应式布局能力就可以让内容更好地适配显示环境的变化。综合运用布局基础能力,可实现常用页面结构的多设备适配。详见[布局基础运用案例](design-layout-cases.md)。 diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/navigation-design.md b/zh-cn/application-dev/key-features/multi-device-app-dev/navigation-design.md deleted file mode 100644 index c3a989c6fdf1fb863c08659b84bac33181d98ba8..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/navigation-design.md +++ /dev/null @@ -1,70 +0,0 @@ -# 应用导航结构设计要求 - - -应用中的导航用于引导用户在应用的各个页面进行浏览。好的导航让用户知道身处何处,去往何方,以及来自哪里。 - - -## 导航的原则 - -导航需要遵循以下原则: - -- **一致:** 导航操作的结果应该与用户的期望保持一致。相同或类似的场景使用用户熟悉的界面布局和控件,在多设备上确保一致的应用架构和导航行为,让用户无论在什么页面,都知道如何导航。例如二级界面使用左上角的返回按钮来返回界面的上一个层级。 - -- **清晰:** 导航应该提供清晰的路径。用户使用的时候,逻辑关系简单且容易理解,能够知道当前处在界面的什么位置,操作后将会跳转到什么位置,不会迷失方向。例如使用底部页签,让用户在平级页面之间进行切换。 - -导航要避免以下设计: - -- **层级过深:** 导航层级建议在三层以内。对于太深的层次,会带来操作效率的问题。如果确实需要深层级设计,建议使用面包屑设计或增加一键回到首页的功能。 - -- **导航复杂:** 在侧边导航中,使用底部页签,会让操作变得复杂,建议仅使用侧边导航。 - - -## 导航的分类 - -常用的应用导航有:平级导航、层级导航和混合导航。 - -**平级导航** - -平级导航结构中,页面均处在同一层级。 - -使用场景:用于展示同等地位或同等层级的界面。 - -![zh-cn_image_0000001224053150](figures/zh-cn_image_0000001224053150.jpg) - -例如:以Tab方式组成的页面。图中照片、相册、发现为一级界面,从视频相册进入二级内容界面。 - -![一多-2-2](figures/一多-2-2.png) - -多设备设计:可转化导航类控件到符合设备体验的位置上。默认设备上使用Tab导航,PAD等大屏设备使用侧边Tab导航,智慧屏使用顶部Tab导航。 - -![一多-2-3](figures/一多-2-3.png) - -**层级导航** - -层级导航结构由父页面和子页面组成。父页面可以有一个或多个子页面。每个子页面都有一个父页面。 - -层级导航适用于多层级的复杂结构。层级结构深的内容,用户访问的路径变长,效率降低,可以通过适当的层级穿透设计(例如:控制中心中的蓝牙开关,解决了进“设置-蓝牙”界面设置操作路径过长的问题)解决此问题。 - -使用场景:页面存在上下级关系的应用。 - -![zh-cn_image_0000001224173138](figures/zh-cn_image_0000001224173138.jpg) - -例如:通过从内容进入后经返回键返回之前的页面。 - -![一多-2-5](figures/一多-2-5.png) - -多设备设计:可以考虑将上下层级的界面在同一界面展示。默认设备和智慧屏上使用上下层级关系。平板等大屏设备上使用分栏的方式展示内容。 - -![一多-2-6](figures/一多-2-6.png) - -**混合导航** - -在实际应用设计中,仅使用平级或层级导航可能无法应对更复杂的业务结构。此时需区分不同页面的导航关系,对同等地位或同等层级的页面使用平级导航结构,对具有复杂关系的页面使用层级导航结构。 - -使用场景:应用由几个同等级的模块组成,每个模块又有上下层级关系页面。 - -![zh-cn_image_0000001268653317](figures/zh-cn_image_0000001268653317.jpg) - -多设备设计:可以根据平级导航、层级导航自身的设计规则综合运用,一般平级导航优先级比层级高。 - -![混合导航](figures/混合导航.png) diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/page-design.md b/zh-cn/application-dev/key-features/multi-device-app-dev/page-design.md deleted file mode 100644 index ef9323ba4bc661c4b1d0c43809eeeeb569d73eb8..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/page-design.md +++ /dev/null @@ -1,136 +0,0 @@ -# 应用页面结构设计 - - -## 通用页面结构 - -应用程序由多个页面组成。我们将常见的页面进行了梳理,总结了以下常用的页面结构。 - -**启动页面** - -针对内容型应用,应用首页内容的获取需要花费一定的时间,此时可以使用启动页缓解页面加载内容的等待感。启动页可以展示应用的品牌形象或者广告,避免让用户等待过长时间。没有网络加载内容的应用,不需要使用启动页。 - -![一多-应用架构-启动页](figures/一多-应用架构-启动页.png) - -用户总是希望第一时间看到应用内容,因此在页面加载完成后,需要及时呈现内容。 - -从后台加载应用时,不应该显示启动页。当应用被切换到后台后,再从后台加载回来时,不应该再次显示启动页。应用需要保留应用的状态,以便从后台恢复,方便用户继续浏览。 - -**列表内容页面** - -列表内容页面通常用于文字和数据的展示,利于提升使用效率。 - -![一多-应用架构-列表视觉图](figures/一多-应用架构-列表视觉图.png) - -列表应该按照一定的逻辑排序,便于用户浏览和操作。例如:按字母顺序排序、按时间排序。 - -列表应该是同类项的集合,应该对外呈现一致的布局样式。常见的是单行列表、双行列表和三行列表。 - -列表显示的内容要主次分明,用户一眼就能关注到重要的信息和操作。 - -**网格内容页面** - -网格内容页面通常用于图片和视频的展示,利于沉浸浏览内容。 - -![一多-应用架构-网格视图](figures/一多-应用架构-网格视图.png) - -网格视图显示同等重要的项目,具有统一的布局。 - -网格视图以图像为主组织内容。例如图库中用网格视图展示图片。 - -网格视图可以辅以文字和操作。例如应用市场中使用网格展示应用程序图标、简单描述和下载按钮。 - -网格视图应该考虑响应式布局。在横竖屏切换时,网格视图应该能够调整网格的数量以适应页面的宽度变化。 - -**多选页面** - -多选页面是对页面内的数据多项选择,然后进行批量处理。常见的是针对列表的多项选择或宫格的多项选择。 - -![应用架构-常用页面结构-通用页面结构-多选页面低保真](figures/应用架构-常用页面结构-通用页面结构-多选页面低保真.png) - -**详情页面** - -详情页用于展示应用的详细描述和操作。 - -![应用架构-常用页面结构-通用页面结构-详情页面低保真](figures/应用架构-常用页面结构-通用页面结构-详情页面低保真.png) - -**空页面** - -在页面内没有数据的时候,使用空页面。 - -![一多-应用架构-空页面](figures/一多-应用架构-空页面.png) - -**设置页面** - -设置页面通常是一个模块所有设置项的聚合。 - -![一多-应用架构-设置](figures/一多-应用架构-设置.png) - -**我的页面** - -针对内容型应用,可以提供我的页面,用于承载用户的信息和资产内容。 - -![一多-应用架构-我的页面](figures/一多-应用架构-我的页面.png) - -**关于页面** - -关于页面用于呈现应用的基本情况,包括联系方式,法律条款等内容。 - -![一多-应用架构-关于](figures/一多-应用架构-关于.png) - - -## 垂类页面结构 - -垂类是指垂直领域,为特定的人群提供特定的服务,属于应用的细分类别,例如音乐类、视频类、直播类等。垂类页面结构是在特定领域长期使用的过程中,形成的广泛被用户接受和理解的页面结构。 - -例如: - -音乐类应用都有音乐歌单,音乐专辑,音乐播放界面。 - -视频类应用都有视频详情和视频播放界面。 - -直播类应用,都有瀑布流推荐和直播界面。 - -... - -常见的垂类页面结构有: - -- 音乐播放页面 - -- 专辑详情页面 - -- 视频详情页面 - -- 视频播放页面 - -**音乐播放界面** - -音乐类应用中的播放器界面,该界面通常有音乐操控(播放,暂停,上一首,下一首)、歌词显示等功能。 - -![应用架构-常用页面结构-垂类页面结构-音乐播放低保真](figures/应用架构-常用页面结构-垂类页面结构-音乐播放低保真.png) - -**专辑详情页** - -音乐类应用中的音乐专辑详情界面,该界面通常有专辑介绍、专辑包含的歌曲列表等功能。 - -![应用架构-常用页面结构-垂类页面结构-歌单详情低保真](figures/应用架构-常用页面结构-垂类页面结构-歌单详情低保真.png) - -**视频详情页面** - -视频类应用的视频详情界面,该界面通常有视频播放器、视频剧集显示、视频简介等功能。 - -![一多-应用架构-视频详情](figures/一多-应用架构-视频详情.png) - -**视频播放界面** - -视频类应用的视频播放界面,该界面通常有视频画面预览、播放控制等功能。 - -![一多-应用架构-视频播放](figures/一多-应用架构-视频播放.png) - - -## 特殊页面结构 - -部分应用界面在差异较大的设备间切换,无法使用自适应和响应式布局设计方法进行适配,从用户预期上也需要调整应用架构时,将需要做特殊适配。 - -例如,同时具有底部Tab和子页签的页面,在大屏上应考虑将底部入口置于顶部工具栏或与子页签融合。 - -![特殊页面结构](figures/特殊页面结构.png) diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/resource-usage.md b/zh-cn/application-dev/key-features/multi-device-app-dev/resource-usage.md index f4e1ce148f9154a3c678f3fca46ae44a94c07dc4..69906fa539f01c0f6ba92cbe9081a1b04ba86baa 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/resource-usage.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/resource-usage.md @@ -114,11 +114,11 @@ struct Index { ## 系统资源 -除了自定义资源,开发者也可以使用系统中预定义的资源(即[分层参数](visual-basics.md),同一资源ID在设备类型、深浅色等不同配置下有不同的取值)。 +除了自定义资源,开发者也可以使用系统中预定义的资源(即[分层参数](../../../design/ux-design/visual-basis.md),同一资源ID在设备类型、深浅色等不同配置下有不同的取值)。 在开发过程中,分层参数的用法与资源限定词基本一致。开发者可以通过"$r('sys.type.resource_id')"的形式引用系统资源。sys代表是系统资源;type代表资源类型,值可以取color、float、string和media;resource_id代表资源id。 -可以查看本文[应用UX设计中关于资源的介绍](design-resources.md),获取系统支持的资源ID及其在不同配置下的取值。 +可以查看[应用UX设计中关于资源的介绍](../../../design/ux-design/design-resources.md),获取系统支持的资源ID及其在不同配置下的取值。 > **说明:** > - 仅声明式开发范式支持使用分层参数,类Web开发范式不支持。 diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/responsive-layout.md b/zh-cn/application-dev/key-features/multi-device-app-dev/responsive-layout.md index f4790177acc329d3e8c22bd043c69a69302e5d36..83b16dfed29cad6e202ea40175a4136bcdec5fe7 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/responsive-layout.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/responsive-layout.md @@ -48,7 +48,7 @@ 通过窗口对象监听断点变化的核心是获取窗口对象及注册窗口尺寸变化的回调函数。 -1. 在Ability的[onWindowStageCreate](../../application-models/uiability-lifecycle.md)生命周期回调中,通过[窗口](../../reference/apis/js-apis-window.md)对象获取启动时的应用窗口宽度并注册回调函数监听窗口尺寸变化。将窗口尺寸的长度单位[由px换算为vp](../../key-features/multi-device-app-dev/visual-basics.md#视觉基础)后,即可基于前文中介绍的规则得到当前断点值,此时可以使用[状态变量](../../quick-start/arkts-state.md)记录当前的断点值方便后续使用。 +1. 在Ability的[onWindowStageCreate](../../application-models/uiability-lifecycle.md)生命周期回调中,通过[窗口](../../reference/apis/js-apis-window.md)对象获取启动时的应用窗口宽度并注册回调函数监听窗口尺寸变化。将窗口尺寸的长度单位[由px换算为vp](../../../design/ux-design/visual-basis.md#视觉基础)后,即可基于前文中介绍的规则得到当前断点值,此时可以使用[状态变量](../../quick-start/arkts-state.md)记录当前的断点值方便后续使用。 ```ts // MainAbility.ts diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/start-with-a-example.md b/zh-cn/application-dev/key-features/multi-device-app-dev/start-with-a-example.md index dd60819c19955bb7a32fea213e7ac53fe33a1e1c..9e17fbe709ff58b754e52f1a82ae5108a7666c44 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/start-with-a-example.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/start-with-a-example.md @@ -20,7 +20,7 @@ | 大设备 | [840, +∞) | > **说明:** -> - vp是virtual pixel(虚拟像素)的缩写,是OpenHarmony中常用的长度单位,详见本文[视觉基础](visual-basics.md)小节中的介绍。 +> - vp是virtual pixel(虚拟像素)的缩写,是OpenHarmony中常用的长度单位,详见[视觉基础](../../../design/ux-design/visual-basis.md)小节中的介绍。 > > - 此处基于设备屏幕宽度划分不同设备是为了读者方便理解。通常智能设备上的应用都是以全屏的形式运行,但随着移动技术的发展,当前部分智能设备支持应用以自由窗口模式运行(即用户可以通过拖拽等操作自由调整应用运行窗口的尺寸),故以应用窗口尺寸为基准进行划分更为合适,本文后续的响应式布局章节中将详细介绍相关内容。 > @@ -50,7 +50,7 @@ 如此,既在各设备上体现了UX的一致性,也在各设备上体现了UX的差异性,从而既可以保障各设备上应用界面的体验,也可以最大程度复用界面代码。 -在本文[应用UX设计章节](design-principles.md)中,将详细介绍应用的UX设计规则。 +在[应用UX设计章节](../../../design/ux-design/app-ux-design.md)中,将详细介绍应用的UX设计规则。 ## 工程管理及调试 diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/typical-layout-scenario.md b/zh-cn/application-dev/key-features/multi-device-app-dev/typical-layout-scenario.md index 9ce49b2a0c0e082fb717ffee5e630744c0c0b2cd..edfd5cb2113d3cb7d450444da890268bde24e23b 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/typical-layout-scenario.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/typical-layout-scenario.md @@ -625,7 +625,7 @@ struct TripleColumnSample { | sm | md | lg | | -------------------------------------------- | --------------------------------------- | --------------------------------------- | -| 弹窗居中显示,
与窗口左右两侧各间距24vp。 | 弹窗居中显示,其宽度约为窗口宽度的1/2。 | 弹窗居中显示,其宽度约为窗口宽度的1/3。 | +| 弹窗横向居中,纵向位于底部显示,与窗口左右两侧各间距24vp。 | 弹窗居中显示,其宽度约为窗口宽度的1/2。 | 弹窗居中显示,其宽度约为窗口宽度的1/3。 | | ![](figures/custom_dialog_sm.png) | ![](figures/custom_dialog_md.png) | ![](figures/custom_dialog_lg.png) | **实现方案** diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/visual-basics.md b/zh-cn/application-dev/key-features/multi-device-app-dev/visual-basics.md deleted file mode 100644 index 357bb82cf40791bb360ad2f974fe170472cc7f06..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/visual-basics.md +++ /dev/null @@ -1,59 +0,0 @@ -# 视觉基础 - - -**虚拟像素单位:vp** - - -虚拟像素(virtual pixel)是一台设备针对应用而言所具有的虚拟尺寸(区别于屏幕硬件本身的像素单位)。它提供了一种灵活的方式来适应不同屏幕密度的显示效果。 - - -![zh-cn_image_0000001224333864](figures/zh-cn_image_0000001224333864.png) - - -相同的vp,在不同像素密度的屏幕上,对应不同px,一般称px/vp为像素密度比。像素密度比为当前设备屏幕的dpi/160。 - - -在dpi为160的OpenHarmony设备上,像素密度比为1,则1vp等于1px。 - - -以vp为尺寸标注单位,可使相同元素在不同密度的设备上具有一致的视觉体量,使用px则容易导致体量不一致的问题。 - - -**8vp网格系统** - - -基于 8vp 为网格的基本单位可以对界面上元素的大小、位置、对齐方式进行更好的规划,构建更有层次感、秩序感,以及多设备上一致的布局效果。一些更小的控件(例如图标)大小也可以对齐 4vp 的网格大小。 - - -![8vp](figures/8vp.png) - - -**字体像素单位:fp** - - -字体像素(font pixel) 大小默认情况下与 vp 相同,即默认情况下 1 fp = 1vp。 - - -**视觉属性:分层参数** - - -分层参数是根据使用场景定义的视觉属性ID,通过在不同色彩主题、多种设备上配置不同的数值,实现多设备适配的效果。OpenHarmony的分层参数包含色彩、字体、圆角、间距、阴影、模糊、缩放,并提供了默认实现。设备、应用、服务均可在此基础上管理并自定义不同场景的视觉属性。 - - -![画板 copy](figures/画板copy.png) - - -例如,对于不同场景的主色调定义了对应的ID与默认实现 - - -| 场景 | 色值 | ID | -| -------- | -------- | -------- | -| 高亮色 | \#007DFF | ohos_id_color_emphasize | -| 高亮色反色 | #006CDE |ohos_id_color_emphasize_contrary| -| 警告色 | \#FA2A2D |ohos_id_color_warning| -| 警示色 | \#FF7500 |ohos_id_color_alert| -| 通讯色 | \#E84826 |ohos_id_color_handup| -| 通讯色 | \#00CB87 |ohos_id_color_connected| - - -关于OpenHarmony默认提供的所有分层参数,详见:[资源](design-resources.md) diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/visual-style-color.md b/zh-cn/application-dev/key-features/multi-device-app-dev/visual-style-color.md deleted file mode 100644 index fd06e85f818a852366fb282384108975b7374a3e..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/visual-style-color.md +++ /dev/null @@ -1,23 +0,0 @@ -# 色彩 - - -色彩能够赋予应用界面足够的生动性,并给用户提供不同设备上、不同应用间视觉感官上的连续性。同时,合理地运用色彩可以传达关键的状态信息,给予用户即时的状态反馈以及数据可视化呈现。 - - -OpenHarmony采用蓝色作为系统的默认主色调。根据人因研究,对蓝色的接受度无论是在男性还是女性群体中,比例都是最高的。在世界地域维度,蓝色也是最受欢迎的颜色。更重要的是,对于大多数色觉障碍人士,蓝色依然可以被辨识。 - - -## 色值及使用场景 - -在色彩设计上,既保持统一的色彩语言,又根据多端不同的使用场景做了调整,带来定制化用户体验。 - -例如,高亮色ohos_id_color_activated,在不同设备和色彩模式上会有不同具体的值: - - | | | -| -------- | -------- | -| ![zh-cn_image_0000001400554657](figures/zh-cn_image_0000001400554657.png)
用于默认设备浅色风格。 | ![zh-cn_image_0000001400874297](figures/zh-cn_image_0000001400874297.png)
用于默认设备深色风格。 | -| ![zh-cn_image_0000001350234552](figures/zh-cn_image_0000001350234552.png)
用于智慧屏深色风格。 | ![zh-cn_image_0000001400674189](figures/zh-cn_image_0000001400674189.png)
用于智能穿戴深色风格。 | - -OpenHarmony后续将支持深色模式、浅色模式,及不同主题切换能力。 - -关于OpenHarmony默认提供的色彩相关分层参数,详见:[资源](design-resources.md) diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/visual-style-font.md b/zh-cn/application-dev/key-features/multi-device-app-dev/visual-style-font.md deleted file mode 100644 index 840f536ef52efc380cc9aeeb04fb52640f341a24..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/visual-style-font.md +++ /dev/null @@ -1,13 +0,0 @@ -# 字体 - - -字体直接影响界面的展示效果和用户的阅读效率。优秀的字形设计、统一的多语言字形风格、正确的字体排版,能有效地提升应用使用体验,并传递品牌连续性。 - - -## 多设备字号层级 - -选择合适的字号有助于定义内容的信息层级以及增强内容的可读性。通过研究全场景设备的显示环境、用户使用时环境的差异,OpenHarmony结合分层参数为不同设备形态提供了一套构建信息层级的字号系统。 - -![字体 copy 2](figures/字体copy2.png) - -关于OpenHarmony默认提供的字体相关分层参数,详见:[资源](design-resources.md) diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/visual-style-icon.md b/zh-cn/application-dev/key-features/multi-device-app-dev/visual-style-icon.md deleted file mode 100644 index 1647101ade0e1696ca1d95d1b26867b00b21030f..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/visual-style-icon.md +++ /dev/null @@ -1,10 +0,0 @@ -# 图标 - - -图标是操作系统与用户界面关键的视觉元素之一。图标应当具备直接识别关键信息或语义的特质,帮助用户轻松辨别图标所代表的含义。为了保证用户在不同的设备中视觉体验的一致性,在图标的设计上应当保持应用图标的元素一致,再根据不同的设备匹配对应的图标背板以适应于各种场景。除此之外,图标在颜色的使用上应当遵循符合人因的色彩规则,满足用户阅读的舒适度以及整体界面的和谐程度。对于面状图标与线状图标的使用应当遵循系统的设计规则,两种样式使用同一种图形结构,降低用户阅读时再次识别的成本。 - - -![zh-cn_image_0000001268334113](figures/zh-cn_image_0000001268334113.jpg) - - -关于OpenHarmony默认提供的图标库,详见[线上图标库](https://developer.harmonyos.com/cn/design/harmonyos-icon/)。 diff --git a/zh-cn/application-dev/media/camera-device-input.md b/zh-cn/application-dev/media/camera-device-input.md index b3ceea2db9ad0456ec9c44847f5ff3ef561c2642..67f66c0641a32323abc36e7876fdadcc2ce54978 100644 --- a/zh-cn/application-dev/media/camera-device-input.md +++ b/zh-cn/application-dev/media/camera-device-input.md @@ -13,11 +13,11 @@ ``` 2. 通过getCameraManager()方法,获取cameraManager对象。 - + [各类Context的获取方式](../application-models/application-context-stage.md)。 ```ts - let cameraManager; - let context: any = getContext(this); - cameraManager = camera.getCameraManager(context) + let cameraManager: camera.CameraManager; + let context: Context = getContext(this); + cameraManager = camera.getCameraManager(context); ``` > **说明:** @@ -27,17 +27,17 @@ 3. 通过cameraManager类中的getSupportedCameras()方法,获取当前设备支持的相机列表,列表中存储了设备支持的所有相机ID。若列表不为空,则说明列表中的每个ID都支持独立创建相机对象;否则,说明当前设备无可用相机,不可继续后续操作。 ```ts - let cameraArray = cameraManager.getSupportedCameras(); - if (cameraArray.length <= 0) { - console.error("cameraManager.getSupportedCameras error"); - return; + let cameraArray: Array = cameraManager.getSupportedCameras(); + if (cameraArray != undefined && cameraArray.length <= 0) { + console.error("cameraManager.getSupportedCameras error"); + return; } for (let index = 0; index < cameraArray.length; index++) { - console.info('cameraId : ' + cameraArray[index].cameraId); // 获取相机ID - console.info('cameraPosition : ' + cameraArray[index].cameraPosition); // 获取相机位置 - console.info('cameraType : ' + cameraArray[index].cameraType); // 获取相机类型 - console.info('connectionType : ' + cameraArray[index].connectionType); // 获取相机连接类型 + console.info('cameraId : ' + cameraArray[index].cameraId); // 获取相机ID + console.info('cameraPosition : ' + cameraArray[index].cameraPosition); // 获取相机位置 + console.info('cameraType : ' + cameraArray[index].cameraType); // 获取相机类型 + console.info('connectionType : ' + cameraArray[index].connectionType); // 获取相机连接类型 } ``` @@ -45,24 +45,25 @@ ```ts // 创建相机输入流 - let cameraInput; + let cameraInput: camera.CameraInput; try { - cameraInput = cameraManager.createCameraInput(cameraArray[0]); + cameraInput = cameraManager.createCameraInput(cameraArray[0]); } catch (error) { - console.error('Failed to createCameraInput errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to createCameraInput errorCode = ' + err.code); } // 监听cameraInput错误信息 - let cameraDevice = cameraArray[0]; - cameraInput.on('error', cameraDevice, (error) => { - console.info(`Camera input error code: ${error.code}`); - }) + let cameraDevice: camera.CameraDevice = cameraArray[0]; + cameraInput.on('error', cameraDevice, (error: BusinessError) => { + console.info(`Camera input error code: ${error.code}`); + }); // 打开相机 await cameraInput.open(); // 获取相机设备支持的输出流能力 - let cameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraArray[0]); + let cameraOutputCapability: camera.CameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraArray[0]); if (!cameraOutputCapability) { - console.error("cameraManager.getSupportedOutputCapability error"); - return; + console.error("cameraManager.getSupportedOutputCapability error"); + return; } console.info("outputCapability: " + JSON.stringify(cameraOutputCapability)); ``` @@ -75,8 +76,8 @@ 通过注册cameraStatus事件,通过回调返回监听结果,callback返回CameraStatusInfo参数,参数的具体内容可参考相机管理器回调接口实例[CameraStatusInfo](../reference/apis/js-apis-camera.md#camerastatusinfo)。 ```ts -cameraManager.on('cameraStatus', (err, cameraStatusInfo) => { +cameraManager.on('cameraStatus', (err: BusinessError, cameraStatusInfo: camera.CameraStatusInfo) => { console.info(`camera: ${cameraStatusInfo.camera.cameraId}`); console.info(`status: ${cameraStatusInfo.status}`); -}) +}); ``` diff --git a/zh-cn/application-dev/media/camera-metadata.md b/zh-cn/application-dev/media/camera-metadata.md index 9e681e0b819b5d93a62e8b948a46b221bf6e44f1..cc7c8aa2c1b3b20935d8c565928c05661ca4efa9 100644 --- a/zh-cn/application-dev/media/camera-metadata.md +++ b/zh-cn/application-dev/media/camera-metadata.md @@ -11,13 +11,13 @@ Metadata主要是通过一个TAG(Key),去找对应的Data,用于传递 1. 调用CameraOutputCapability类中的supportedMetadataObjectTypes()方法,获取当前设备支持的元数据类型,并通过createMetadataOutput()方法创建元数据输出流。 ```ts - let metadataObjectTypes = cameraOutputCapability.supportedMetadataObjectTypes; - let metadataOutput; + let metadataObjectTypes: Array = cameraOutputCapability.supportedMetadataObjectTypes; + let metadataOutput: camera.MetadataOutput; try { - metadataOutput = cameraManager.createMetadataOutput(metadataObjectTypes); + metadataOutput = cameraManager.createMetadataOutput(metadataObjectTypes); } catch (error) { - // 失败返回错误码error.code并处理 - console.info(error.code); + let err = error as BusinessError; + console.info('Failed to createMetadataOutput, error code: '+ err.code); } ``` @@ -25,9 +25,9 @@ Metadata主要是通过一个TAG(Key),去找对应的Data,用于传递 ```ts metadataOutput.start().then(() => { - console.info('Callback returned with metadataOutput started.'); - }).catch((err) => { - console.info('Failed to metadataOutput start '+ err.code); + console.info('Callback returned with metadataOutput started.'); + }).catch((err: BusinessError) => { + console.info('Failed to metadataOutput start, error code: '+ err.code); }); ``` @@ -35,9 +35,9 @@ Metadata主要是通过一个TAG(Key),去找对应的Data,用于传递 ```ts metadataOutput.stop().then(() => { - console.info('Callback returned with metadataOutput stopped.'); - }).catch((err) => { - console.info('Failed to metadataOutput stop '+ err.code); + console.info('Callback returned with metadataOutput stopped.'); + }).catch((err: BusinessError) => { + console.info('Failed to metadataOutput stop '+ err.code); }); ``` @@ -48,9 +48,9 @@ Metadata主要是通过一个TAG(Key),去找对应的Data,用于传递 - 通过注册监听获取metadata对象,监听事件固定为metadataObjectsAvailable。检测到有效metadata数据时,callback返回相应的metadata数据信息,metadataOutput创建成功时可监听。 ```ts - metadataOutput.on('metadataObjectsAvailable', (err, metadataObjectArr) => { - console.info(`metadata output metadataObjectsAvailable`); - }) + metadataOutput.on('metadataObjectsAvailable', (err: BusinessError, metadataObjectArr: Array) => { + console.info(`metadata output metadataObjectsAvailable`); + }); ``` > **说明:** @@ -60,7 +60,7 @@ Metadata主要是通过一个TAG(Key),去找对应的Data,用于传递 - 通过注册回调函数,获取监听metadata流的错误结果,callback返回metadata输出接口使用错误时返回的错误码,错误码类型参见[CameraErrorCode](../reference/apis/js-apis-camera.md#cameraerrorcode)。 ```ts - metadataOutput.on('error', (metadataOutputError) => { - console.info(`Metadata output error code: ${metadataOutputError.code}`); - }) + metadataOutput.on('error', (metadataOutputError: BusinessError) => { + console.info(`Metadata output error code: ${metadataOutputError.code}`); + }); ``` diff --git a/zh-cn/application-dev/media/camera-mode.md b/zh-cn/application-dev/media/camera-mode.md new file mode 100644 index 0000000000000000000000000000000000000000..09f82a0731fd5917d1047a7eaaa39f31b3d99efc --- /dev/null +++ b/zh-cn/application-dev/media/camera-mode.md @@ -0,0 +1,276 @@ +# 人像模式拍照实现方案 + +## 开发流程 + +人像模式依赖于模式化管理器,在获取到模式化管理的能力后,开始创建拍照流 + +模式化管理是对于cameraManager功能的增强与扩充,主要用于一些高级功能的管理,开发流程如下 + +![portraitgraphing Development Process](figures/portrait-capture-development-process.png) + +## 完整示例 +[各类Context的获取方式](../application-models/application-context-stage.md) +```ts +import camera from '@ohos.multimedia.camera'; +import image from '@ohos.multimedia.image'; +import media from '@ohos.multimedia.media'; + + +// 创建CameraManager对象 +let context: Context = getContext(this); +let cameraManager: camera.CameraManager = camera.getCameraManager(context); +if (!cameraManager) { + console.error("camera.getCameraManager error"); + return; +} +// 创建ModeManager对象 +let modeManager: camera.ModeManager = camera.getModeManager(context); +if (!cameraManager) { + console.error("camera.getModeManager error"); + return; +} +// 监听相机状态变化 +cameraManager.on('cameraStatus', (err: BusinessError, cameraStatusInfo: camera.CameraStatusInfo) => { + console.info(`camera : ${cameraStatusInfo.camera.cameraId}`); + console.info(`status: ${cameraStatusInfo.status}`); +}); +// 获取相机列表 +let cameraArray: Array = cameraManager.getSupportedCameras(); +if (cameraArray.length <= 0) { + console.error("cameraManager.getSupportedCameras error"); + return; +} + +for (let index = 0; index < cameraArray.length; index++) { + console.info('cameraId : ' + cameraArray[index].cameraId); // 获取相机ID + console.info('cameraPosition : ' + cameraArray[index].cameraPosition); // 获取相机位置 + console.info('cameraType : ' + cameraArray[index].cameraType); // 获取相机类型 + console.info('connectionType : ' + cameraArray[index].connectionType); // 获取相机连接类型 +} + +// 获取模式列表 +let cameraModeArray: Array = modeManager.getSupportedModes(cameraArray[0]); +if (cameraModeArray.length <= 0) { + console.error("modeManager.getSupportedModes error"); + return; +} +// 创建相机输入流 +let cameraInput: camera.CameraInput; +try { + cameraInput = cameraManager.createCameraInput(cameraArray[0]); +} catch (error) { + let err = error as BusinessError; + console.error('Failed to createCameraInput errorCode = ' + err.code); +} +// 监听cameraInput错误信息 +let cameraDevice: camera.CameraDevice = cameraArray[0]; +cameraInput.on('error', cameraDevice, (error: BusinessError) => { + console.info(`Camera input error code: ${error.code}`); +}) + +// 打开相机 +await cameraInput.open(); + +// 获取当前模式相机设备支持的输出流能力 +let cameraOutputCap: camera.CameraOutputCapability = modeManager.getSupportedOutputCapability(cameraArray[0], cameraModeArray[0]); +if (!cameraOutputCap) { + console.error("modeManager.getSupportedOutputCapability error"); + return; +} +console.info("outputCapability: " + JSON.stringify(cameraOutputCap)); + +let previewProfilesArray: Array = cameraOutputCap.previewProfiles; +if (!previewProfilesArray) { + console.error("createOutput previewProfilesArray == null || undefined"); +} + +let photoProfilesArray: Array = cameraOutputCap.photoProfiles; +if (!photoProfilesArray) { + console.error("createOutput photoProfilesArray == null || undefined"); +} + +// 创建预览输出流,其中参数 surfaceId 参考上文 XComponent 组件,预览流为XComponent组件提供的surface +let previewOutput: camera.PreviewOutput; +try { + previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId); +} catch (error) { + let err = error as BusinessError; + console.error("Failed to create the PreviewOutput instance. error code:" + err.code); +} +// 监听预览输出错误信息 +previewOutput.on('error', (error: BusinessError) => { + console.info(`Preview output error code: ${error.code}`); +}) +// 创建ImageReceiver对象,并设置照片参数:分辨率大小是根据前面 photoProfilesArray 获取的当前设备所支持的拍照分辨率大小去设置 +let imageReceiver: image.ImageReceiver = image.createImageReceiver(1920, 1080, 4, 8); +// 获取照片显示SurfaceId +let photoSurfaceId: string = await imageReceiver.getReceivingSurfaceId(); +// 创建拍照输出流 +let photoOutput: camera.PhotoOutput; +try { + photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId); +} catch (error) { + let err = error as BusinessError; + console.error('Failed to createPhotoOutput errorCode = ' + err.code); +} +//创建portrait会话 +let portraitSession: camera.CaptureSession; +try { + portraitSession = modeManager.createCaptureSession(cameraModeArray[0]); +} catch (error) { + let err = error as BusinessError; + console.error('Failed to create the CaptureSession instance. errorCode = ' + err.code); +} + +// 监听portraitSession错误信息 +portraitSession.on('error', (error: BusinessError) => { + console.info(`Capture session error code: ${error.code}`); +}); + +// 开始配置会话 +try { + portraitSession.beginConfig(); +} catch (error) { + let err = error as BusinessError; + console.error('Failed to beginConfig. errorCode = ' + err.code); +} + +// 向会话中添加相机输入流 +try { + portraitSession.addInput(cameraInput); +} catch (error) { + let err = error as BusinessError; + console.error('Failed to addInput. errorCode = ' + err.code); +} + +// 向会话中添加预览输出流 +try { + portraitSession.addOutput(previewOutput); +} catch (error) { + let err = error as BusinessError; + console.error('Failed to addOutput(previewOutput). errorCode = ' + err.code); +} + +// 向会话中添加拍照输出流 +try { + portraitSession.addOutput(photoOutput); +} catch (error) { + let err = error as BusinessError; + console.error('Failed to addOutput(photoOutput). errorCode = ' + err.code); +} + +// 提交会话配置 +await portraitSession.commitConfig(); + +// 启动会话 +await portraitSession.start().then(() => { + console.info('Promise returned to indicate the session start success.'); +}) + +// 获取支持的美颜类型 +let beautyTypes: Array; +try { + beautyTypes = portraitSession.getSupportedBeautyTypes(); +} catch (error) { + let err = error as BusinessError; + console.error('Failed to get the beauty types. errorCode = ' + err.code); +} +// 获取支持的美颜类型对应的美颜强度范围 +let beautyRanges: Array; +try { + beautyRanges = portraitSession.getSupportedBeautyRanges(beautyTypes[0]); +} catch (error) { + let err = error as BusinessError; + console.error('Failed to get the beauty types ranges. errorCode = ' + err.code); +} +// 设置美颜类型及对应的美颜强度 +try { + portraitSession.setBeauty(beautyTypes[0], beautyRanges[0]); +} catch (error) { + let err = error as BusinessError; + console.error('Failed to set the beauty type value. errorCode = ' + err.code); +} +// 获取已经设置的美颜类型对应的美颜强度 +let beautyLevel: number; +try { + beautyLevel = portraitSession.getBeauty(beautyTypes[0]); +} catch (error) { + let err = error as BusinessError; + console.error('Failed to get the beauty type value. errorCode = ' + err.code); +} + +// 获取支持的滤镜类型 +let filterTypes: Array; +try { + filterTypes = portraitSession.getSupportedFilters(); +} catch (error) { + let err = error as BusinessError; + console.error('Failed to get the filter types. errorCode = ' + err.code); +} +// 设置滤镜类型 +try { + portraitSession.setFilter(filterTypes[0]); +} catch (error) { + let err = error as BusinessError; + console.error('Failed to set the filter type value. errorCode = ' + err.code); +} +// 获取已经设置的滤镜类型 +let filter: number; +try { + filter = portraitSession.getFilter(); +} catch (error) { + let err = error as BusinessError; + console.error('Failed to get the filter type value. errorCode = ' + err.code); +} + +// 获取支持的虚化类型 +let portraitTypes: Array; +try { + portraitTypes = portraitSession.getSupportedPortraitEffects(); +} catch (error) { + let err = error as BusinessError; + console.error('Failed to get the portrait effects types. errorCode = ' + err.code); +} +// 设置虚化类型 +try { + portraitSession.setPortraitEffect(portraitTypes[0]); +} catch (error) { + let err = error as BusinessError; + console.error('Failed to set the portrait effects value. errorCode = ' + err.code); +} +// 获取已经设置的虚化类型 +let effect: camera.PortraitEffect; +try { + effect = portraitSession.getPortraitEffect(); +} catch (error) { + let err = error as BusinessError; + console.error('Failed to get the portrait effects value. errorCode = ' + err.code); +} + +let captureSettings: camera.PhotoCaptureSetting; +// 使用当前拍照设置进行拍照 +photoOutput.capture(captureSettings, async (err: BusinessError) => { + if (err) { + console.error('Failed to capture the photo ${err.message}'); + return; + } + console.info('Callback invoked to indicate the photo capture request success.'); +}); +// 停止当前会话 +portraitSession.stop(); + +// 释放相机输入流 +cameraInput.close(); + +// 释放预览输出流 +previewOutput.release(); + +// 释放拍照输出流 +photoOutput.release(); + +// 释放会话 +portraitSession.release(); + +// 会话置空 +portraitSession = null; +``` diff --git a/zh-cn/application-dev/media/camera-overview.md b/zh-cn/application-dev/media/camera-overview.md index 0e9226066c85923d45a207e84b109e7bf82299ad..15aafd04d4865fa0086b42544d2ee1c2f2753f13 100644 --- a/zh-cn/application-dev/media/camera-overview.md +++ b/zh-cn/application-dev/media/camera-overview.md @@ -30,4 +30,4 @@ 针对相机开发,有以下相关实例可供参考: -- [相机和媒体库(ArkTS)(Full SDK)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Beta2/code/SystemFeature/Media/Camera) \ No newline at end of file +- [相机和媒体库(ArkTS)(Full SDK)(API10)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SystemFeature/Media/Camera) diff --git a/zh-cn/application-dev/media/camera-performance-improvement.md b/zh-cn/application-dev/media/camera-performance-improvement.md index dd8310024d9e350713d06aae072732083456c152..7f1bc46078ee1090644f88d16db6a5425f8af220 100644 --- a/zh-cn/application-dev/media/camera-performance-improvement.md +++ b/zh-cn/application-dev/media/camera-performance-improvement.md @@ -31,19 +31,21 @@ ![](figures/deferred-surface-sequence-diagram.png) +[各类Context的获取方式](../application-models/application-context-stage.md) + ```js import camera from '@ohos.multimedia.camera'; -function async preview(context: Context, cameraInfo: camera.Device, previewProfile: camera.Profile, photoProfile: camera.Profile, surfaceId: string): Promise { +async function Preview(context: Context, cameraInfo: camera.CameraDevice, previewProfile: camera.Profile, photoProfile: camera.Profile, surfaceId: string): Promise { const cameraManager: camera.CameraManager = camera.getCameraManager(context); - const cameraInput camera.CameraInput = await cameraManager.createCameraInput(cameraInfo) + const cameraInput: camera.CameraInput = cameraManager.createCameraInput(cameraInfo); const previewOutput: camera.PreviewOutput = await cameraManager.createDeferredPreviewOutput(previewProfile); - const photoOutput: camera.PhotoOutput = await cameraManager.createPhotoOutput(photoProfile); - const session: camera.CaptureSession = await this.mCameraManager.createCaptureSession(); - await session.beginConfig(); - await session.addInput(cameraInput); - await session.addOutput(previewOutput); - await session.addOutput(photoOutput); + const photoOutput: camera.PhotoOutput = cameraManager.createPhotoOutput(photoProfile, surfaceId); + const session: camera.CaptureSession = cameraManager.createCaptureSession(); + session.beginConfig(); + session.addInput(cameraInput); + session.addOutput(previewOutput); + session.addOutput(photoOutput); await session.commitConfig(); await session.start(); await previewOutput.addDeferredSurface(surfaceId); @@ -79,33 +81,34 @@ function async preview(context: Context, cameraInfo: camera.Device, previewProfi ![](figures/quick-thumbnail-sequence-diagram.png) +[各类Context的获取方式](../application-models/application-context-stage.md) ```js -import camera from '@ohos.multimedia.camera' - -this.cameraManager = camera.getCameraManager(globalThis.abilityContext); -let cameras = this.cameraManager.getSupportedCameras() +import camera from '@ohos.multimedia.camera'; +let context: Context = getContext(this); +let cameraManager: camera.CameraManager = camera.getCameraManager(context); +let cameras: Array = cameraManager.getSupportedCameras(); // 创建CaptureSession实例 -this.captureSession = await this.cameraManager.createCaptureSession() +let captureSession: camera.CaptureSession = cameraManager.createCaptureSession(); // 开始配置会话 -await this.captureSession.beginConfig() +captureSession.beginConfig(); // 把CameraInput加入到会话 -this.cameraInput = await this.cameraManager.createCameraInput(cameras[0]) -await this.cameraInput.open() -await this.captureSession.addInput(this.cameraInput) +let cameraInput: camera.CameraInput = cameraManager.createCameraInput(cameras[0]); +cameraInput.open(); +captureSession.addInput(cameraInput); // 把PhotoOutPut加入到会话 -this.photoOutPut = await this.cameraManager.createPhotoOutput(photoProfile, surfaceId) -await this.captureSession.addOutput(this.photoOutPut) -boolean isSupported = this.photoOutPut.isQuickThumbnailSupported() +let photoOutPut: camera.PhotoOutput = cameraManager.createPhotoOutput(photoProfile, surfaceId); +captureSession.addOutput(photoOutPut); +let isSupported: boolean = photoOutPut.isQuickThumbnailSupported(); if (isSupported) { - // 使能快速缩略图 - this.photoOutPut.enableQuickThumbnail(true) - this.photoOutPut.on('quickThumbnail', (err, pixelmap) => { + // 使能快速缩略图 + photoOutPut.enableQuickThumbnail(true); + photoOutPut.on('quickThumbnail', (err: BusinessError, pixelmap: image.PixelMap) => { if (err || pixelmap === undefined) { - Logger.error(this.tag, 'photoOutPut on thumbnail failed ') - return + console.error('photoOutPut on thumbnail failed'); + return; } // 显示或保存pixelmap - this.showOrSavePicture(pixelmap) + showOrSavePicture(pixelmap); }) } ``` @@ -135,16 +138,19 @@ if (isSupported) { ![](figures/prelaunch-sequence-diagram.png) +[各类Context的获取方式](../application-models/application-context-stage.md) + - **桌面应用** ```js - import camera from '@ohos.multimedia.camera' - - this.cameraManager = camera.getCameraManager(globalThis.abilityContext); + import camera from '@ohos.multimedia.camera'; + let context: Context = getContext(this); + let cameraManager: camera.CameraManager = camera.getCameraManager(context); try { - this.cameraManager.prelaunch(); + cameraManager.prelaunch(); } catch (error) { - console.error(`catch error: Code: ${error.code}, message: ${error.message}`) + let err = error as BusinessError; + console.error(`catch error: Code: ${err.code}, message: ${err.message}`); } ``` @@ -155,15 +161,16 @@ if (isSupported) { 具体申请方式及校验方式,请参考[访问控制授权申请指导](../security/accesstoken-guidelines.md)。 ```js - import camera from '@ohos.multimedia.camera' - - this.cameraManager = camera.getCameraManager(globalThis.abilityContext); - let cameras = this.cameraManager.getSupportedCameras() - if(this.cameraManager.isPrelaunchSupported(cameras[0])) { + import camera from '@ohos.multimedia.camera'; + let context: Context = getContext(this); + let cameraManager: camera.CameraManager = camera.getCameraManager(context); + let cameras: Array = cameraManager.getSupportedCameras(); + if(cameraManager.isPrelaunchSupported(cameras[0])) { try { - this.cameraManager.setPrelaunchConfig({cameraDevice: cameras[0]}); + cameraManager.setPrelaunchConfig({cameraDevice: cameras[0]}); } catch (error) { - console.error(`catch error: Code: ${error.code}, message: ${error.message}`) + let err = error as BusinessError; + console.error(`catch error: Code: ${err.code}, message: ${err.message}`); } } ``` diff --git a/zh-cn/application-dev/media/camera-preview.md b/zh-cn/application-dev/media/camera-preview.md index 2836389c3b3db5ed27629f249bbf333e3ec7caaf..ccb84119acd25ee43ea56160ea1fc970d69a74d7 100644 --- a/zh-cn/application-dev/media/camera-preview.md +++ b/zh-cn/application-dev/media/camera-preview.md @@ -14,36 +14,36 @@ // 创建XComponentController mXComponentController: XComponentController = new XComponentController; build() { - Flex() { - // 创建XComponent - XComponent({ - id: '', - type: 'surface', - libraryname: '', - controller: this.mXComponentController - }) - .onLoad(() => { - // 设置Surface宽高(1920*1080),预览尺寸设置参考前面 previewProfilesArray 获取的当前设备所支持的预览分辨率大小去设置 - this.mXComponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080}); - // 获取Surface ID - globalThis.surfaceId = this.mXComponentController.getXComponentSurfaceId(); - }) - .width('1920px') - .height('1080px') - } + Flex() { + // 创建XComponent + XComponent({ + id: '', + type: 'surface', + libraryname: '', + controller: this.mXComponentController + }) + .onLoad(() => { + // 设置Surface宽高(1920*1080),预览尺寸设置参考前面 previewProfilesArray 获取的当前设备所支持的预览分辨率大小去设置 + this.mXComponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080}); + // 获取Surface ID + globalThis.surfaceId = this.mXComponentController.getXComponentSurfaceId(); + }) + .width('1920px') + .height('1080px') + } } ``` 2. 通过CameraOutputCapability类中的previewProfiles()方法获取当前设备支持的预览能力,返回previewProfilesArray数组 。通过createPreviewOutput()方法创建预览输出流,其中,createPreviewOutput()方法中的两个参数分别是previewProfilesArray数组中的第一项和步骤一中获取的surfaceId。 ```ts - let previewProfilesArray = cameraOutputCapability.previewProfiles; - let previewOutput; + let previewProfilesArray: Array = cameraOutputCapability.previewProfiles; + let previewOutput: camera.PreviewOutput; try { - previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId); - } - catch (error) { - console.error("Failed to create the PreviewOutput instance." + error); + previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId); + } catch (error) { + let err = error as BusinessError; + console.error("Failed to create the PreviewOutput instance. error code: " + err.code); } ``` @@ -51,9 +51,9 @@ ```ts previewOutput.start().then(() => { - console.info('Callback returned with previewOutput started.'); - }).catch((err) => { - console.info('Failed to previewOutput start '+ err.code); + console.info('Callback returned with previewOutput started.'); + }).catch((err: BusinessError) => { + console.info('Failed to previewOutput start '+ err.code); }); ``` @@ -66,22 +66,22 @@ ```ts previewOutput.on('frameStart', () => { - console.info('Preview frame started'); - }) + console.info('Preview frame started'); + }); ``` - 通过注册固定的frameEnd回调函数获取监听预览结束结果,previewOutput创建成功时即可监听,预览完成最后一帧时触发,有该事件返回结果则认为预览流已结束。 ```ts previewOutput.on('frameEnd', () => { - console.info('Preview frame ended'); - }) + console.info('Preview frame ended'); + }); ``` - 通过注册固定的error回调函数获取监听预览输出错误结果,callback返回预览输出接口使用错误时对应的错误码,错误码类型参见[CameraErrorCode](../reference/apis/js-apis-camera.md#cameraerrorcode)。 ```ts - previewOutput.on('error', (previewOutputError) => { - console.info(`Preview output error code: ${previewOutputError.code}`); - }) + previewOutput.on('error', (previewOutputError: BusinessError) => { + console.info(`Preview output error code: ${previewOutputError.code}`); + }); ``` diff --git a/zh-cn/application-dev/media/camera-recording-case.md b/zh-cn/application-dev/media/camera-recording-case.md index a1f980fd2af149a10a9fce339d8f18f28c7bba6c..5b9d965fc2ab99a7d00f868806c5863203e5c44e 100644 --- a/zh-cn/application-dev/media/camera-recording-case.md +++ b/zh-cn/application-dev/media/camera-recording-case.md @@ -8,240 +8,239 @@ ## 完整示例 - +[各类Context的获取方式](../application-models/application-context-stage.md) ```ts -import camera from '@ohos.multimedia.camera' -import media from '@ohos.multimedia.media' +import camera from '@ohos.multimedia.camera'; +import media from '@ohos.multimedia.media'; // 创建CameraManager对象 -context: any = getContext(this) -let cameraManager = camera.getCameraManager(this.context) +let context: Context = getContext(this); +let cameraManager: camera.CameraManager = camera.getCameraManager(context); if (!cameraManager) { - console.error("camera.getCameraManager error") - return; -} + console.error("camera.getCameraManager error"); + return; +} // 监听相机状态变化 -cameraManager.on('cameraStatus', (err, cameraStatusInfo) => { - console.log(`camera : ${cameraStatusInfo.camera.cameraId}`); - console.log(`status: ${cameraStatusInfo.status}`); -}) +cameraManager.on('cameraStatus', (err: BusinessError, cameraStatusInfo: camera.CameraStatusInfo) => { + console.log(`camera : ${cameraStatusInfo.camera.cameraId}`); + console.log(`status: ${cameraStatusInfo.status}`); +}); +// 获取相机列表 +let cameraArray: Array = cameraManager.getSupportedCameras(); +if (cameraArray.length <= 0) { + console.error("cameraManager.getSupportedCameras error") + return; +} // 获取相机设备支持的输出流能力 -let cameraOutputCap = cameraManager.getSupportedOutputCapability(cameraArray[0]); +let cameraOutputCap: camera.CameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraArray[0]); if (!cameraOutputCap) { - console.error("cameraManager.getSupportedOutputCapability error") - return; + console.error("cameraManager.getSupportedOutputCapability error") + return; } console.log("outputCapability: " + JSON.stringify(cameraOutputCap)); -let previewProfilesArray = cameraOutputCap.previewProfiles; +let previewProfilesArray: Array = cameraOutputCap.previewProfiles; if (!previewProfilesArray) { - console.error("createOutput previewProfilesArray == null || undefined") -} + console.error("createOutput previewProfilesArray == null || undefined"); +} -let photoProfilesArray = cameraOutputCap.photoProfiles; +let photoProfilesArray: Array = cameraOutputCap.photoProfiles; if (!photoProfilesArray) { - console.error("createOutput photoProfilesArray == null || undefined") -} + console.error("createOutput photoProfilesArray == null || undefined"); +} -let videoProfilesArray = cameraOutputCap.videoProfiles; +let videoProfilesArray: Array = cameraOutputCap.videoProfiles; if (!videoProfilesArray) { - console.error("createOutput videoProfilesArray == null || undefined") -} + console.error("createOutput videoProfilesArray == null || undefined"); +} -let metadataObjectTypesArray = cameraOutputCap.supportedMetadataObjectTypes; +let metadataObjectTypesArray: Array = cameraOutputCap.supportedMetadataObjectTypes; if (!metadataObjectTypesArray) { - console.error("createOutput metadataObjectTypesArray == null || undefined") + console.error("createOutput metadataObjectTypesArray == null || undefined"); } // 配置参数以实际硬件设备支持的范围为准 let AVRecorderProfile = { - audioBitrate : 48000, - audioChannels : 2, - audioCodec : media.CodecMimeType.AUDIO_AAC, - audioSampleRate : 48000, - fileFormat : media.ContainerFormatType.CFT_MPEG_4, - videoBitrate : 2000000, - videoCodec : media.CodecMimeType.VIDEO_MPEG4, - videoFrameWidth : 640, - videoFrameHeight : 480, - videoFrameRate : 30 -} -let AVRecorderConfig = { - audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, - videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, - profile : AVRecorderProfile, - url : 'fd://', // 文件需先由调用者创建,赋予读写权限,将文件fd传给此参数,eg.fd://45--file:///data/media/01.mp4 - rotation : 0, // 合理值0、90、180、270,非合理值prepare接口将报错 - location : { latitude : 30, longitude : 130 } -} - -let avRecorder -media.createAVRecorder((error, recorder) => { - if (recorder != null) { - avRecorder = recorder; - console.log('createAVRecorder success'); - } else { - console.log(`createAVRecorder fail, error:${error}`); - } + audioBitrate : 48000, + audioChannels : 2, + audioCodec : media.CodecMimeType.AUDIO_AAC, + audioSampleRate : 48000, + fileFormat : media.ContainerFormatType.CFT_MPEG_4, + videoBitrate : 2000000, + videoCodec : media.CodecMimeType.VIDEO_MPEG4, + videoFrameWidth : 640, + videoFrameHeight : 480, + videoFrameRate : 30 +}; +let aVRecorderConfig = { + audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, + videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, + profile : AVRecorderProfile, + url : 'fd://', // 文件需先由调用者创建,赋予读写权限,将文件fd传给此参数,eg.fd://45--file:///data/media/01.mp4 + rotation : 0, // 合理值0、90、180、270,非合理值prepare接口将报错 + location : { latitude : 30, longitude : 130 } +}; + +let avRecorder: media.AVRecorder; +media.createAVRecorder((error: BusinessError, recorder: media.AVRecorder) => { + if (recorder != null) { + avRecorder = recorder; + console.log('createAVRecorder success'); + } else { + console.log(`createAVRecorder fail, error:${error}`); + } }); -avRecorder.prepare(AVRecorderConfig, (err) => { - if (err == null) { - console.log('prepare success'); - } else { - console.log('prepare failed and error is ' + err.message); - } +avRecorder.prepare(aVRecorderConfig, (err: BusinessError) => { + if (err == null) { + console.log('prepare success'); + } else { + console.log('prepare failed and error is ' + err.message); + } }) -let videoSurfaceId = null; // 该surfaceID用于传递给相机接口创造videoOutput -avRecorder.getInputSurface((err, surfaceId) => { - if (err == null) { - console.log('getInputSurface success'); - videoSurfaceId = surfaceId; - } else { - console.log('getInputSurface failed and error is ' + err.message); - } +let videoSurfaceId: string = null; // 该surfaceID用于传递给相机接口创造videoOutput +avRecorder.getInputSurface((err: BusinessError, surfaceId: string) => { + if (err == null) { + console.log('getInputSurface success'); + videoSurfaceId = surfaceId; + } else { + console.log('getInputSurface failed and error is ' + err.message); + } }); // 创建VideoOutput对象 -let videoOutput +let videoOutput: camera.VideoOutput; try { - videoOutput = cameraManager.createVideoOutput(videoProfilesArray[0], videoSurfaceId) + videoOutput = cameraManager.createVideoOutput(videoProfilesArray[0], videoSurfaceId) } catch (error) { - console.error('Failed to create the videoOutput instance. errorCode = ' + error.code); + console.error('Failed to create the videoOutput instance. errorCode = ' + error.code); } // 监听视频输出错误信息 -videoOutput.on('error', (error) => { - console.log(`Preview output error code: ${error.code}`); -}) +videoOutput.on('error', (error: BusinessError) => { + console.log(`Preview output error code: ${error.code}`); +}); //创建会话 -let captureSession +let captureSession: camera.CaptureSession; try { - captureSession = cameraManager.createCaptureSession() + captureSession = cameraManager.createCaptureSession(); } catch (error) { - console.error('Failed to create the CaptureSession instance. errorCode = ' + error.code); + console.error('Failed to create the CaptureSession instance. errorCode = ' + error.code); } // 监听session错误信息 -captureSession.on('error', (error) => { - console.log(`Capture session error code: ${error.code}`); -}) +captureSession.on('error', (error: BusinessError) => { + console.log(`Capture session error code: ${error.code}`); +}); // 开始配置会话 try { - captureSession.beginConfig() + captureSession.beginConfig(); } catch (error) { - console.error('Failed to beginConfig. errorCode = ' + error.code); -} - -// 获取相机列表 -let cameraArray = cameraManager.getSupportedCameras(); -if (cameraArray.length <= 0) { - console.error("cameraManager.getSupportedCameras error") - return; + console.error('Failed to beginConfig. errorCode = ' + error.code); } // 创建相机输入流 -let cameraInput +let cameraInput: camera.CameraInput; try { - cameraInput = cameraManager.createCameraInput(cameraArray[0]); + cameraInput = cameraManager.createCameraInput(cameraArray[0]); } catch (error) { - console.error('Failed to createCameraInput errorCode = ' + error.code); + console.error('Failed to createCameraInput errorCode = ' + error.code); } // 监听cameraInput错误信息 -let cameraDevice = cameraArray[0]; -cameraInput.on('error', cameraDevice, (error) => { - console.log(`Camera input error code: ${error.code}`); -}) +let cameraDevice: camera.CameraDevice = cameraArray[0]; +cameraInput.on('error', cameraDevice, (error: BusinessError) => { + console.log(`Camera input error code: ${error.code}`); +}); // 打开相机 await cameraInput.open(); // 向会话中添加相机输入流 try { - captureSession.addInput(cameraInput) + captureSession.addInput(cameraInput); } catch (error) { - console.error('Failed to addInput. errorCode = ' + error.code); + console.error('Failed to addInput. errorCode = ' + error.code); } // 创建预览输出流,其中参数 surfaceId 参考下面 XComponent 组件,预览流为XComponent组件提供的surface -let previewOutput +let previewOutput: camera.PreviewOutput; try { - previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId) + previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId); } catch (error) { - console.error("Failed to create the PreviewOutput instance.") + console.error("Failed to create the PreviewOutput instance.") } // 向会话中添加预览输入流 try { - captureSession.addOutput(previewOutput) + captureSession.addOutput(previewOutput); } catch (error) { - console.error('Failed to addOutput(previewOutput). errorCode = ' + error.code); + console.error('Failed to addOutput(previewOutput). errorCode = ' + error.code); } // 向会话中添加录像输出流 try { - captureSession.addOutput(videoOutput) + captureSession.addOutput(videoOutput); } catch (error) { - console.error('Failed to addOutput(videoOutput). errorCode = ' + error.code); + console.error('Failed to addOutput(videoOutput). errorCode = ' + error.code); } // 提交会话配置 -await captureSession.commitConfig() +await captureSession.commitConfig(); // 启动会话 await captureSession.start().then(() => { - console.log('Promise returned to indicate the session start success.'); -}) + console.log('Promise returned to indicate the session start success.'); +}); // 启动录像输出流 -videoOutput.start(async (err) => { - if (err) { - console.error('Failed to start the video output ${err.message}'); - return; - } - console.log('Callback invoked to indicate the video output start success.'); +videoOutput.start(async (err: BusinessError) => { + if (err) { + console.error('Failed to start the video output ${err.message}'); + return; + } + console.log('Callback invoked to indicate the video output start success.'); }); // 开始录像 avRecorder.start().then(() => { - console.log('videoRecorder start success'); -}) + console.log('videoRecorder start success'); +}); // 停止录像输出流 -videoOutput.stop((err) => { - if (err) { - console.error('Failed to stop the video output ${err.message}'); - return; - } - console.log('Callback invoked to indicate the video output stop success.'); +videoOutput.stop((err: BusinessError) => { + if (err) { + console.error('Failed to stop the video output ${err.message}'); + return; + } + console.log('Callback invoked to indicate the video output stop success.'); }); // 停止录像 avRecorder.stop().then(() => { - console.log('stop success'); -}) + console.log('stop success'); +}); // 停止当前会话 -captureSession.stop() +captureSession.stop(); // 释放相机输入流 -cameraInput.close() +cameraInput.close(); // 释放预览输出流 -previewOutput.release() +previewOutput.release(); // 释放录像输出流 -videoOutput.release() +videoOutput.release(); // 释放会话 -captureSession.release() +captureSession.release(); // 会话置空 -captureSession = null +captureSession = null; ``` diff --git a/zh-cn/application-dev/media/camera-recording.md b/zh-cn/application-dev/media/camera-recording.md index 95b38a8bb358eff10d5330e8d39f0f439b6cc71c..5847ea529c8f59b3b8c1294c187c0a0fd0c6beed 100644 --- a/zh-cn/application-dev/media/camera-recording.md +++ b/zh-cn/application-dev/media/camera-recording.md @@ -17,30 +17,31 @@ 系统提供的media接口可以创建一个录像AVRecorder实例,通过该实例的getInputSurface方法获取SurfaceId,与录像输出流做关联,处理录像输出流输出的数据。 ```ts - let AVRecorder; - media.createAVRecorder((error, recorder) => { - if (recorder != null) { - AVRecorder = recorder; - console.info('createAVRecorder success'); - } else { - console.info(`createAVRecorder fail, error:${error}`); - } + let avRecorder: media.AVRecorder; + media.createAVRecorder((error: BusinessError, recorder: media.AVRecorder) => { + if (recorder != null) { + avRecorder = recorder; + console.info('createAVRecorder success'); + } else { + console.info(`createAVRecorder fail, error:${error}`); + } + }); + // aVRecorderConfig可参考下一章节 + let aVRecorderConfig: media.AVRecorderConfig; + avRecorder.prepare(aVRecorderConfig, (err: BusinessError) => { + if (err == null) { + console.log('prepare success'); + } else { + console.log('prepare failed and error is ' + err.message); + } }); - // AVRecorderConfig可参考下一章节 - AVRecorder.prepare(AVRecorderConfig, (err) => { - if (err == null) { - console.log('prepare success'); - } else { - console.log('prepare failed and error is ' + err.message); - } - }) - let videoSurfaceId = null; - AVRecorder.getInputSurface().then((surfaceId) => { - console.info('getInputSurface success'); - videoSurfaceId = surfaceId; - }).catch((err) => { - console.info('getInputSurface failed and catch error is ' + err.message); + let videoSurfaceId: string = null; + avRecorder.getInputSurface().then((surfaceId: string) => { + console.info('getInputSurface success'); + videoSurfaceId = surfaceId; + }).catch((err: BusinessError) => { + console.info('getInputSurface failed and catch error is ' + err.message); }); ``` @@ -49,43 +50,44 @@ 通过CameraOutputCapability类中的videoProfiles,可获取当前设备支持的录像输出流。然后,定义创建录像的参数,通过createVideoOutput方法创建录像输出流。 ```ts - let videoProfilesArray = cameraOutputCapability.videoProfiles; + let videoProfilesArray: Array = cameraOutputCapability.videoProfiles; if (!videoProfilesArray) { - console.error("createOutput videoProfilesArray == null || undefined"); + console.error("createOutput videoProfilesArray == null || undefined"); } // 创建视频录制的参数 let videoConfig = { - videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, - profile: { - fileFormat : media.ContainerFormatType.CFT_MPEG_4, // 视频文件封装格式,只支持MP4 - videoBitrate : 100000, // 视频比特率 - videoCodec : media.CodecMimeType.VIDEO_MPEG4, // 视频文件编码格式,支持mpeg4和avc两种格式 - videoFrameWidth : 640, // 视频分辨率的宽 - videoFrameHeight : 480, // 视频分辨率的高 - videoFrameRate : 30 // 视频帧率 - }, - url: 'fd://35', - rotation: 90 // 90°为默认竖屏显示角度,如果由于设备原因或应用期望以其他方式显示等原因,请根据实际情况调整该参数 + videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, + profile: { + fileFormat : media.ContainerFormatType.CFT_MPEG_4, // 视频文件封装格式,只支持MP4 + videoBitrate : 100000, // 视频比特率 + videoCodec : media.CodecMimeType.VIDEO_MPEG4, // 视频文件编码格式,支持mpeg4和avc两种格式 + videoFrameWidth : 640, // 视频分辨率的宽 + videoFrameHeight : 480, // 视频分辨率的高 + videoFrameRate : 30 // 视频帧率 + }, + url: 'fd://35', + rotation: 90 // 90°为默认竖屏显示角度,如果由于设备原因或应用期望以其他方式显示等原因,请根据实际情况调整该参数 } // 创建avRecorder - let avRecorder; - media.createAVRecorder((error, recorder) => { + let avRecorder: media.AVRecorder; + media.createAVRecorder((error: BusinessError, recorder: media.AVRecorder) => { if (recorder != null) { - avRecorder = recorder; - console.info('createAVRecorder success'); + avRecorder = recorder; + console.info('createAVRecorder success'); } else { - console.info(`createAVRecorder fail, error:${error}`); + console.info(`createAVRecorder fail, error:${error}`); } }); // 设置视频录制的参数 avRecorder.prepare(videoConfig); // 创建VideoOutput对象 - let videoOutput; + let videoOutput: camera.VideoOutput; try { - videoOutput = cameraManager.createVideoOutput(videoProfilesArray[0], videoSurfaceId); + videoOutput = cameraManager.createVideoOutput(videoProfilesArray[0], videoSurfaceId); } catch (error) { - console.error('Failed to create the videoOutput instance. errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to create the videoOutput instance. errorCode = ' + err.code); } ``` @@ -93,17 +95,17 @@ 先通过videoOutput的start方法启动录像输出流,再通过avRecorder的start方法开始录像。 - ``` - videoOutput.start(async (err) => { - if (err) { - console.error('Failed to start the video output ${err.message}'); - return; - } - console.info('Callback invoked to indicate the video output start success.'); + ```ts + videoOutput.start(async (err: BusinessError) => { + if (err) { + console.error('Failed to start the video output ${err.message}'); + return; + } + console.info('Callback invoked to indicate the video output start success.'); }); avRecorder.start().then(() => { - console.info('avRecorder start success'); + console.info('avRecorder start success'); }); ``` @@ -113,15 +115,15 @@ ```ts videoRecorder.stop().then(() => { - console.info('stop success'); + console.info('stop success'); }); - videoOutput.stop((err) => { - if (err) { - console.error('Failed to stop the video output ${err.message}'); - return; - } - console.info('Callback invoked to indicate the video output stop success.'); + videoOutput.stop((err: BusinessError) => { + if (err) { + console.error('Failed to stop the video output ${err.message}'); + return; + } + console.info('Callback invoked to indicate the video output stop success.'); }); ``` @@ -134,22 +136,22 @@ ```ts videoOutput.on('frameStart', () => { - console.info('Video frame started'); - }) + console.info('Video frame started'); + }); ``` - 通过注册固定的frameEnd回调函数获取监听录像结束结果,videoOutput创建成功时即可监听,录像完成最后一帧时触发,有该事件返回结果则认为录像流已结束。 ```ts videoOutput.on('frameEnd', () => { - console.info('Video frame ended'); - }) + console.info('Video frame ended'); + }); ``` - 通过注册固定的error回调函数获取监听录像输出错误结果,callback返回预览输出接口使用错误时对应的错误码,错误码类型参见[CameraErrorCode](../reference/apis/js-apis-camera.md#cameraerrorcode)。 ```ts - videoOutput.on('error', (error) => { - console.info(`Video output error code: ${error.code}`); - }) + videoOutput.on('error', (error: BusinessError) => { + console.info(`Video output error code: ${error.code}`); + }); ``` diff --git a/zh-cn/application-dev/media/camera-session-management.md b/zh-cn/application-dev/media/camera-session-management.md index fdef64d33ff8226ab459f7e3c5f0967b7ee30ad6..1d40506b33a4035ea9344f5fd51478815097cf05 100644 --- a/zh-cn/application-dev/media/camera-session-management.md +++ b/zh-cn/application-dev/media/camera-session-management.md @@ -18,11 +18,12 @@ 1. 调用cameraManager类中的createCaptureSession()方法创建一个会话。 ```ts - let captureSession; + let captureSession: camera.CaptureSession; try { - captureSession = cameraManager.createCaptureSession(); + captureSession = cameraManager.createCaptureSession(); } catch (error) { - console.error('Failed to create the CaptureSession instance. errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to create the CaptureSession instance. errorCode = ' + err.code); } ``` @@ -30,9 +31,10 @@ ```ts try { - captureSession.beginConfig(); + captureSession.beginConfig(); } catch (error) { - console.error('Failed to beginConfig. errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to beginConfig. errorCode = ' + err.code); } ``` @@ -42,24 +44,27 @@ ```ts try { - captureSession.addInput(cameraInput); + captureSession.addInput(cameraInput); } catch (error) { - console.error('Failed to addInput. errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to addInput. errorCode = ' + err.code); } try { - captureSession.addOutput(previewOutput); + captureSession.addOutput(previewOutput); } catch (error) { - console.error('Failed to addOutput(previewOutput). errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to addOutput(previewOutput). errorCode = ' + err.code); } try { - captureSession.addOutput(photoOutput); + captureSession.addOutput(photoOutput); } catch (error) { - console.error('Failed to addOutput(photoOutput). errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to addOutput(photoOutput). errorCode = ' + err.code); } - await captureSession.commitConfig() ; + await captureSession.commitConfig(); await captureSession.start().then(() => { - console.info('Promise returned to indicate the session start success.'); - }) + console.info('Promise returned to indicate the session start success.'); + }); ``` 4. 会话控制。调用captureSession类中的stop()方法可以停止当前会话。调用removeOutput()和addOutput()方法可以完成会话切换控制。以下示例代码以移除拍照流photoOutput,添加视频流videoOutput为例,完成了拍照到录像的切换。 @@ -67,20 +72,23 @@ ```ts await captureSession.stop(); try { - captureSession.beginConfig(); + captureSession.beginConfig(); } catch (error) { - console.error('Failed to beginConfig. errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to beginConfig. errorCode = ' + err.code); } // 从会话中移除拍照输出流 try { - captureSession.removeOutput(photoOutput); + captureSession.removeOutput(photoOutput); } catch (error) { - console.error('Failed to removeOutput(photoOutput). errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to removeOutput(photoOutput). errorCode = ' + err.code); } // 向会话中添加视频输出流 try { - captureSession.addOutput(videoOutput); + captureSession.addOutput(videoOutput); } catch (error) { - console.error('Failed to addOutput(videoOutput). errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to addOutput(videoOutput). errorCode = ' + err.code); } ``` diff --git a/zh-cn/application-dev/media/camera-shooting-case.md b/zh-cn/application-dev/media/camera-shooting-case.md index c8f307cc352937643b72e9942730bae8db0c5a87..1f1b9081923a9e1b79532dd278a38f152206ace7 100644 --- a/zh-cn/application-dev/media/camera-shooting-case.md +++ b/zh-cn/application-dev/media/camera-shooting-case.md @@ -7,234 +7,249 @@ ![Photographing Development Process](figures/photographing-development-process.png) ## 完整示例 - +[各类Context的获取方式](../application-models/application-context-stage.md) ```ts -import camera from '@ohos.multimedia.camera' -import image from '@ohos.multimedia.image' -import media from '@ohos.multimedia.media' +import camera from '@ohos.multimedia.camera'; +import image from '@ohos.multimedia.image'; +import media from '@ohos.multimedia.media'; // 创建CameraManager对象 -context: any = getContext(this) -let cameraManager = camera.getCameraManager(this.context) +let context: Context = getContext(this); +let cameraManager: camera.CameraManager = camera.getCameraManager(context); if (!cameraManager) { - console.error("camera.getCameraManager error") - return; + console.error("camera.getCameraManager error"); + return; } // 监听相机状态变化 -cameraManager.on('cameraStatus', (err, cameraStatusInfo) => { - console.info(`camera : ${cameraStatusInfo.camera.cameraId}`); - console.info(`status: ${cameraStatusInfo.status}`); -}) +cameraManager.on('cameraStatus', (err: BusinessError, cameraStatusInfo: camera.CameraStatusInfo) => { + console.info(`camera : ${cameraStatusInfo.camera.cameraId}`); + console.info(`status: ${cameraStatusInfo.status}`); +}); // 获取相机列表 -let cameraArray = cameraManager.getSupportedCameras(); +let cameraArray: Array = cameraManager.getSupportedCameras(); if (cameraArray.length <= 0) { - console.error("cameraManager.getSupportedCameras error") - return; + console.error("cameraManager.getSupportedCameras error"); + return; } for (let index = 0; index < cameraArray.length; index++) { - console.info('cameraId : ' + cameraArray[index].cameraId); // 获取相机ID - console.info('cameraPosition : ' + cameraArray[index].cameraPosition); // 获取相机位置 - console.info('cameraType : ' + cameraArray[index].cameraType); // 获取相机类型 - console.info('connectionType : ' + cameraArray[index].connectionType); // 获取相机连接类型 + console.info('cameraId : ' + cameraArray[index].cameraId); // 获取相机ID + console.info('cameraPosition : ' + cameraArray[index].cameraPosition); // 获取相机位置 + console.info('cameraType : ' + cameraArray[index].cameraType); // 获取相机类型 + console.info('connectionType : ' + cameraArray[index].connectionType); // 获取相机连接类型 } // 创建相机输入流 -let cameraInput +let cameraInput: camera.CameraInput; try { - cameraInput = cameraManager.createCameraInput(cameraArray[0]); + cameraInput = cameraManager.createCameraInput(cameraArray[0]); } catch (error) { - console.error('Failed to createCameraInput errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to createCameraInput errorCode = ' + err.code); } // 监听cameraInput错误信息 -let cameraDevice = cameraArray[0]; -cameraInput.on('error', cameraDevice, (error) => { - console.info(`Camera input error code: ${error.code}`); +let cameraDevice: camera.CameraDevice = cameraArray[0]; +cameraInput.on('error', cameraDevice, (error: BusinessError) => { + console.info(`Camera input error code: ${error.code}`); }) // 打开相机 await cameraInput.open(); // 获取相机设备支持的输出流能力 -let cameraOutputCap = cameraManager.getSupportedOutputCapability(cameraArray[0]); +let cameraOutputCap: camera.CameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraArray[0]); if (!cameraOutputCap) { - console.error("cameraManager.getSupportedOutputCapability error") - return; + console.error("cameraManager.getSupportedOutputCapability error"); + return; } console.info("outputCapability: " + JSON.stringify(cameraOutputCap)); -let previewProfilesArray = cameraOutputCap.previewProfiles; +let previewProfilesArray: Array = cameraOutputCap.previewProfiles; if (!previewProfilesArray) { - console.error("createOutput previewProfilesArray == null || undefined") + console.error("createOutput previewProfilesArray == null || undefined"); } -let photoProfilesArray = cameraOutputCap.photoProfiles; +let photoProfilesArray: Array = cameraOutputCap.photoProfiles; if (!photoProfilesArray) { - console.error("createOutput photoProfilesArray == null || undefined") + console.error("createOutput photoProfilesArray == null || undefined"); } // 创建预览输出流,其中参数 surfaceId 参考上文 XComponent 组件,预览流为XComponent组件提供的surface -let previewOutput +let previewOutput: camera.PreviewOutput; try { - previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId) + previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId); } catch (error) { - console.error("Failed to create the PreviewOutput instance.") + let err = error as BusinessError; + console.error(`Failed to create the PreviewOutput instance. error code: ${err.code}`); } // 监听预览输出错误信息 -previewOutput.on('error', (error) => { - console.info(`Preview output error code: ${error.code}`); -}) +previewOutput.on('error', (error: BusinessError) => { + console.info(`Preview output error code: ${error.code}`); +}); // 创建ImageReceiver对象,并设置照片参数:分辨率大小是根据前面 photoProfilesArray 获取的当前设备所支持的拍照分辨率大小去设置 -let imageReceiver = await image.createImageReceiver(1920, 1080, 4, 8) +let imageReceiver: image.ImageReceiver = image.createImageReceiver(1920, 1080, 4, 8); // 获取照片显示SurfaceId -let photoSurfaceId = await imageReceiver.getReceivingSurfaceId() +let photoSurfaceId: string = await imageReceiver.getReceivingSurfaceId(); // 创建拍照输出流 -let photoOutput +let photoOutput: camera.PhotoOutput; try { - photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId) + photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId); } catch (error) { - console.error('Failed to createPhotoOutput errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to createPhotoOutput errorCode = ' + err.code); } //创建会话 -let captureSession +let captureSession: camera.CaptureSession; try { - captureSession = cameraManager.createCaptureSession() + captureSession = cameraManager.createCaptureSession(); } catch (error) { - console.error('Failed to create the CaptureSession instance. errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to create the CaptureSession instance. errorCode = ' + err.code); } // 监听session错误信息 -captureSession.on('error', (error) => { - console.info(`Capture session error code: ${error.code}`); -}) +captureSession.on('error', (error: BusinessError) => { + console.info(`Capture session error code: ${error.code}`); +}); // 开始配置会话 try { - captureSession.beginConfig() + captureSession.beginConfig(); } catch (error) { - console.error('Failed to beginConfig. errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to beginConfig. errorCode = ' + err.code); } // 向会话中添加相机输入流 try { - captureSession.addInput(cameraInput) + captureSession.addInput(cameraInput); } catch (error) { - console.error('Failed to addInput. errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to addInput. errorCode = ' + err.code); } // 向会话中添加预览输出流 try { - captureSession.addOutput(previewOutput) + captureSession.addOutput(previewOutput); } catch (error) { - console.error('Failed to addOutput(previewOutput). errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to addOutput(previewOutput). errorCode = ' + err.code); } // 向会话中添加拍照输出流 try { - captureSession.addOutput(photoOutput) + captureSession.addOutput(photoOutput); } catch (error) { - console.error('Failed to addOutput(photoOutput). errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to addOutput(photoOutput). errorCode = ' + err.code); } // 提交会话配置 -await captureSession.commitConfig() +await captureSession.commitConfig(); // 启动会话 await captureSession.start().then(() => { - console.info('Promise returned to indicate the session start success.'); -}) + console.info('Promise returned to indicate the session start success.'); +}); // 判断设备是否支持闪光灯 -let flashStatus +let flashStatus: boolean; try { - flashStatus = captureSession.hasFlash() + flashStatus = captureSession.hasFlash(); } catch (error) { - console.error('Failed to hasFlash. errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to hasFlash. errorCode = ' + err.code); } console.info('Promise returned with the flash light support status:' + flashStatus); if (flashStatus) { - // 判断是否支持自动闪光灯模式 - let flashModeStatus + // 判断是否支持自动闪光灯模式 + let flashModeStatus: boolean; + try { + let status: boolean = captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO); + flashModeStatus = status; + } catch (error) { + let err = error as BusinessError; + console.error('Failed to check whether the flash mode is supported. errorCode = ' + err.code); + } + if(flashModeStatus) { + // 设置自动闪光灯模式 try { - let status = captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO) - flashModeStatus = status + captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO); } catch (error) { - console.error('Failed to check whether the flash mode is supported. errorCode = ' + error.code); - } - if(flashModeStatus) { - // 设置自动闪光灯模式 - try { - captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO) - } catch (error) { - console.error('Failed to set the flash mode. errorCode = ' + error.code); - } + let err = error as BusinessError; + console.error('Failed to set the flash mode. errorCode = ' + err.code); } + } } // 判断是否支持连续自动变焦模式 -let focusModeStatus +let focusModeStatus: boolean; try { - let status = captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO) - focusModeStatus = status + let status: boolean = captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO); + focusModeStatus = status; } catch (error) { - console.error('Failed to check whether the focus mode is supported. errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to check whether the focus mode is supported. errorCode = ' + err.code); } if (focusModeStatus) { - // 设置连续自动变焦模式 - try { - captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO) - } catch (error) { - console.error('Failed to set the focus mode. errorCode = ' + error.code); - } + // 设置连续自动变焦模式 + try { + captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO); + } catch (error) { + let err = error as BusinessError; + console.error('Failed to set the focus mode. errorCode = ' + err.code); + } } // 获取相机支持的可变焦距比范围 -let zoomRatioRange +let zoomRatioRange: Array; try { - zoomRatioRange = captureSession.getZoomRatioRange() + zoomRatioRange = captureSession.getZoomRatioRange(); } catch (error) { - console.error('Failed to get the zoom ratio range. errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to get the zoom ratio range. errorCode = ' + err.code); } // 设置可变焦距比 try { - captureSession.setZoomRatio(zoomRatioRange[0]) + captureSession.setZoomRatio(zoomRatioRange[0]); } catch (error) { - console.error('Failed to set the zoom ratio value. errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to set the zoom ratio value. errorCode = ' + err.code); } -let settings = { - quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // 设置图片质量高 - rotation: camera.ImageRotation.ROTATION_0 // 设置图片旋转角度0 +let settings: camera.PhotoCaptureSetting = { + quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // 设置图片质量高 + rotation: camera.ImageRotation.ROTATION_0 // 设置图片旋转角度0 } // 使用当前拍照设置进行拍照 -photoOutput.capture(settings, async (err) => { - if (err) { - console.error('Failed to capture the photo ${err.message}'); - return; - } - console.info('Callback invoked to indicate the photo capture request success.'); +photoOutput.capture(settings, async (err: BusinessError) => { + if (err) { + console.error('Failed to capture the photo ${err.message}'); + return; + } + console.info('Callback invoked to indicate the photo capture request success.'); }); // 停止当前会话 -captureSession.stop() +captureSession.stop(); // 释放相机输入流 -cameraInput.close() +cameraInput.close(); // 释放预览输出流 -previewOutput.release() +previewOutput.release(); // 释放拍照输出流 -photoOutput.release() +photoOutput.release(); // 释放会话 -captureSession.release() +captureSession.release(); // 会话置空 -captureSession = null +captureSession = null; ``` diff --git a/zh-cn/application-dev/media/camera-shooting.md b/zh-cn/application-dev/media/camera-shooting.md index 9f16f3210151e9d9e92fb64fc16a68a6c3c5d538..210264a6f3c8f91af540a86d5394eabfd0b9e908 100644 --- a/zh-cn/application-dev/media/camera-shooting.md +++ b/zh-cn/application-dev/media/camera-shooting.md @@ -17,16 +17,16 @@ 通过image的createImageReceiver方法创建ImageReceiver实例,再通过实例的getReceivingSurfaceId方法获取SurfaceId,与拍照输出流相关联,获取拍照输出流的数据。 ```ts - function getImageReceiverSurfaceId() { - let receiver = image.createImageReceiver(640, 480, 4, 8); - console.info('before ImageReceiver check'); - if (receiver !== undefined) { - console.info('ImageReceiver is ok'); - let photoSurfaceId = receiver.getReceivingSurfaceId(); - console.info('ImageReceived id: ' + JSON.stringify(photoSurfaceId)); - } else { - console.info('ImageReceiver is not ok'); - } + async function getImageReceiverSurfaceId() { + let receiver: image.ImageReceiver = image.createImageReceiver(640, 480, 4, 8); + console.info('before ImageReceiver check'); + if (receiver !== undefined) { + console.info('ImageReceiver is ok'); + let photoSurfaceId: string = await receiver.getReceivingSurfaceId(); + console.info('ImageReceived id: ' + JSON.stringify(photoSurfaceId)); + } else { + console.info('ImageReceiver is not ok'); + } } ``` @@ -35,15 +35,16 @@ 通过CameraOutputCapability类中的photoProfiles()方法,可获取当前设备支持的拍照输出流,通过createPhotoOutput()方法传入支持的某一个输出流及步骤一获取的SurfaceId创建拍照输出流。 ```ts - let photoProfilesArray = cameraOutputCapability.photoProfiles; + let photoProfilesArray: Array = cameraOutputCapability.photoProfiles; if (!photoProfilesArray) { - console.error("createOutput photoProfilesArray == null || undefined"); + console.error("createOutput photoProfilesArray == null || undefined"); } - let photoOutput; + let photoOutput: camera.PhotoOutput; try { - photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId); + photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId); } catch (error) { - console.error('Failed to createPhotoOutput errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to createPhotoOutput errorCode = ' + err.code); } ``` @@ -53,59 +54,66 @@ ```ts // 判断设备是否支持闪光灯 - let flashStatus; + let flashStatus: boolean; try { - flashStatus = captureSession.hasFlash(); + flashStatus = captureSession.hasFlash(); } catch (error) { - console.error('Failed to hasFlash. errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to hasFlash. errorCode = ' + err.code); } console.info('Promise returned with the flash light support status:' + flashStatus); if (flashStatus) { - // 判断是否支持自动闪光灯模式 - let flashModeStatus; + // 判断是否支持自动闪光灯模式 + let flashModeStatus: boolean; + try { + let status: boolean = captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO); + flashModeStatus = status; + } catch (error) { + let err = error as BusinessError; + console.error('Failed to check whether the flash mode is supported. errorCode = ' + err.code); + } + if(flashModeStatus) { + // 设置自动闪光灯模式 try { - let status = captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO); - flashModeStatus = status; + captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO); } catch (error) { - console.error('Failed to check whether the flash mode is supported. errorCode = ' + error.code); - } - if(flashModeStatus) { - // 设置自动闪光灯模式 - try { - captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO); - } catch (error) { - console.error('Failed to set the flash mode. errorCode = ' + error.code); - } + let err = error as BusinessError; + console.error('Failed to set the flash mode. errorCode = ' + err.code); } + } } // 判断是否支持连续自动变焦模式 - let focusModeStatus; + let focusModeStatus: boolean; try { - let status = captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO); - focusModeStatus = status; + let status: boolean = captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO); + focusModeStatus = status; } catch (error) { - console.error('Failed to check whether the focus mode is supported. errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to check whether the focus mode is supported. errorCode = ' + err.code); } if (focusModeStatus) { - // 设置连续自动变焦模式 - try { - captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO); - } catch (error) { - console.error('Failed to set the focus mode. errorCode = ' + error.code); - } + // 设置连续自动变焦模式 + try { + captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO); + } catch (error) { + let err = error as BusinessError; + console.error('Failed to set the focus mode. errorCode = ' + err.code); + } } // 获取相机支持的可变焦距比范围 - let zoomRatioRange; + let zoomRatioRange: Array; try { - zoomRatioRange = captureSession.getZoomRatioRange(); + zoomRatioRange = captureSession.getZoomRatioRange(); } catch (error) { - console.error('Failed to get the zoom ratio range. errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to get the zoom ratio range. errorCode = ' + err.code); } // 设置可变焦距比 try { - captureSession.setZoomRatio(zoomRatioRange[0]); + captureSession.setZoomRatio(zoomRatioRange[0]); } catch (error) { - console.error('Failed to set the zoom ratio value. errorCode = ' + error.code); + let err = error as BusinessError; + console.error('Failed to set the zoom ratio value. errorCode = ' + err.code); } ``` @@ -114,18 +122,18 @@ 通过photoOutput类的capture()方法,执行拍照任务。该方法有两个参数,第一个参数为拍照设置参数的setting,setting中可以设置照片的质量和旋转角度,第二参数为回调函数。 ```ts - let settings = { - quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // 设置图片质量高 - rotation: camera.ImageRotation.ROTATION_0, // 设置图片旋转角度0 - location: captureLocation, // 设置图片地理位置 - mirror: false // 设置镜像使能开关(默认关) + let settings: camera.PhotoCaptureSetting = { + quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // 设置图片质量高 + rotation: camera.ImageRotation.ROTATION_0, // 设置图片旋转角度0 + location: captureLocation, // 设置图片地理位置 + mirror: false // 设置镜像使能开关(默认关) }; - photoOutput.capture(settings, async (err) => { - if (err) { - console.error('Failed to capture the photo ${err.message}'); - return; - } - console.info('Callback invoked to indicate the photo capture request success.'); + photoOutput.capture(settings, async (err: BusinessError) => { + if (err) { + console.error('Failed to capture the photo ${err.message}'); + return; + } + console.info('Callback invoked to indicate the photo capture request success.'); }); ``` @@ -136,24 +144,24 @@ - 通过注册固定的captureStart回调函数获取监听拍照开始结果,photoOutput创建成功时即可监听,拍照第一次曝光时触发,该事件返回此次拍照的captureId。 ```ts - photoOutput.on('captureStart', (err, captureId) => { - console.info(`photo capture stated, captureId : ${captureId}`); - }) + photoOutput.on('captureStart', (err: BusinessError, captureId: number) => { + console.info(`photo capture stated, captureId : ${captureId}`); + }); ``` - 通过注册固定的captureEnd回调函数获取监听拍照结束结果,photoOutput创建成功时即可监听,该事件返回结果为拍照完全结束后的相关信息[CaptureEndInfo](../reference/apis/js-apis-camera.md#captureendinfo)。 ```ts - photoOutput.on('captureEnd', (err, captureEndInfo) => { - console.info(`photo capture end, captureId : ${captureEndInfo.captureId}`); - console.info(`frameCount : ${captureEndInfo.frameCount}`); - }) + photoOutput.on('captureEnd', (err: BusinessError, captureEndInfo: camera.CaptureEndInfo) => { + console.info(`photo capture end, captureId : ${captureEndInfo.captureId}`); + console.info(`frameCount : ${captureEndInfo.frameCount}`); + }); ``` - 通过注册固定的error回调函数获取监听拍照输出流的错误结果。callback返回拍照输出接口使用错误时的对应错误码,错误码类型参见[CameraErrorCode](../reference/apis/js-apis-camera.md#cameraerrorcode)。 ```ts - photoOutput.on('error', (error) => { - console.info(`Photo output error code: ${error.code}`); - }) + photoOutput.on('error', (error: BusinessError) => { + console.info(`Photo output error code: ${error.code}`); + }); ``` diff --git a/zh-cn/application-dev/napi/native-buffer-guidelines.md b/zh-cn/application-dev/napi/native-buffer-guidelines.md index 63c7f769a6b2c70ac6ad7b3d32fde0f6c5019d0d..59309b082a1f4781240f08eeb21e84ee973bbfd3 100644 --- a/zh-cn/application-dev/napi/native-buffer-guidelines.md +++ b/zh-cn/application-dev/napi/native-buffer-guidelines.md @@ -39,6 +39,8 @@ libnative_buffer.so 1. **创建OH_NativeBuffer实例**。 ```c++ + #include + OH_NativeBuffer_Config config { .width = 0x100, .height = 0x100, @@ -69,8 +71,8 @@ libnative_buffer.so 3. **获取内存的属性信息**。 ```c++ // 获取OH_NativeBuffer的属性 - OH_NativeBuffer_Config config = {}; - OH_NativeBuffer_GetConfig(buffer, &config); + OH_NativeBuffer_Config config2 = {}; + OH_NativeBuffer_GetConfig(buffer, &config2); // 获取OH_NativeBuffer的序列号 uint32_t hwBufferID = OH_NativeBuffer_GetSeqNum(buffer); ``` diff --git a/zh-cn/application-dev/napi/native-image-guidelines.md b/zh-cn/application-dev/napi/native-image-guidelines.md index a8d1d01f68ed2dd5cfee99922c34bde977e7d8e2..c9608b8543235f62099288126d6488427e6135e2 100644 --- a/zh-cn/application-dev/napi/native-image-guidelines.md +++ b/zh-cn/application-dev/napi/native-image-guidelines.md @@ -51,8 +51,11 @@ libnative_buffer.so 这里提供一份初始化EGL环境的代码示例 ```c++ + #include + #include #include #include + using GetPlatformDisplayExt = PFNEGLGETPLATFORMDISPLAYEXTPROC; constexpr const char* EGL_EXT_PLATFORM_WAYLAND = "EGL_EXT_platform_wayland"; constexpr const char* EGL_KHR_PLATFORM_WAYLAND = "EGL_KHR_platform_wayland"; @@ -167,7 +170,15 @@ libnative_buffer.so OHNativeWindow* nativeWindow = OH_NativeImage_AcquireNativeWindow(image); ``` -4. **将生产的内容写入NativeWindowBuffer**。 +4. **设置NativeWindow的宽高**。 + ```c++ + int code = SET_BUFFER_GEOMETRY; + int32_t width = 800; + int32_t height = 600; + int32_t ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, code, width, height); + ``` + +5. **将生产的内容写入NativeWindowBuffer**。 1. 从NativeWindow中获取NativeWindowBuffer ```c++ OHNativeWindowBuffer* buffer = nullptr; @@ -176,38 +187,46 @@ libnative_buffer.so OH_NativeWindow_NativeWindowRequestBuffer(nativeWindow, &buffer, &fenceFd); BufferHandle *handle = OH_NativeWindow_GetBufferHandleFromNative(buffer); - int code = SET_BUFFER_GEOMETRY; - int32_t width = 0x100; - int32_t height = 0x100; - ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, code, width, height); ``` - 3. 将生产的内容写入NativeWindowBuffer + 2. 将生产的内容写入NativeWindowBuffer ```c++ + #include + + // 使用系统mmap接口拿到bufferHandle的内存虚拟地址 + void* mappedAddr = mmap(handle->virAddr, handle->size, PROT_READ | PROT_WRITE, MAP_SHARED, handle->fd, 0); + if (mappedAddr == MAP_FAILED) { + // mmap failed + } static uint32_t value = 0x00; value++; - uint32_t *pixel = static_cast(handle->virAddr); + uint32_t *pixel = static_cast(mappedAddr); for (uint32_t x = 0; x < width; x++) { for (uint32_t y = 0; y < height; y++) { *pixel++ = value; } } + // 内存使用完记得去掉内存映射 + int result = munmap(mappedAddr, handle->size); + if (result == -1) { + // munmap failed + } ``` - 4. 将NativeWindowBuffer提交到NativeWindow + 3. 将NativeWindowBuffer提交到NativeWindow ```c++ // 设置刷新区域,如果Region中的Rect为nullptr,或者rectNumber为0,则认为NativeWindowBuffer全部有内容更改。 Region region{nullptr, 0}; // 通过OH_NativeWindow_NativeWindowFlushBuffer 提交给消费者使用,例如:显示在屏幕上。 OH_NativeWindow_NativeWindowFlushBuffer(nativeWindow, buffer, fenceFd, region); ``` - 5. 用完需要销毁NativeWindow + 4. 用完需要销毁NativeWindow ```c++ OH_NativeWindow_DestroyNativeWindow(nativeWindow); ``` -5. **更新内容到OpenGL纹理**。 +6. **更新内容到OpenGL纹理**。 ```c++ // 更新内容到OpenGL纹理。 - int32_t ret = OH_NativeImage_UpdateSurfaceImage(image); + ret = OH_NativeImage_UpdateSurfaceImage(image); if (ret != 0) { std::cout << "OH_NativeImage_UpdateSurfaceImage failed" << std::endl; } @@ -220,7 +239,7 @@ libnative_buffer.so } ``` -6. **解绑OpenGL纹理,绑定到新的外部纹理上**。 +7. **解绑OpenGL纹理,绑定到新的外部纹理上**。 ```c++ // 将OH_NativeImage实例从当前OpenGL ES上下文分离 ret = OH_NativeImage_DetachContext(image); @@ -233,7 +252,7 @@ libnative_buffer.so ret = OH_NativeImage_AttachContext(image, textureId2); ``` -7. **OH_NativeImage实例使用完需要销毁掉**。 +8. **OH_NativeImage实例使用完需要销毁掉**。 ```c++ // 销毁OH_NativeImage实例 OH_NativeImage_Destroy(&image); diff --git a/zh-cn/application-dev/napi/native-vsync-guidelines.md b/zh-cn/application-dev/napi/native-vsync-guidelines.md index 0261621db13cf1e36772e7ef2bb1732cfba346a0..9e0c68bd95332241dba2dec9d94552b6f216dbcb 100644 --- a/zh-cn/application-dev/napi/native-vsync-guidelines.md +++ b/zh-cn/application-dev/napi/native-vsync-guidelines.md @@ -33,6 +33,8 @@ libnative_vsync.so 1. **首先需要准备一个VSync回调函数** ```c++ + #include + static bool flag = false; static void OnVSync(long long timestamp, void* data) { @@ -49,6 +51,9 @@ libnative_vsync.so 3. **通过OH_NativeVsync实例设置VSync回调函数**。 ```c++ + #include + #include + OH_NativeVSync_RequestFrame(nativeVSync, callback, nullptr); while (!flag) { // 判断flag值,上面的VSync回调函数被执行后才会跳出while循环,表示已经接收到VSync信号 std::cout << "wait for vsync!\n"; diff --git a/zh-cn/application-dev/napi/native-window-guidelines.md b/zh-cn/application-dev/napi/native-window-guidelines.md index 4e191da6e2e5a8256c338d489d8efb906df0cb6f..acdfedde2aea97e7e7c95372ff2e295696ec8323 100644 --- a/zh-cn/application-dev/napi/native-window-guidelines.md +++ b/zh-cn/application-dev/napi/native-window-guidelines.md @@ -53,6 +53,10 @@ libnative_window.so OH_NativeXComponent *nativeXComponent = nullptr; // 通过napi_unwrap接口,解析出NativeXComponent的实例指针 napi_unwrap(env, exportInstance, reinterpret_cast(&nativeXComponent)); + // 获取XComponentId + char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {}; + uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1; + OH_NativeXComponent_GetXComponentId(nativeXComponent, idStr, &idSize); ``` 3. 定义 OH_NativeXComponent_Callback。 ```c++ @@ -104,10 +108,6 @@ libnative_window.so int32_t height = 0x100; // 这里的nativeWindow是从上一步骤中的回调函数中获得的 int32_t ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, code, width, height); - // 设置 OHNativeWindowBuffer 的步长 - code = SET_STRIDE; - int32_t stride = 0x8; - ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, code, stride); ``` 3. **从图形队列申请OHNativeWindowBuffer**。 diff --git a/zh-cn/application-dev/napi/vulkan-guidelines.md b/zh-cn/application-dev/napi/vulkan-guidelines.md index f0bf36a0225106d05611f4526c7c2031d7fcf220..bc14fbe7a73ef93eb52de1795bdc6f0d0837b511 100644 --- a/zh-cn/application-dev/napi/vulkan-guidelines.md +++ b/zh-cn/application-dev/napi/vulkan-guidelines.md @@ -18,6 +18,11 @@ Vulkan是一套用来做2D和3D渲染的图形应用程序接口,其中创建V 以下步骤说明了如何在OpenHarmony平台创建一个VkSurfaceKHR对象。 +首先,使用OpenHarmony平台扩展的接口,需要定义一个宏`VK_USE_PLATFORM_OHOS`,我们在CMakeLists.txt定义这个宏。 +```txt +ADD_DEFINITIONS(-DVK_USE_PLATFORM_OHOS=1) +``` + **添加动态链接库** CMakeLists.txt中添加以下lib。 @@ -80,7 +85,6 @@ libvulkan.so OHNativeWindow* nativeWindow = static_cast(window); } - EXTERN_C_START static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor desc[] = { @@ -88,18 +92,20 @@ libvulkan.so }; napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); - // 声明一个XComponent的Callback - OH_NativeXComponent_Callback callback; - // 注册OnSurfaceCreated回调函数 - callback.OnSurfaceCreated = OnSurfaceCreatedCB; - - char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {}; - uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1; napi_value exportInstance = nullptr; OH_NativeXComponent *nativeXComponent = nullptr; // 获取nativeXComponent napi_get_named_property(env, exports, OH_NATIVE_XCOMPONENT_OBJ, &exportInstance); napi_unwrap(env, exportInstance, reinterpret_cast(&nativeXComponent)); + // 获取XComponentId + char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {}; + uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1; + OH_NativeXComponent_GetXComponentId(nativeXComponent, idStr, &idSize); + + // 声明一个XComponent的Callback + OH_NativeXComponent_Callback callback; + // 注册OnSurfaceCreated回调函数 + callback.OnSurfaceCreated = OnSurfaceCreatedCB; // 将callback注册给nativeXComponent OH_NativeXComponent_RegisterCallback(nativeXComponent, &callback); @@ -115,7 +121,7 @@ libvulkan.so surfaceCreateInfo.window = nativeWindow; // 这里的nativeWindow就是从上一步骤OnSurfaceCreatedCB回调函数中拿到的 int err = vkCreateSurfaceOHOS(instance, &surfaceCreateInfo, NULL, &surface); if (err != VK_SUCCESS) { - std::cout << "Could not create surface!" << std::endl; + // Create Surface Failed. } ``` 后续更多vulkan的用法请参考[Vulkan官方网站](https://www.vulkan.org/)。 diff --git a/zh-cn/application-dev/quick-start/arkts-appstorage.md b/zh-cn/application-dev/quick-start/arkts-appstorage.md index 778dba37b9b36aed2d4e7d315e618f0610930336..7082d7743d9f523f036ed86e6f3cdb2c17b688b4 100644 --- a/zh-cn/application-dev/quick-start/arkts-appstorage.md +++ b/zh-cn/application-dev/quick-start/arkts-appstorage.md @@ -142,13 +142,13 @@ AppStorage是单例,它的所有API都是静态的,使用方法类似于中L ```ts -AppStorage.SetOrCreate('PropA', 47); +AppStorage.setOrCreate('PropA', 47); let storage: LocalStorage = new LocalStorage({ 'PropA': 17 }); -let propA: number = AppStorage.Get('PropA') // propA in AppStorage == 47, propA in LocalStorage == 17 -var link1: SubscribedAbstractProperty = AppStorage.Link('PropA'); // link1.get() == 47 -var link2: SubscribedAbstractProperty = AppStorage.Link('PropA'); // link2.get() == 47 -var prop: SubscribedAbstractProperty = AppStorage.Prop('PropA'); // prop.get() = 47 +let propA: number = AppStorage.get('PropA') // propA in AppStorage == 47, propA in LocalStorage == 17 +var link1: SubscribedAbstractProperty = AppStorage.link('PropA'); // link1.get() == 47 +var link2: SubscribedAbstractProperty = AppStorage.link('PropA'); // link2.get() == 47 +var prop: SubscribedAbstractProperty = AppStorage.prop('PropA'); // prop.get() = 47 link1.set(48); // two-way sync: link1.get() == link2.get() == prop.get() == 48 prop.set(1); // one-way sync: prop.get()=1; but link1.get() == link2.get() == 48 @@ -158,7 +158,7 @@ storage.get('PropA') // == 17 storage.set('PropA', 101); storage.get('PropA') // == 101 -AppStorage.Get('PropA') // == 49 +AppStorage.get('PropA') // == 49 link1.get() // == 49 link2.get() // == 49 prop.get() // == 49 @@ -171,7 +171,7 @@ prop.get() // == 49 ```ts -AppStorage.SetOrCreate('PropA', 47); +AppStorage.setOrCreate('PropA', 47); let storage = new LocalStorage({ 'PropA': 48 }); @Entry(storage) @@ -372,9 +372,9 @@ export struct TapImage { AppStorage与[PersistentStorage](arkts-persiststorage.md)以及[Environment](arkts-environment.md)配合使用时,需要注意以下几点: -- 在AppStorage中创建属性后,调用PersistentStorage.PersistProp()接口时,会使用在AppStorage中已经存在的值,并覆盖PersistentStorage中的同名属性,所以建议要使用相反的调用顺序,反例可见[在PersistentStorage之前访问AppStorage中的属性](arkts-persiststorage.md#在persistentstorage之前访问appstorage中的属性); +- 在AppStorage中创建属性后,调用PersistentStorage.persistProp()接口时,会使用在AppStorage中已经存在的值,并覆盖PersistentStorage中的同名属性,所以建议要使用相反的调用顺序,反例可见[在PersistentStorage之前访问AppStorage中的属性](arkts-persiststorage.md#在persistentstorage之前访问appstorage中的属性); -- 如果在AppStorage中已经创建属性后,再调用Environment.EnvProp()创建同名的属性,会调用失败。因为AppStorage已经有同名属性,Environment环境变量不会再写入AppStorage中,所以建议AppStorage中属性不要使用Environment预置环境变量名。 +- 如果在AppStorage中已经创建属性后,再调用Environment.envProp()创建同名的属性,会调用失败。因为AppStorage已经有同名属性,Environment环境变量不会再写入AppStorage中,所以建议AppStorage中属性不要使用Environment预置环境变量名。 - 状态装饰器装饰的变量,改变会引起UI的渲染更新,如果改变的变量不是用于UI更新,只是用于消息传递,推荐使用 emitter方式。例子可见[以持久化方式订阅某个事件并接收事件回调](#以持久化方式订阅某个事件并接收事件回调)。 diff --git a/zh-cn/application-dev/quick-start/arkts-environment.md b/zh-cn/application-dev/quick-start/arkts-environment.md index feba33c01e6e9c58303e65153de87ead8e3f16fe..0e22f582e453ee7d0b0ee998aff383e22c873440 100644 --- a/zh-cn/application-dev/quick-start/arkts-environment.md +++ b/zh-cn/application-dev/quick-start/arkts-environment.md @@ -12,11 +12,11 @@ Environment是ArkUI框架在应用程序启动时创建的单例对象。它为A ### 从UI中访问Environment参数 -- 使用Environment.EnvProp将设备运行的环境变量存入AppStorage中: +- 使用Environment.envProp将设备运行的环境变量存入AppStorage中: ```ts // 将设备的语言code存入AppStorage,默认值为en - Environment.EnvProp('languageCode', 'en'); + Environment.envProp('languageCode', 'en'); ``` - 可以使用\@StorageProp链接到Component中。 @@ -34,8 +34,8 @@ Environment是ArkUI框架在应用程序启动时创建的单例对象。它为A ```ts // 将设备languageCode存入AppStorage中 -Environment.EnvProp('languageCode', 'en'); -let enable = AppStorage.Get('languageCode'); +Environment.envProp('languageCode', 'en'); +let enable = AppStorage.get('languageCode'); @Entry @Component @@ -59,9 +59,9 @@ struct Index { ```ts // 使用Environment.EnvProp将设备运行languageCode存入AppStorage中; -Environment.EnvProp('languageCode', 'en'); +Environment.envProp('languageCode', 'en'); // 从AppStorage获取单向绑定的languageCode的变量 -const lang: SubscribedAbstractProperty = AppStorage.Prop('languageCode'); +const lang: SubscribedAbstractProperty = AppStorage.prop('languageCode'); if (lang.get() === 'zh') { console.info('你好'); @@ -89,7 +89,7 @@ export default class EntryAbility extends UIAbility { window.then(window => { let uicontext = window.getUIContext() uicontext.runScopedTask(() => { - Environment.EnvProp('languageCode', 'en'); + Environment.envProp('languageCode', 'en'); }) }) } diff --git a/zh-cn/application-dev/quick-start/arkts-localstorage.md b/zh-cn/application-dev/quick-start/arkts-localstorage.md index 668f493433bce17622efe8b92e2e6cae93e0cdae..5d2fa0db9f43a5be9b2470dfdc552726218d54b8 100644 --- a/zh-cn/application-dev/quick-start/arkts-localstorage.md +++ b/zh-cn/application-dev/quick-start/arkts-localstorage.md @@ -196,12 +196,12 @@ link1.set(49); // two-way sync: link1.get() == link2.get() == prop.get() == 49 @Component struct Child { - // @LocalStorageLink变量装饰器与LocalStorage中的'ProA'属性建立双向绑定 + // @LocalStorageLink变量装饰器与LocalStorage中的'PropA'属性建立双向绑定 @LocalStorageLink('PropA') storLink2: number = 1; build() { Button(`Child from LocalStorage ${this.storLink2}`) - // 更改将同步至LocalStorage中的'ProA'以及Parent.storLink1 + // 更改将同步至LocalStorage中的'PropA'以及Parent.storLink1 .onClick(() => this.storLink2 += 1) } } @@ -209,7 +209,7 @@ link1.set(49); // two-way sync: link1.get() == link2.get() == prop.get() == 49 @Entry(storage) @Component struct CompA { - // @LocalStorageLink变量装饰器与LocalStorage中的'ProA'属性建立双向绑定 + // @LocalStorageLink变量装饰器与LocalStorage中的'PropA'属性建立双向绑定 @LocalStorageLink('PropA') storLink1: number = 1; build() { @@ -239,7 +239,7 @@ link1.set(49); // two-way sync: link1.get() == link2.get() == prop.get() == 49 @Entry(storage) @Component struct CompA { - // @LocalStorageProp变量装饰器与LocalStorage中的'ProA'属性建立单向绑定 + // @LocalStorageProp变量装饰器与LocalStorage中的'PropA'属性建立单向绑定 @LocalStorageProp('PropA') storProp1: number = 1; build() { @@ -254,7 +254,7 @@ link1.set(49); // two-way sync: link1.get() == link2.get() == prop.get() == 49 @Component struct Child { - // @LocalStorageProp变量装饰器与LocalStorage中的'ProA'属性建立单向绑定 + // @LocalStorageProp变量装饰器与LocalStorage中的'PropA'属性建立单向绑定 @LocalStorageProp('PropA') storProp2: number = 2; build() { @@ -275,7 +275,7 @@ link1.set(49); // two-way sync: link1.get() == link2.get() == prop.get() == 49 ```ts // 构造LocalStorage实例 let storage = new LocalStorage({ 'PropA': 47 }); -// 调用link9+接口构造'PropA'的双向同步数据,linkToPropA 是全部变量 +// 调用link9+接口构造'PropA'的双向同步数据,linkToPropA 是全局变量 let linkToPropA = storage.link('PropA'); @Entry(storage) @@ -398,12 +398,12 @@ export default class EntryAbility extends UIAbility { } ``` -在UI页面通过GetShared接口获取在通过loadContent共享的LocalStorage实例。 +在UI页面通过getShared接口获取在通过loadContent共享的LocalStorage实例。 ```ts -// 通过GetShared接口获取stage共享的Storage实例 -let storage = LocalStorage.GetShared() +// 通过getShared接口获取stage共享的Storage实例 +let storage = LocalStorage.getShared() @Entry(storage) @Component diff --git a/zh-cn/application-dev/quick-start/arkts-observed-and-objectlink.md b/zh-cn/application-dev/quick-start/arkts-observed-and-objectlink.md index 7df90501a582c02e796a5eb61a73013dc14335ee..d63149dcb8418d6d5bf6028dcbeb074f1b1ff1fa 100644 --- a/zh-cn/application-dev/quick-start/arkts-observed-and-objectlink.md +++ b/zh-cn/application-dev/quick-start/arkts-observed-and-objectlink.md @@ -35,7 +35,7 @@ | ----------------- | ---------------------------------------- | | 装饰器参数 | 无 | | 同步类型 | 不与父组件中的任何类型同步变量。 | -| 允许装饰的变量类型 | 必须为被\@Observed装饰的class实例,必须指定类型。
不支持简单类型,可以使用[\@Prop](arkts-prop.md)。
\@ObjectLink的属性是可以改变的,但是变量的分配是不允许的,也就是说这个装饰器装饰变量是只读的,不能被改变。 | +| 允许装饰的变量类型 | 必须为被\@Observed装饰的class实例,必须指定类型。
不支持简单类型,可以使用[\@Prop](arkts-prop.md)。
支持继承Date或者Array的class实例,示例见[观察变化](#观察变化)。
\@ObjectLink的属性是可以改变的,但是变量的分配是不允许的,也就是说这个装饰器装饰变量是只读的,不能被改变。 | | 被装饰变量的初始值 | 不允许。 | \@ObjectLink装饰的数据为可读示例。 @@ -75,7 +75,7 @@ this.objLink= ... ## 观察变化和行为表现 -### 观察的变化 +### 观察变化 \@Observed装饰的类,如果其属性为非简单类型,比如class、Object或者数组,也需要被\@Observed装饰,否则将观察不到其属性的变化。 @@ -121,6 +121,67 @@ this.b.a.c = 5 - 如果数据源是数组,则可以观察到数组item的替换,如果数据源是class,可观察到class的属性的变化,示例请参考[对象数组](#对象数组)。 +继承Date的class时,可以观察到Date整体的赋值,同时可通过调用Date的接口`setFullYear`, `setMonth`, `setDate`, `setHours`, `setMinutes`, `setSeconds`, `setMilliseconds`, `setTime`, `setUTCFullYear`, `setUTCMonth`, `setUTCDate`, `setUTCHours`, `setUTCMinutes`, `setUTCSeconds`, `setUTCMilliseconds` 更新Date的属性。 + +```ts +@Observed +class DateClass extends Date { + constructor(args: any) { + super(args) + } +} + +@Observed +class ClassB { + public a: DateClass; + + constructor(a: DateClass) { + this.a = a; + } +} + +@Component +struct ViewA { + label: string = 'date'; + @ObjectLink a: DateClass; + + build() { + Column() { + Button(`child increase the day by 1`) + .onClick(() => { + this.a.setDate(this.a.getDate() + 1); + }) + DatePicker({ + start: new Date('1970-1-1'), + end: new Date('2100-1-1'), + selected: this.a + }) + } + } +} + +@Entry +@Component +struct ViewB { + @State b: ClassB = new ClassB(new DateClass('2023-1-1')); + + build() { + Column() { + ViewA({ label: 'date', a: this.b.a }) + + Button(`parent update the new date`) + .onClick(() => { + this.b.a = new DateClass('2023-07-07'); + }) + Button(`ViewB: this.b = new ClassB(new DateClass('2023-08-20'))`) + .onClick(() => { + this.b = new ClassB(new DateClass('2023-08-20')); + }) + } + } +} +``` + ### 框架行为 diff --git a/zh-cn/application-dev/quick-start/arkts-persiststorage.md b/zh-cn/application-dev/quick-start/arkts-persiststorage.md index c92158b30875d0452ae9311055f7c8dd065916d6..957ea8b7259baadc01169277ec34e1a032295d93 100644 --- a/zh-cn/application-dev/quick-start/arkts-persiststorage.md +++ b/zh-cn/application-dev/quick-start/arkts-persiststorage.md @@ -34,13 +34,13 @@ PersistentStorage和UIContext相关联,需要在[UIContext](../reference/apis/ 1. 初始化PersistentStorage: ```ts - PersistentStorage.PersistProp('aProp', 47); + PersistentStorage.persistProp('aProp', 47); ``` 2. 在AppStorage获取对应属性: ```ts - AppStorage.Get('aProp'); // returns 47 + AppStorage.get('aProp'); // returns 47 ``` 或在组件内部定义: @@ -54,7 +54,7 @@ PersistentStorage和UIContext相关联,需要在[UIContext](../reference/apis/ ```ts -PersistentStorage.PersistProp('aProp', 47); +PersistentStorage.persistProp('aProp', 47); @Entry @Component @@ -78,7 +78,7 @@ struct Index { ``` - 新应用安装后首次启动运行: - 1. 调用PersistProp初始化PersistentStorage,首先查询在PersistentStorage本地文件中是否存在“aProp”,查询结果为不存在,因为应用是第一次安装。 + 1. 调用persistProp初始化PersistentStorage,首先查询在PersistentStorage本地文件中是否存在“aProp”,查询结果为不存在,因为应用是第一次安装。 2. 接着查询属性“aProp”在AppStorage中是否存在,依旧不存在。 3. 在AppStorge中创建名为“aProp”的number类型属性,属性初始值是定义的默认值47。 4. PersistentStorage将属性“aProp”和值47写入磁盘,AppStorage中“aProp”对应的值和其后续的更改将被持久化。 @@ -95,21 +95,21 @@ struct Index { 4. 因为“aProp”对应的属性已经被持久化,所以在AppStorage中“aProp”的改变会触发PersistentStorage,将新的改变写入本地磁盘。 - 后续启动应用: - 1. 执行PersistentStorage.PersistProp('aProp', 47),在首先查询在PersistentStorage本地文件查询“aProp”属性,成功查询到。 + 1. 执行PersistentStorage.persistProp('aProp', 47),在首先查询在PersistentStorage本地文件查询“aProp”属性,成功查询到。 2. 将在PersistentStorage查询到的值写入AppStorage中。 3. 在Index组件里,\@StorageLink绑定的“aProp”为PersistentStorage写入AppStorage中的值,即为上一次退出引用存入的值。 ### 在PersistentStorage之前访问AppStorage中的属性 -该示例为反例。在调用PersistentStorage.PersistProp或者PersistProps之前使用接口访问AppStorage中的属性是错误的,因为这样的调用顺序会丢失上一次应用程序运行中的属性值: +该示例为反例。在调用PersistentStorage.persistProp或者persistProps之前使用接口访问AppStorage中的属性是错误的,因为这样的调用顺序会丢失上一次应用程序运行中的属性值: ```ts -let aProp = AppStorage.SetOrCreate('aProp', 47); -PersistentStorage.PersistProp('aProp', 48); +let aProp = AppStorage.setOrCreate('aProp', 47); +PersistentStorage.persistProp('aProp', 48); ``` -应用在非首次运行时,先执行AppStorage.SetOrCreate('aProp', 47):属性“aProp”在AppStorage中创建,其类型为number,其值设置为指定的默认值47。'aProp'是持久化的属性,所以会被写回PersistentStorage磁盘中,PersistentStorage存储的上次退出应用的值丢失。 +应用在非首次运行时,先执行AppStorage.setOrCreate('aProp', 47):属性“aProp”在AppStorage中创建,其类型为number,其值设置为指定的默认值47。'aProp'是持久化的属性,所以会被写回PersistentStorage磁盘中,PersistentStorage存储的上次退出应用的值丢失。 -PersistentStorage.PersistProp('aProp', 48):在PersistentStorage中查找到“aProp”,找到,值为47。 +PersistentStorage.persistProp('aProp', 48):在PersistentStorage中查找到“aProp”,找到,值为47。 diff --git a/zh-cn/application-dev/quick-start/arkts-prop.md b/zh-cn/application-dev/quick-start/arkts-prop.md index b9c26caecc72796493cb68c3ad44a9bc63b55222..07683420d50e79846e7bc9e7502ad330fec42c02 100644 --- a/zh-cn/application-dev/quick-start/arkts-prop.md +++ b/zh-cn/application-dev/quick-start/arkts-prop.md @@ -188,7 +188,7 @@ struct ParentComponent { ### 父组件\@State到子组件\@Prop简单数据类型同步 -以下示例是\@State到子组件\@Prop简单数据同步,父组件ParentComponent的状态变量countDownStartValue初始化子组件CountDownComponent中\@Prop装饰的count,点击“Try again”,count的修改仅保留在CountDownComponent 不会同步给父组件CountDownComponent。 +以下示例是\@State到子组件\@Prop简单数据同步,父组件ParentComponent的状态变量countDownStartValue初始化子组件CountDownComponent中\@Prop装饰的count,点击“Try again”,count的修改仅保留在CountDownComponent 不会同步给父组件ParentComponent。 ParentComponent的状态变量countDownStartValue的变化将重置CountDownComponent的count。 @@ -400,7 +400,7 @@ struct Library { 在下面的示例中,更改了\@State 修饰的allBooks数组中Book对象上的属性,但点击“Mark read for everyone”无反应。这是因为该属性是第二层的嵌套属性,\@State装饰器只能观察到第一层属性,不会观察到此属性更改,所以框架不会更新ReaderComp。 -``` +```ts let nextId: number = 1; // @Observed @@ -465,7 +465,7 @@ struct Library { 需要使用\@Observed装饰class Book,Book的属性将被观察。 需要注意的是,\@Prop在子组件装饰的状态变量和父组件的数据源是单向同步关系,即ReaderComp中的\@Prop book的修改不会同步给父组件Library。而父组件只会在数值有更新的时候(和上一次状态的对比),才会触发UI的重新渲染。 -``` +```ts @Observed class Book { public id: number; @@ -537,11 +537,12 @@ struct MainProgram { } Row() { - Column() - // customCounter必须从父组件初始化,因为MyComponent的customCounter成员变量缺少本地初始化;此处,customCounter2可以不做初始化。 - MyComponent({ customCounter: this.mainCounter }) - // customCounter2也可以从父组件初始化,父组件初始化的值会覆盖子组件customCounter2的本地初始化的值 - MyComponent({ customCounter: this.mainCounter, customCounter2: this.mainCounter }) + Column() { + // customCounter必须从父组件初始化,因为MyComponent的customCounter成员变量缺少本地初始化;此处,customCounter2可以不做初始化。 + MyComponent({ customCounter: this.mainCounter }) + // customCounter2也可以从父组件初始化,父组件初始化的值会覆盖子组件customCounter2的本地初始化的值 + MyComponent({ customCounter: this.mainCounter, customCounter2: this.mainCounter }) + } } } } diff --git a/zh-cn/application-dev/quick-start/arkts-rendering-control-foreach.md b/zh-cn/application-dev/quick-start/arkts-rendering-control-foreach.md index 3ebc03922feee540683274d519d430ef8771945f..a2fad12f67e9208177af7e7165ef02d9fa6d3d50 100644 --- a/zh-cn/application-dev/quick-start/arkts-rendering-control-foreach.md +++ b/zh-cn/application-dev/quick-start/arkts-rendering-control-foreach.md @@ -43,7 +43,7 @@ ForEach( ``` -## 开发者的建议 +## 开发建议 - 建议开发者不要假设项构造函数的执行顺序。执行顺序可能不能是数组中项的排列顺序。 diff --git a/zh-cn/application-dev/quick-start/arkts-rendering-control-lazyforeach.md b/zh-cn/application-dev/quick-start/arkts-rendering-control-lazyforeach.md index 518b697e53a7864104b483263739314c16f7fa06..a0d63098b12a81cf5f0b32e32f036d257807c635 100644 --- a/zh-cn/application-dev/quick-start/arkts-rendering-control-lazyforeach.md +++ b/zh-cn/application-dev/quick-start/arkts-rendering-control-lazyforeach.md @@ -14,17 +14,17 @@ LazyForEach( keyGenerator?: (item: any) => string // (可选) .键值生成函数 ): void interface IDataSource { - totalCount(): number; // Get total count of data - getData(index: number): any; // Get single data by index - registerDataChangeListener(listener: DataChangeListener): void; // Register listener to listening data changes - unregisterDataChangeListener(listener: DataChangeListener): void; // Unregister listener + totalCount(): number; // 获得数据总数 + getData(index: number): any; // 获取索引值对应的数据 + registerDataChangeListener(listener: DataChangeListener): void; // 注册数据改变的监听器 + unregisterDataChangeListener(listener: DataChangeListener): void; // 注销数据改变的监听器 } interface DataChangeListener { - onDataReloaded(): void; // Called while data reloaded - onDataAdd(index: number): void; // Called while single data added - onDataMove(from: number, to: number): void; // Called while single data moved - onDataDelete(index: number): void; // Called while single data deleted - onDataChange(index: number): void; // Called while single data changed + onDataReloaded(): void; // 重新加载数据时调用 + onDataAdd(index: number): void; // 添加数据时调用 + onDataMove(from: number, to: number): void; // 数据移动起始位置与数据移动目标位置交换时调用 + onDataDelete(index: number): void; // 删除数据时调用 + onDataChange(index: number): void; // 改变数据时调用 } ``` diff --git a/zh-cn/application-dev/quick-start/module-configuration-file.md b/zh-cn/application-dev/quick-start/module-configuration-file.md index 3f1bb37b13b018dbd111d69f4d158808d34bc5f7..dfe5f0dbc6039893cb1817bca52c2a107bfbcdbe 100644 --- a/zh-cn/application-dev/quick-start/module-configuration-file.md +++ b/zh-cn/application-dev/quick-start/module-configuration-file.md @@ -240,7 +240,7 @@ abilities标签描述UIAbility组件的配置信息,标签值为数组类型 | label | 标识当前UIAbility组件对用户显示的名称,标签值配置为该名称的资源索引以支持多语言。 | 字符串 | 该标签可缺省,缺省值为空。
如果UIAbility被配置为MainElement,该标签必须配置。 | | permissions | 标识当前UIAbility组件自定义的权限信息。当其他应用访问该UIAbility时,需要申请相应的权限信息。
一个数组元素为一个权限名称。通常采用反向域名格式(最大255字节),取值为系统预定义的权限。 | 字符串数组 | 该标签可缺省,缺省值为空。 | | [metadata](#metadata标签) | 标识当前UIAbility组件的元信息。 | 对象数组 | 该标签可缺省,缺省值为空。 | -| exported | 标识当前UIAbility组件是否可以被其他应用调用。
- true:表示可以被其他应用调用。
- false:表示不可以被其他应用调用。 | 布尔值 | 该标签可缺省,缺省值为false。 | +| exported | 标识当前UIAbility组件是否可以被其他应用调用。
- true:表示可以被其他应用调用。
- false:表示不可以被其他应用调用,包括无法被aa工具命令拉起应用。 | 布尔值 | 该标签可缺省,缺省值为false。 | | continuable | 标识当前UIAbility组件是否可以[迁移](../application-models/hop-cross-device-migration.md)。
- true:表示可以被迁移。
- false:表示不可以被迁移。 | 布尔值 | 该标签可缺省,缺省值为false。 | | [skills](#skills标签) | 标识当前UIAbility组件或ExtensionAbility组件能够接收的[Want](../application-models/want-overview.md)的特征集,为数组格式。
配置规则:
- 对于Entry类型的HAP,OpenHarmony应用可以配置多个具有入口能力的skills标签(即配置了ohos.want.action.home和entity.system.home)。
- 对于Feature类型的HAP,只有OpenHarmony应用可以配置具有入口能力的skills标签,OpenHarmony服务不允许配置。 | 对象数组 | 该标签可缺省,缺省值为空。 | | backgroundModes | 标识当前UIAbility组件的长时任务集合。指定用于满足特定类型的长时任务。
长时任务类型有如下:
- dataTransfer:通过网络/对端设备进行数据下载、备份、分享、传输等业务。
- audioPlayback:音频输出业务。
- audioRecording:音频输入业务。
- location:定位、导航业务。
- bluetoothInteraction:蓝牙扫描、连接、传输业务(穿戴)。
- multiDeviceConnection:多设备互联业务。
- wifiInteraction:Wi-Fi扫描、连接、传输业务(克隆多屏)。
- voip:音视频电话,VoIP业务。
- taskKeeping:计算业务。 | 字符串数组 | 该标签可缺省,缺省值为空。 | @@ -381,7 +381,7 @@ skills示例: | uri | 标识当前ExtensionAbility组件提供的数据URI,为字符数组类型(最大长度255),用反向域名的格式表示。
**说明:**
该标签在type为dataShare类型的ExtensionAbility时,不可缺省。 | 字符串 | 该标签可缺省,缺省值为空。 | |skills | 标识当前ExtensionAbility组件能够接收的[Want](../application-models/want-overview.md)的特征集,为数组格式。
配置规则:entry包可以配置多个具有入口能力的skills标签(配置了ohos.want.action.home和entity.system.home)的ExtensionAbility,其中第一个配置了skills标签的ExtensionAbility中的label和icon作为OpenHarmony服务或应用的label和icon。
**说明:**
OpenHarmony服务的Feature包不能配置具有入口能力的skills标签。
OpenHarmony应用的Feature包可以配置具有入口能力的skills标签。 | 数组 | 该标签可缺省,缺省值为空。 | | [metadata](#metadata标签) | 标识当前ExtensionAbility组件的元信息。 | 对象 | 该标签可缺省,缺省值为空。 | -| exported | 标识当前ExtensionAbility组件是否可以被其他应用调用,为布尔类型。
- true:表示可以被其他应用调用。
- false:表示不可以被其他应用调用。 | 布尔值 | 该标签可缺省,缺省值为false。 | +| exported | 标识当前ExtensionAbility组件是否可以被其他应用调用,为布尔类型。
- true:表示可以被其他应用调用。
- false:表示不可以被其他应用调用,包括无法被aa工具命令拉起应用。 | 布尔值 | 该标签可缺省,缺省值为false。 | extensionAbilities示例: diff --git a/zh-cn/application-dev/quick-start/module-structure.md b/zh-cn/application-dev/quick-start/module-structure.md index 58e1254a06a0ec69494b52a5a74f1770b772e6dc..8979a1d6a8cf23661ea216843630f2ecd7cde7b6 100644 --- a/zh-cn/application-dev/quick-start/module-structure.md +++ b/zh-cn/application-dev/quick-start/module-structure.md @@ -202,7 +202,7 @@ metadata对象示例: | label | 标识Ability对用户显示的名称。取值是对该名称的资源索引,支持多语言,例:$string:ability_label。如果在该Ability的skills属性中,actions的取值包含 "action.system.home",entities取值中包含"entity.system.home",则该Ability的label将同时作为应用的label。如果存在多个符合条件的Ability,则取位置靠前的Ability的label作为应用的label。
说明: 应用的"icon"和"label"是用户可感知配置项,需要区别于当前所有已有的应用"icon"或"label"(至少有一个不同)。该标签为资源文件中定义的字符串的引用,或以"{}"包括的字符串。该标签最大长度为255个字节。 | 字符串 | 可缺省,缺省值为空。 | | uri | 标识Ability的统一资源标识符。该标签最大长度为255个字节。 | 字符串 | 可缺省,对于data类型的Ability不可缺省。 | | launchType | 标识Ability的启动模式,支持"standard"和"singleton"两种模式:
standard:表示该Ability可以有多实例。该模式适用于大多数应用场景。
singleton:表示该Ability在所有任务栈中仅可以有一个实例。例如,具有全局唯一性的呼叫来电界面即采用"singleton"模式。该标签仅适用于默认设备、平板、智慧屏、车机、智能穿戴。 | 字符串 | 可缺省,缺省值为"singleton"。 | -| visible | 标识Ability是否可以被其他应用调用。
true:可以被其他应用调用。
false:不能被其他应用调用。 | 布尔类型 | 可缺省,缺省值为"false"。 | +| visible | 标识Ability是否可以被其他应用调用。
true:可以被其他应用调用。
false:不能被其他应用调用,包括无法被aa工具命令拉起应用。 | 布尔类型 | 可缺省,缺省值为"false"。 | | permissions | 标识其他应用的Ability调用此Ability时需要申请的权限集合,一个数组元素为一个权限名称。通常采用反向域名格式(最大255字节),取值为系统预定义的权限。 | 字符串数组 | 可缺省,缺省值为空。 | |skills | 标识Ability能够接收的want的特征。 | 对象数组 | 可缺省,缺省值为空。 | | deviceCapability | 标识Ability运行时要求设备具有的能力,采用字符串数组的格式表示。该标签为数组,支持最多配置512个元素,单个元素最大字节长度为64。 | 字符串数组 | 可缺省,缺省值为空。 | diff --git a/zh-cn/application-dev/quick-start/start-overview.md b/zh-cn/application-dev/quick-start/start-overview.md index 94fdb74b5f722c6f40a5d6dccb58b4ee8016e19c..e8181d9a38a1fa75e4992954ae59907658a317b3 100644 --- a/zh-cn/application-dev/quick-start/start-overview.md +++ b/zh-cn/application-dev/quick-start/start-overview.md @@ -35,7 +35,7 @@ OpenHarmony提供了一套UI开发框架,即方舟开发框架(ArkUI框架 FA模型和Stage模型的整体架构和设计思想等更多区别,请见[应用模型解读](../application-models/application-model-description.md)。 -快速入门提供了一个含有两个页面的开发实例,并使用了不同的开发语言或不同的应用模型进行开发,以便开发者理解以上基本概念及应用开发流程。 +快速入门提供了一个含有两个页面的开发实例,并基于Stage模型构建第一个ArkTS应用,以便开发者理解以上基本概念及应用开发流程。 ## 工具准备 diff --git a/zh-cn/application-dev/quick-start/start-with-ets-stage.md b/zh-cn/application-dev/quick-start/start-with-ets-stage.md index 50f6a5358a6abef0fe7f257f2684b25d70f014ec..04f63893d96bfd9ced996ed1f9d3f5c40b30142a 100644 --- a/zh-cn/application-dev/quick-start/start-with-ets-stage.md +++ b/zh-cn/application-dev/quick-start/start-with-ets-stage.md @@ -2,7 +2,7 @@ > **说明:** -> +> > 为确保运行效果,本文以使用**DevEco Studio 4.0 Beta2**版本为例,点击[此处](../../release-notes/OpenHarmony-v4.0-beta2.md#配套关系)获取下载链接。 ## 创建ArkTS工程 @@ -302,7 +302,13 @@ .height('5%') // 跳转按钮绑定onClick事件,点击时跳转到第二页 .onClick(() => { - router.pushUrl({ url: 'pages/Second' }) + console.info(`Succeeded in clicking the 'Next' button.`) + // 跳转到第二页 + router.pushUrl({ url: 'pages/Second' }).then(() => { + console.info('Succeeded in jumping to the second page.') + }).catch((err) => { + console.error(`Failed to jump to the second page.Code is ${err.code}, message is ${err.message}`) + }) }) } .width('100%') @@ -346,7 +352,14 @@ .height('5%') // 返回按钮绑定onClick事件,点击按钮时返回到第一页 .onClick(() => { - router.back() + console.info(`Succeeded in clicking the 'Back' button.`) + try { + // 返回第一页 + router.back() + console.info('Succeeded in returning to the first page.') + } catch (err) { + console.error(`Failed to return to the first page.Code is ${err.code}, message is ${err.message}`) + } }) } .width('100%') diff --git a/zh-cn/application-dev/quick-start/typescript-to-arkts-migration-guide.md b/zh-cn/application-dev/quick-start/typescript-to-arkts-migration-guide.md index 936d48a0e7aab7592af9b28a32c8acbaebd5f009..4497a9775dca7274e4f1f08dd572e8bc85f0a9ed 100644 --- a/zh-cn/application-dev/quick-start/typescript-to-arkts-migration-guide.md +++ b/zh-cn/application-dev/quick-start/typescript-to-arkts-migration-guide.md @@ -3,10 +3,10 @@ 本文通过提供简洁的约束指导如何将标准的TypeScript代码重构为ArkTS代码。尽管ArkTS是基于TypeScript设计的,但出于性能考虑,一些TypeScript的特性被限制了。因此,在ArkTS中,所有的TypeScript特性被分成三类。 1. **完全支持的特性**:原始代码无需任何修改。根据测试,对于已遵循最佳TypeScript实践的项目,代码库中90%到97%的内容可以保持原封不动。 -2. **部分支持的特性**:需小规模的代码重构。例如,必须使用关键字`let`代替`var`来声明变量。注意,根据本文提供的约束进行代码重构后,您的代码仍为有效的TypeScript代码。 +2. **部分支持的特性**:需小规模的代码重构。例如,必须使用关键字`let`代替`var`来声明变量。 3. **不支持的特性**:需大规模的代码重构。例如,不支持`any`类型,所有使用`any`的代码都需要引入显式类型。 -本文将逐一介绍所有部分支持和所有不支持的特性,并提供代码重构的建议。对于没有提到的特性,则说明ArkTS完全支持。 +本文将逐一介绍所有部分支持和所有不支持的特性,并提供代码重构的建议。根据本文提供的约束进行代码重构后代码仍为有效的TypeScript代码。对于没有提到的特性,则说明ArkTS完全支持。 **示例** @@ -49,7 +49,7 @@ ArkTS在设计之初,就确定了如下目标: - ArkTS代码需非常容易阅读和理解,因为代码的阅读频率高于编写频率。 - 以最小功耗快速执行代码,这点对于移动设备(ArkTS的目标设备)来说至关重要。 -静态类型是ArkTS最重要的特性之一。使用静态类型有助于实现上述两个目标。如果程序采用静态类型,即所有类型在编译时都是已知的,那么开发者就能够容易理解代码中使用了哪些数据结构。同时,由于所有类型在程序实际运行前都是已知的,编译器可以提前验证代码的正确性,从而可以减少运行时类型检查项,有助于性能提升。 +静态类型是ArkTS最重要的特性之一。使用静态类型有助于实现上述两个目标。如果程序采用静态类型,即所有类型在编译时都是已知的,那么开发者就能够容易理解代码中使用了哪些数据结构。同时,由于所有类型在程序实际运行前都是已知的,编译器可以提前验证代码的正确性,从而可以减少运行时的类型检查,有助于性能提升。 基于上述考虑,ArkTS中禁止使用`any`类型。 @@ -107,24 +107,24 @@ class Point { // 无法从对象中删除某个属性,从而确保所有Point对象都具有属性x: let p1 = new Point(1.0, 1.0) -delete p1.x // 无论使用TypeScript还是ArkTS,都会产生编译时错误 -delete (p1 as any).x // 使用TypeScript时,不会报错;使用ArkTS时,会产生编译时错误 +delete p1.x // 在TypeScript和ArkTS中,都会产生编译时错误 +delete (p1 as any).x // 在TypeScript中不会报错;在ArkTS中会产生编译时错误 -// Point类没有定义命名为`z`的属性,在程序运行时也无法添加该属性: +// Point类没有定义命名为z的属性,在程序运行时也无法添加该属性: let p2 = new Point(2.0, 2.0) -p2.z = "Label"; // 无论使用TypeScript还是ArkTS,都会产生编译时错误 -(p2 as any).z = "Label" // 使用TypeScript时,不会报错;使用ArkTS时,会产生编译时错误 +p2.z = "Label"; // 在TypeScript和ArkTS中,都会产生编译时错误 +(p2 as any).z = "Label" // 在TypeScript中不会报错;在ArkTS中会产生编译时错误 -// 确保所有Point对象只有属性x和y,并且无法产生一些任意标识符并将其用作新属性: +// 类的定义确保了所有Point对象只有属性x和y,并且无法被添加其他属性: let p3 = new Point(3.0, 3.0) -let prop = Symbol(); // 使用TypeScript时,不会报错;使用ArkTS时,会产生编译时错误 -(p3 as any)[prop] = p3.x // 使用TypeScript时,不会报错;使用ArkTS时,会产生编译时错误 -p3[prop] = p3.x // 无论使用TypeScript还是ArkTS,都会产生编译时错误 +let prop = Symbol(); // 在TypeScript中不会报错;在ArkTS中会产生编译时错误 +(p3 as any)[prop] = p3.x // 在TypeScript中不会报错;在ArkTS中会产生编译时错误 +p3[prop] = p3.x // 在TypeScript和ArkTS中,都会产生编译时错误 -// 确保所有Point对象都具有number类型的属性x和y。因此,无法赋予其他类型的值给该属性: +// 类的定义确保了所有Point对象的属性x和y都具有number类型,因此,无法将其他类型的值赋值给它们: let p4 = new Point(4.0, 4.0) -p4.x = "Hello!"; // 无论使用TypeScript还是ArkTS,都会产生编译时错误 -(p4 as any).x = "Hello!" // 使用TypeScript时,不会报错;使用ArkTS时,会产生编译时错误 +p4.x = "Hello!"; // 在TypeScript和ArkTS中,都会产生编译时错误 +(p4 as any).x = "Hello!" // 在TypeScript中不会报错;在ArkTS中会产生编译时错误 // 使用符合类定义的Point对象: function distance(p1 : Point, p2 : Point) : number { @@ -148,22 +148,18 @@ console.log("Distance between p5 and p6: " + distance(p5, p6)) **示例** ```typescript -// 运算符`+`可以用于数字和字符串,但不能用于其他类型: -class C { - // ... -} -let c1 : C = new C() -let c2 : C = new C() -console.log(c1 + c2) // 编译时报错 +// 一元运算符`+`只能作用于数值类型: +console.log(+42) // 合法运算 +console.log(+"42") // 编译时错误 ``` 使用额外的语义重载语言运算符会增加语言规范的复杂度,而且,开发者还被迫牢记所有可能的例外情况及对应的处理规则。在某些情况下,产生一些不必要的运行时开销。 当前只有不到1%的代码库使用该特性。因此,尽管限制运算符的语义需要重构代码,但重构量很小且非常容易操作,并且,通过重构能使代码更清晰、具备更高性能。 -### (暂时)不支持 structural typing +### 不支持 structural typing -假设两个不相关的类`T`和`U`拥有相同的公共API: +假设两个不相关的类`T`和`U`拥有相同的`public`API: ```typescript class T { @@ -203,8 +199,8 @@ greeter(t) // 是否允许? 换句话说,我们将采取下面哪种方法呢: -- `T`和`U`没有继承关系或没有任何公共接口,但由于它们具有相同的公共API,它们“在某种程度上是相等的”,所以上述两个问题的答案都是“是”; -- `T`和`U`没有继承关系或没有任何公共接口,应当始终被视为完全不同的类型,因此上述两个问题的答案都是“否”。 +- `T`和`U`没有继承关系或没有`implements`相同的接口,但由于它们具有相同的`public`API,它们“在某种程度上是相等的”,所以上述两个问题的答案都是“是”; +- `T`和`U`没有继承关系或没有`implements`相同的接口,应当始终被视为完全不同的类型,因此上述两个问题的答案都是“否”。 采用第一种方法的语言支持structural typing,而采用第二种方法的语言则不支持structural typing。目前TypeScript支持structural typing,而ArkTS不支持。 @@ -254,12 +250,11 @@ console.log(z.get(2)) **相关约束** * 不支持Symbol() API -* 访问未定义的属性将导致编译时错误 +* 不支持通过索引访问字段 * 不支持delete运算符 * 仅允许在表达式中使用typeof运算符 * 不支持in运算符 * 禁止运行时检查对象属性 -* 不支持声明动态属性 * 限制使用标准库 @@ -271,6 +266,8 @@ console.log(z.get(2)) TypeScript中的`Symbol()`API用于在运行时生成唯一的属性名称。由于该API的常见使用场景在静态类型语言中没有意义,因此,ArkTS不支持`Symbol()`API。在ArkTS中,对象布局在编译时就确定了,且不能在运行时被更改。 +ArkTS也不支持`Symbol.iterator`和`Iterable interface`。请使用数组或容器。 + **TypeScript** ```typescript @@ -278,6 +275,26 @@ const sym = Symbol() let o = { [sym]: "value" } + +let obj = { + data: ['a', 'b', 'c'], + [Symbol.iterator]() { + const this_ = this + let index = 0 + return { + next() { + return { + done: index >= this_.data.length, + value: 'name_' + this_.data[index++] + } + } + } + } +} + +for (let t of obj) { + console.log(t) +} ``` **ArkTS** @@ -287,17 +304,21 @@ class SomeClass { public someProperty : string = "" } let o = new SomeClass() + +let arr:string[] = ['a', 'b', 'c'] +for (let t of arr) { + console.log('name_' + t) +} ``` **相关约束** * 仅支持属性名为标识符的对象 -* 访问未定义的属性将导致编译时错误 +* 不支持通过索引访问字段 * 不支持delete运算符 * 仅允许在表达式中使用typeof运算符 * 不支持in运算符 * 禁止运行时检查对象属性 -* 不支持声明动态属性 * 限制使用标准库 ### 不支持以`#`开头的私有字段 @@ -324,13 +345,13 @@ class C { } ``` -### 类型、命名空间等的命名必须唯一 +### 类型、命名空间的命名必须唯一 **规则:**`arkts-unique-names` **级别:错误** -类型、命名空间等的命名必须唯一,且能够与其他名称(例如:变量名)区分开来。 +类型(类、接口、枚举)、命名空间的命名必须唯一,且与其他名称(例如:变量名、函数名)不同。 **TypeScript** @@ -830,93 +851,100 @@ class Point {x: number = 0; y: number = 0} type N = number ``` -### 不支持索引访问字段 +### 不支持通过索引访问字段 **规则:**`arkts-no-props-by-index` **级别:错误** -ArkTS不支持通过索引访问对象的字段。改用点操作符。 +ArkTS不支持动态声明字段,不支持动态访问字段。只能访问已在类中声明或者继承可见的字段,访问其他字段将会造成编译时错误。 +使用点操作符访问字段,例如(`obj.field`),不支持索引访问(`obj[field]`)。 +ArkTS支持通过索引访问`TypedArray`(例如`Int32Array`)中的元素。 **TypeScript** ```typescript -class Point {x: number = 0; y: number = 0} -let p: Point = {x: 1, y: 2} -let x = p["x"] -``` - -**ArkTS** - -```typescript -class Point {x: number = 0; y: number = 0} +class Point { + x: number = 0 + y: number = 0 +} let p: Point = {x: 1, y: 2} -let x = p.x -``` - -### 不支持structural identity - -**规则:**`arkts-no-structural-identity` +console.log(p["x"]) -**级别:错误** - -目前ArkTS不支持structural identity,即编译器无法比较两种类型的公共API并决定它们是否相同。可改用其他机制,例如继承、接口或类型别名。 - -对于下面的示例,类型`X`和`Y`在TypeScript中是等价的(可互换),而在ArkTS中,他们是不等价的。 - -**TypeScript** - -```typescript -interface X { - f(): string +class Person { + name: string = "" + age: number = 0; + [key: string]: string | number } -interface Y { // Y等于X - f(): string +let person: Person = { + name: "John", + age: 30, + email: "***@example.com", + phoneNumber: "18*********", } ``` **ArkTS** ```typescript -interface X { - f(): string +class Point { + x: number = 0 + y: number = 0 } +let p: Point = {x: 1, y: 2} +console.log(p.x) -type Y = X // Y等于X -``` +class Person { + name: string + age: number + email: string + phoneNumber: string -**相关约束** + constructor(name: string, age: number, email: string, + phoneNumber: string) { + this.name = name + this.age = age + this.email = email + this.phoneNumber = phoneNumber + } +} + +let person = new Person("John", 30, "***@example.com", "18*********") +console.log(person["name"]) // 编译时错误 +console.log(person.unknownProperty) // 编译时错误 -* 子类型/父类型不支持structural typing -* 赋值检查不支持structural typing -* 类型推断不支持structural typing +let arr = new Int32Array(1) +console.log(arr[0]) +``` -### 子类型/父类型不支持structural typing +### 不支持structural typing -**规则:**`arkts-no-structural-subtyping` +**规则:**`arkts-no-structural-typing` **级别:错误** -当前ArkTS在类型推导时不会检查structural是否相同,即编译器无法比较两种类型的公共API并决定它们是否相同。改用其他机制,例如继承或接口。 +ArkTS不支持structural typing,编译器无法比较两种类型的`public`API并决定它们是否相同。使用其他机制,例如继承、接口或类型别名。 **TypeScript** ```typescript -class X { - public foo: number +interface I1 { + f(): string +} - constructor() { - this.foo = 0 - } +interface I2 { // I2等价于I1 + f(): string } -class Y { - public foo: number +class X { + n: number = 0 + s: string = "" +} - constructor() { - this.foo = 0 - } +class Y { // Y等价于X + n: number = 0 + s: string = "" } let x = new X() @@ -927,118 +955,80 @@ y = x console.log("Assign Y to X") x = y -``` - -**ArkTS** - -```typescript -class X { - public foo: number - - constructor() { - this.foo = 0 - } -} -// Y从X派生,显式定义继承关系 -class Y extends X { - constructor() { - super() - } +function foo(x: X) { + console.log(x.n, x.s) } -let x = new X() -let y = new Y() - -console.log("Assign Y to X") -x = y // ok, X是Y的父类 - -// 不能将X赋值给Y -// y = x -编译时错误 +// 由于X和Y的API是等价的,所以X和Y是等价的 +foo(new X()) +foo(new Y()) ``` -**相关约束** - -* 不支持structural identity -* 赋值检查不支持structural typing -* 类型推断不支持structural typing - -### 赋值检查不支持structural typing - -**规则:**`arkts-no-structural-assignability` - -**级别:错误** - -当前ArkTS在检查变量是否可相互赋值时不检查结构等价性,即编译器无法比较两种类型的公共API并决定它们是否相同。改用其他机制,例如继承或接口。 - -**TypeScript** +**ArkTS** ```typescript -class X { - public foo: number +interface I1 { + f(): string +} - constructor() { - this.foo = 0 - } +type I2 = I1 // I2是I1的别名 + +class B { + n: number = 0 + s: string = "" } -class Y { - public foo: number +// D是B的继承类,构建了子类型和父类型的关系 +class D extends B { constructor() { - this.foo = 0 + super() } } -let x = new X() -let y = new Y() - -console.log("Assign X to Y") -y = x +let b = new B() +let d = new D() -console.log("Assign Y to X") -x = y -``` +console.log("Assign D to B") +b = d // 合法赋值,因为B是D的父类 -**ArkTS** +// 将b赋值给d将会引起编译时错误 +// d = b -```typescript interface Z { - foo: number + n: number + s: string } -// X实现了接口Z,显式化定义了X和Y之间的关系。 +// 类X implements 接口Z,构建了X和Y的关系 class X implements Z { - public foo: number - - constructor() { - this.foo = 0 - } + n: number = 0 + s: string = "" } -// Y实现了接口Z,显式化定义了X和Y之间的关系。 +// 类Y implements 接口Z,构建了X和Y的关系 class Y implements Z { - public foo: number - - constructor() { - this.foo = 0 - } + n: number = 0 + s: string = "" } let x: Z = new X() let y: Z = new Y() console.log("Assign X to Y") -y = x // ok,两者类型相同 +y = x // 合法赋值,它们是相同的类型 console.log("Assign Y to X") -x = y // ok,两者类型相同 -``` +x = y // 合法赋值,它们是相同的类型 -**相关约束** +function foo(c: Z): void { + console.log(c.n, c.s) +} -* 不支持structural identity -* 子类型/父类型不支持structural typing -* 类型推断不支持structural typing +// 类X和类Y implement 相同的接口,因此下面的两个函数调用都是合法的 +foo(new X()) +foo(new Y()) +``` ### 显式标注泛型函数类型实参,除非可以从参数中推断出类型实参 @@ -1080,105 +1070,13 @@ function greet(): T { let z = greet() ``` -### 类型推断不支持structural typing - -**规则:**`arkts-no-structural-inference` - -**级别:错误** - -当前ArkTS不支持structural typing,即编译器无法比较两种类型的公共API并决定它们是否相同。使用继承和接口显式指定类型之间的关系。 - -**TypeScript** - -```typescript -class X { - public foo: number - private s: string - - constructor (f: number) { - this.foo = f - this.s = "" - } - - public say(): void { - console.log("X = ", this.foo) - } -} - -class Y { - public foo: number - - constructor (f: number) { - this.foo = f - } - public say(): void { - console.log("Y = ", this.foo) - } -} - -function bar(z: X): void { - z.say() -} - -// X和Y具有相同的公共API,因此它们是等价的。 -// 允许第二次调用 -bar(new X(1)) -bar(new Y(2) as X) -``` - -**ArkTS** - -```typescript -interface Z { - say(): void -} - -class X implements Z { - public foo: number - private s: string - - constructor (f: number) { - this.foo = f - this.s = "" - } - public say(): void { - console.log("X = ", this.foo) - } -} - -class Y implements Z { - public foo: number - - constructor (f: number) { - this.foo = f - } - public say(): void { - console.log("Y = ", this.foo) - } -} - -function bar(z: Z): void { - z.say() -} - -// X和Y实现了相同的接口Z,因此两个调用均允许: -bar(new X(1)) -bar(new Y(2)) -``` - -**相关约束** - -* 不支持structural identity -* 子类型/父类型不支持structural typing -* 赋值检查不支持structural typing - ### 不支持使用正则字面量 **规则:**`arkts-no-regexp-literals` **级别:错误** -当前ArkTS不支持正则字面量。改用通过`RegExp()`创建。 +当前ArkTS不支持正则字面量。请使用`RegExp()`创建正则对象。 **TypeScript** @@ -1249,7 +1147,7 @@ function id_x_y(o: Point): Point { return o } -// 因为TS支持structural typing,编译器可以推断p的类型为Point +// TS支持structural typing,可以推断p的类型为Point let p = {x: 5, y: 10} id_x_y(p) @@ -1305,7 +1203,7 @@ class Point { y: number = 0 // 在字面量初始化之前,使用constructor()创建一个有效对象。 - // 由于Point没有其它构造函数,编译器将自动添加一个默认构造函数。 + // 由于没有为Point定义构造函数,编译器将自动添加一个默认构造函数。 } function id_x_y(o: Point): Point { @@ -1392,32 +1290,6 @@ let a2: C[] = [{n: 1, s: "1"}, {n: 2, s : "2"}] // a2的类型为“C[]” * 对象字面量必须对应某些显式声明的类或接口 * 对象字面量不能用于类型声明 -### 显式标注Lambda函数的参数类型 - -**规则:**`arkts-explicit-param-types-in-lambdas` - -**级别:错误** - -当前ArkTS要求显式标注lambda函数的参数的类型。 - -**TypeScript** - -```typescript -// 只有在开启noImplicitAny选项时会产生编译时错误 -let f = (s /* type any is assumed */) => { - console.log(s) -} -``` - -**ArkTS** - -```typescript -// 显式标注Lambda函数的参数类型 -let f = (s: string) => { - console.log(s) -} -``` - ### 使用箭头函数而非函数表达式 **规则:**`arkts-no-func-expressions` @@ -1540,54 +1412,6 @@ class C1 implements C { } ``` -### 访问未定义的属性将导致编译时错误 - -**规则:**`arkts-no-undefined-prop-access` - -**级别:错误** - -ArkTS仅支持访问那些在类中已声明或通过继承可访问的属性。禁止访问任何其他属性,否则会导致编译时错误。使用恰当的类型可以帮助编译期进行类型检查,确定属性是否存在。 - -**TypeScript** - -```typescript -let person = {name: "Bob", isEmployee: true} - -let n = person["name"] -let e = person["isEmployee"] -let s = person["office"] // 只有在开启noImplicitAny选项时会产生编译时错误 -``` - -**ArkTS** - -```typescript -class Person { - constructor(name: string, isEmployee: boolean) { - this.name = name - this.isEmployee = isEmployee - } - - name: string - isEmployee: boolean -} - -let person = new Person("Bob", true) -let n = person.name -let e = person.isEmployee -let s = person.office // 编译时错误 -``` - -**相关约束** - -* 对象的属性名必须是合法的标识符 -* 不支持Symbol() API -* 不支持delete运算符 -* 仅允许在表达式中使用typeof运算符 -* 不支持in运算符 -* 禁止运行时检查对象属性 -* 不支持声明动态属性 -* 限制使用标准库 - ### 类型转换仅支持`as T`语法 **规则:**`arkts-as-casts` @@ -1743,11 +1567,10 @@ p.y = null * 对象的属性名必须是合法的标识符 * 不支持Symbol() API -* 访问未定义的属性将导致编译时错误 +* 不支持通过索引访问字段 * 仅允许在表达式中使用typeof运算符 * 不支持in运算符 * 禁止运行时检查对象属性 -* 不支持声明动态属性 ### 仅允许在表达式中使用`typeof`运算符 @@ -1783,66 +1606,12 @@ let s2: string * 对象的属性名必须是合法的标识符 * 不支持Symbol() API -* 访问未定义的属性将导致编译时错误 +* 不支持通过索引访问字段 * 不支持delete运算符 * 不支持in运算符 * 禁止运行时检查对象属性 -* 不支持声明动态属性 * 限制使用标准库 -### 二元运算符`+`仅支持数字和字符串的隐式转换 - -**规则:**`arkts-no-polymorphic-plus` - -**级别:错误** - -如果二元运算符`+`的一个操作数是`string`类型(包括enum中的`string`),那么另一个操作数可以是任意的类型,在运算时它的值被隐式转换成`string`。在其他情况下,ArkTS只支持`number`和enum中的`number`的隐式转换。 -正如TypeScript一样,ArkTS不支持两个`boolean`类型的值相加。其他情形下,都需要显式转换为字符串。 - -**TypeScript** - -```typescript -enum E { E1, E2 } - -let a = 10 + 32 // 42 -let b = E.E1 + 10 // 10 -let c = 10 + "5" // "105" - -let d = "5" + E.E2 // "51" -let e = "Hello, " + "world!" // "Hello, world!" -let f = "string" + true // "stringtrue" - -let g = (new Object()) + "string" // "[object Object]string" - -let i = true + true // JS: 2, TS: 编译时错误 -let j = true + 2 // JS: 3, TS: 编译时错误 -let k = E.E1 + true // JS: 1, TS: 编译时错误 -``` - -**ArkTS** - -```typescript -enum E { E1, E2 } - -let a = 10 + 32 // 42 -let b = E.E1 + 10 // 10 -let c = 10 + "5" // "105" - -let d = "5" + E.E2 // "51" -let e = "Hello, " + "world!" // "Hello, world!" -let f = "string" + true // "stringtrue" - -let g = (new Object()).toString() + "string" - -let i = true + true // 编译时错误 -let j = true + 2 // 编译时错误 -let k = E.E1 + true // 编译时错误 -``` - -**相关约束** - -* 一元运算符+、-和~仅适用于数值类型 - ### 部分支持`instanceof`运算符 **规则:**`arkts-instanceof-ref-types` @@ -1911,11 +1680,10 @@ let b = p instanceof Person // true,且属性name一定存在 * 对象的属性名必须是合法的标识符 * 不支持Symbol() API -* 访问未定义的属性将导致编译时错误 +* 不支持通过索引访问字段 * 不支持delete运算符 * 仅允许在表达式中使用typeof运算符 * 禁止运行时检查对象属性 -* 不支持声明动态属性 * 限制使用标准库 ### 不支持解构赋值 @@ -2030,33 +1798,6 @@ let x = zp.x let y = zp.y ``` -### 不支持隐含类型的推断 - -**规则:**`arkts-no-implied-inference` - -**级别:错误** - -目前ArkTS不支持隐含类型的推断,改用显式的类型标注。如果容器中有不同类型的数据,请使用`Object[]`。 - -**TypeScript** - -```typescript -let [a, b, c] = [1, "hello", true] -``` - -**ArkTS** - -```typescript -let a = 1 -let b = "hello" -let c = true - -let arr: Object[] = [1, "hello", true] -let a1 = arr[0] -let b1 = arr[1] -let c1 = arr[2] -``` - ### 不支持在catch语句标注类型 **规则:**`arkts-no-types-in-catch` @@ -2119,30 +1860,15 @@ for (let i = 0; i < a.length; ++i) { **相关约束** -* 不支持可迭代接口 * for-of仅适用于数组和字符串 -### 不支持可迭代接口 - -**规则:**`arkts-no-iterable` - -**级别:错误** - -ArkTS不支持`Symbol`API、`Symbol.iterator`和最终可迭代的接口。请使用数组和标准库中的容器。 - -**相关约束** - -* 不支持Symbol() API -* 不支持for .. in -* for-of仅支持数组和字符串 - ### `for-of`仅适用于数组和字符串 **规则:**`arkts-for-of-str-arr` **级别:错误** -ArkTS支持通过`for .. of`迭代数组和字符串,但不支持迭代对象。 +ArkTS支持通过`for .. of`迭代数组、字符串和`TypedArray`(例如`Int32Array`),但不支持迭代对象。 **TypeScript** @@ -2166,7 +1892,6 @@ for (let n of numbers) { **相关约束** * 不支持for .. in -* 不支持可迭代接口 ### 不支持映射类型 @@ -2226,92 +1951,6 @@ let r: number = 42 console.log("Area: ", Math.PI * r * r) ``` -### `case`语句仅支持编译期值 - -**规则:**`arkts-no-computed-case` - -**级别:错误** - -在ArkTS中,`case`语句仅支持编译期值。若值无法在编译期确定,请使用`if`语句。 - -**TypeScript** - -```typescript -let x = 2 -let y = 3 -switch (x) { - case 1: - console.log(1) - break - case 2: - console.log(2) - break - case y: - console.log(y) - break - default: - console.log("other") -} -``` - -**ArkTS** - -```typescript -let x = 2 -switch (x) { - case 1: - console.log(1) - break - case 2: - console.log(2) - break - case 3: - console.log(3) - break - default: - console.log("other") -} -``` - -### 限制`switch`语句中表达式的类型 - -**规则:**`arkts-limited-switch` - -**级别:错误** - -ArkTS支持`switch`语句中使用`number`, `Number`, `string`, `String`或者`enum`类型的值。其他情况下请使用`if`语句。 - -**TypeScript** - -```typescript -class Point { - x: number = 0 - y: number = 0 -} - -let a = new Point() - -switch (a) { - case null: break - default: console.log("not null") -} -``` - -**ArkTS** - -```typescript -class Point { - x: number = 0 - y: number = 0 -} - -let a = new Point() - -if (a != null) { - console.log("not null") -} -``` - ### 限制`throw`语句中表达式的类型 **规则:**`arkts-limited-throw` @@ -2475,7 +2114,7 @@ function addNum(a: number, b: number): void { **级别:错误** -ArkTS不支持在函数中使用`this`。只能在方法中使用`this`。 +ArkTS不支持在函数和静态方法中使用`this`。只能在方法中使用`this`。 **TypeScript** @@ -2689,7 +2328,7 @@ function main(): void { **级别:错误** -展开运算符唯一支持的场景是函数剩余参数为数组类型。 +展开运算符唯一支持的场景是函数剩余参数为数组类型,包括`TypedArray`(例如`Int32Array`)。 **TypeScript** @@ -2845,7 +2484,7 @@ class C implements Mover, Shaker { **级别:错误** -ArkTS不支持合并声明。所用类、接口等的声明必须唯一。 +ArkTS不支持类、接口的声明合并。 **TypeScript** @@ -2962,11 +2601,10 @@ function main(): void { * 对象的属性名必须是合法的标识符 * 不支持Symbol() API -* 访问未定义的属性将导致编译时错误 +* 不支持通过索引访问字段 * 不支持delete运算符 * 仅允许运算符typeof在表达式上下文中使用 * 不支持in运算符 -* 不支持声明动态属性 * 限制使用标准库 ### 不支持构造函数类型 @@ -3018,65 +2656,7 @@ let Impersonizer: PersonCtor = (n: string, a: number): Person => { const person = createPerson(Impersonizer, "John", 30) ``` -### 不支持声明动态属性 - -**规则:**`arkts-no-dyn-prop-decl` - -**级别:错误** - -ArkTS不支持声明动态属性。必须在类中声明所有的属性。尽管可以用对象数组来实现动态特性,但更推荐使用静态类型范式来显式声明字段、名称和类型。 - -**TypeScript** - -```typescript -class Person { - name: string = "" - age: number = 0; // 此处需要分号 - [key: string]: string | number -} - -const person: Person = { - name: "John", - age: 30, - email: "***@example.com", - phoneNumber: 18*********, -} -``` - -**ArkTS** - -```typescript -class Person { - name: string - age: number - email: string - phoneNumber: number - - constructor(name: string, age: number, email: string, phoneNumber: number) { - this.name = name - this.age = age - this.email = email - this.phoneNumber = phoneNumber - } -} - -function main(): void { - const person: Person = new Person("John", 30, "***@example.com", 18*********) -} -``` - -**相关约束** - -* 对象的属性名必须是合法的标识符 -* 不支持Symbol() API -* 访问未定义的属性将导致编译时错误 -* 不支持delete运算符 -* 仅允许在表达式中使用typeof运算符 -* 不支持in运算符 -* 禁止运行时检查对象属性 -* 限制使用标准库 - -### 只能使用类型相同的编译期表达式初始化枚举成员 +### 只能使用类型相同的编译时表达式初始化枚举成员 **规则:**`arkts-no-enum-mixed-types` @@ -3273,7 +2853,7 @@ import "path/to/module" **ArkTS** ```typescript -import * from "path/to/module" +import * as ns from "path/to/module" ``` ### 不支持`import default as ...` @@ -3326,7 +2906,7 @@ import * as m from "mod" **级别:错误** -ArkTS支持大多数场景下的重导出,比如命名导出和重命名导出,重导出import的。不支持`export * as ...`。 +ArkTS支持命名重导出和重命名重导出。支持`export * ...`的语法,不支持`export * as ...`的语法。 **TypeScript** @@ -3363,6 +2943,9 @@ export class Class2 { export { Class1 } from "module1" export { C2 as Class2 } from "module1" +// 支持以下语法 +// export * from "module1" + // consumer模块 import { Class1, Class2 } from "module2" @@ -3512,7 +3095,7 @@ declare namespace N { function foo(x: number): number } -import * from "module" +import * as m from "module" console.log("N.foo called: ", N.foo(42)) ``` @@ -3622,32 +3205,6 @@ let ce = new CustomError() * 不支持在原型上赋值 -### 不支持动态导入 - -**规则:**`arkts-no-runtime-import` - -**级别:错误** - -由于在ArkTS中,导入是编译时而非运行时特性,因此,ArkTS不支持动态导入,如`await import...`。改用静态`import`语法。 - -**TypeScript** - -```typescript -const zipUtil = await import("utils/create-zip-file") -``` - -**ArkTS** - -```typescript -import { zipUtil } from "utils/create-zip-file" -``` - -**相关约束** - -* 不支持在模块名中使用通配符 -* 不支持通用模块定义(UMD) -* 不支持导入断言 - ### 不支持确定赋值断言 **规则:**`arkts-no-definite-assignment` @@ -3796,7 +3353,7 @@ M.abc = 200 **级别:错误** -当前ArkTS不支持从TypeScript扩展到标准库的utility类型(例如`Omit`、`Pick`等)。支持`Partial`和`Record`。 +ArkTS仅支持`Partial`和`Record`,不支持TypeScript中其他的`Utility Types`。 对于*Record*类型,表达式*rec[index]*的类型是*V | undefined*。 对于`Record`类型,键-值中的值的类型必须是可选类型或者包含`undefined`的联合类型。 @@ -4079,9 +3636,7 @@ ArkTS不允许使用TypeScript或JavaScript标准库中的某些接口。大部 全局对象的属性和方法:`eval`、 `Infinity`、`NaN`、`isFinite`、`isNaN`、`parseFloat`、`parseInt`、 -`encodeURI`、`encodeURIComponent`、`Encode`、 -`decodeURI`、`decodeURIComponent`、`Decode`、 -`escape`、`unescape`、`ParseHexOctet` +`Encode`、`Decode`、`ParseHexOctet` `Object`:`__proto__`、`__defineGetter__`、`__defineSetter__`、 `__lookupGetter__`、`__lookupSetter__`、`assign`、`create`、 @@ -4111,16 +3666,15 @@ ArkTS不允许使用TypeScript或JavaScript标准库中的某些接口。大部 * 对象的属性名必须是合法的标识符 * 不支持Symbol() API -* 访问未定义的属性将导致编译时错误 +* 不支持通过索引访问字段 * 仅允许在表达式中使用typeof运算符 * 不支持in运算符 * 禁止运行时检查对象属性 -* 不支持声明动态属性 * 不支持globalThis ### 强制开启严格类型检查 -**规则 `arkts-strict-typing`** +**规则:**`arkts-strict-typing` **级别:错误** @@ -4172,7 +3726,7 @@ let n2: number = 0 ### 不允许通过注释关闭类型检查 -**规则 `arkts-strict-typing-required`** +**规则:**`arkts-strict-typing-required` **级别:错误** @@ -4206,7 +3760,7 @@ let s2: string = null // 编译时报错 ### 允许ArkTS代码导入TS代码, 不允许TS代码导入ArkTS代码 -**规则 `arkts-no-ts-deps`** +**规则:**`arkts-no-ts-deps` **级别:错误** @@ -4238,7 +3792,7 @@ import { C } from "lib1" ### 除了ArkUI中的装饰器,不允许使用其他装饰器 -**规则 `arkts-no-decorators-except-arkui`** +**规则:**`arkts-no-decorators-except-arkui` **级别:错误** @@ -4267,3 +3821,52 @@ function classDecorator(x: number, y: number): void { class BugReport { } ``` + +### `class`不能被用作对象 + +**规则:**`arkts-no-classes-as-obj` + +**级别:错误** + +在ArkTS中,`class`声明的是一个新的类型,不是一个值。因此,不支持将`class`用作对象(例如将`class`赋值给一个对象)。 + +**TypeScript** + +```typescript +class C { + s: string = "" + n: number = 0 +} + +let c = C +``` + +### 不支持在`import`语句前使用其他语句 + +**规则:**`arkts-no-misplaced-imports` + +**级别:错误** + +在ArkTS中,除动态`import`语句外,所有`import`语句需要放在所有其他语句之前。 + +**TypeScript** + +```typescript +class C { + s: string = "" + n: number = 0 +} + +import foo from "module1" +``` + +**ArkTS** + +```typescript +import foo from "module1" + +class C { + s: string = "" + n: number = 0 +} +``` diff --git a/zh-cn/application-dev/reference/apis/common_event/commonEvent-window.md b/zh-cn/application-dev/reference/apis/common_event/commonEvent-window.md index 83e183c75b2f00b432022446d318114f224c8df9..da223eca100e3ba8d9a44a437607b9d0e5e13e43 100644 --- a/zh-cn/application-dev/reference/apis/common_event/commonEvent-window.md +++ b/zh-cn/application-dev/reference/apis/common_event/commonEvent-window.md @@ -1,7 +1,7 @@ # 窗口管理子系统公共事件定义 窗口管理子系统支持发布下列系统公共事件,若需要订阅这些事件,请参见公共事件[接口文档](../js-apis-commonEventManager.md)。 -### COMMON_EVENT_SPLIT_SCREEN10+ +## COMMON_EVENT_SPLIT_SCREEN10+ 表示分屏行为的公共事件。 - 常量值: “usual.event.SPLIT_SCREEN” diff --git a/zh-cn/application-dev/reference/apis/js-apis-ability-featureAbility.md b/zh-cn/application-dev/reference/apis/js-apis-ability-featureAbility.md index 554aaedd9eefdff268ae72a0e6f29c1e1b56f040..8bd95f08ca7b69a0340b387f63e7e304b860803d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-ability-featureAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-ability-featureAbility.md @@ -127,7 +127,7 @@ acquireDataAbilityHelper(uri: string): DataAbilityHelper 使用规则: - 跨应用访问dataAbility,对端应用需配置关联启动 - - 调用方应用位于后台时,使用该接口访问dataAbility需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 + - 调用方应用位于后台时,使用该接口访问dataAbility需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限(基于API 8或更早版本SDK开发的应用在启动DataAbility组件时不受此限制的约束) - 跨应用场景下,目标dataAbility的visible属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 - 组件启动规则详见:[组件启动规则(FA模型)](../../application-models/component-startup-rules-fa.md) @@ -563,7 +563,7 @@ connectAbility(request: Want, options:ConnectOptions): number 使用规则: - 跨应用连接serviceAbility,对端应用需配置关联启动 - - 调用方应用位于后台时,使用该接口连接serviceAbility需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 + - 调用方应用位于后台时,使用该接口连接serviceAbility需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限(基于API 8或更早版本SDK开发的应用在启动ServiceAbility组件时不受此限制的约束) - 跨应用场景下,目标serviceAbility的visible属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 - 组件启动规则详见:[组件启动规则(FA模型)](../../application-models/component-startup-rules-fa.md) diff --git a/zh-cn/application-dev/reference/apis/js-apis-ability-particleAbility.md b/zh-cn/application-dev/reference/apis/js-apis-ability-particleAbility.md index ef0d0134d8a7f645ddd16d166a5086c0598a33e4..ab74e04e4f36611643716dcd5badec2051c1608d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-ability-particleAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-ability-particleAbility.md @@ -181,7 +181,7 @@ acquireDataAbilityHelper(uri: string): DataAbilityHelper 使用规则: - 跨应用访问dataAbility,对端应用需配置关联启动 - - 调用方应用位于后台时,使用该接口访问dataAbility需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 + - 调用方应用位于后台时,使用该接口访问dataAbility需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限(基于API 8或更早版本SDK开发的应用在启动DataAbility组件时不受此限制的约束) - 跨应用场景下,目标dataAbility的visible属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 - 组件启动规则详见:[组件启动规则(FA模型)](../../application-models/component-startup-rules-fa.md) @@ -230,7 +230,7 @@ startBackgroundRunning(id: number, request: NotificationRequest, callback: Async **示例**: ```ts -import notification from '@ohos.notification'; +import notification from '@ohos.notificationManager'; import particleAbility from '@ohos.ability.particleAbility'; import wantAgent from '@ohos.app.ability.wantAgent'; @@ -299,7 +299,7 @@ startBackgroundRunning(id: number, request: NotificationRequest): Promise<voi **示例**: ```ts -import notification from '@ohos.notification'; +import notification from '@ohos.notificationManager'; import particleAbility from '@ohos.ability.particleAbility'; import wantAgent from '@ohos.app.ability.wantAgent'; @@ -404,7 +404,7 @@ connectAbility(request: Want, options:ConnectOptions): number 使用规则: - 跨应用连接serviceAbility,对端应用需配置关联启动 - - 调用方应用位于后台时,使用该接口连接serviceAbility需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 + - 调用方应用位于后台时,使用该接口连接serviceAbility需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限(基于API 8或更早版本SDK开发的应用在启动ServiceAbility组件时不受此限制的约束) - 跨应用场景下,目标serviceAbility的visible属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 - 组件启动规则详见:[组件启动规则(FA模型)](../../application-models/component-startup-rules-fa.md) diff --git a/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md b/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index d71dabc4c8b38071f30c5d8ef766aab50721f36b..3b9166ac058b018d8713bd7ff2f9872610d959ca 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -7,7 +7,7 @@ ## 导入模块 -```js +```ts import abilityAccessCtrl from '@ohos.abilityAccessCtrl' ``` @@ -28,8 +28,8 @@ createAtManager(): AtManager **示例:** -```js -let atManager = abilityAccessCtrl.createAtManager(); +```ts +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); ``` ## AtManager @@ -67,15 +67,16 @@ checkAccessToken(tokenID: number, permissionName: Permissions): Promise<Grant **示例:** -```js +```ts import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import { BusinessError } from '@ohos.base'; -let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let tokenID: number = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 try { - atManager.checkAccessToken(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS').then((data) => { + atManager.checkAccessToken(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS').then((data: abilityAccessCtrl.GrantStatus) => { console.log(`checkAccessToken success, data->${JSON.stringify(data)}`); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log(`checkAccessToken fail, err->${JSON.stringify(err)}`); }); } catch(err) { @@ -114,10 +115,12 @@ verifyAccessTokenSync(tokenID: number, permissionName: Permissions): GrantStatus **示例:** -```js -let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 -let data = atManager.verifyAccessTokenSync(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS'); +```ts +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; + +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let tokenID: number = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 +let data: abilityAccessCtrl.GrantStatus = atManager.verifyAccessTokenSync(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS'); console.log(`data->${JSON.stringify(data)}`); ``` @@ -161,16 +164,17 @@ grantUserGrantedPermission(tokenID: number, permissionName: Permissions, permiss **示例:** -```js +```ts import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import { BusinessError } from '@ohos.base'; -let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 -let permissionFlags = 1; +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let tokenID: number = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 +let permissionFlags: number = 1; try { atManager.grantUserGrantedPermission(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS', permissionFlags).then(() => { console.log('grantUserGrantedPermission success'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log(`grantUserGrantedPermission fail, err->${JSON.stringify(err)}`); }); } catch(err) { @@ -213,14 +217,15 @@ grantUserGrantedPermission(tokenID: number, permissionName: Permissions, permiss **示例:** -```js +```ts import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import { BusinessError } from '@ohos.base'; -let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 -let permissionFlags = 1; +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let tokenID: number = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 +let permissionFlags: number = 1; try { - atManager.grantUserGrantedPermission(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS', permissionFlags, (err, data) => { + atManager.grantUserGrantedPermission(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS', permissionFlags, (err: BusinessError, data: void) => { if (err) { console.log(`grantUserGrantedPermission fail, err->${JSON.stringify(err)}`); } else { @@ -272,16 +277,17 @@ revokeUserGrantedPermission(tokenID: number, permissionName: Permissions, permis **示例:** -```js +```ts import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import { BusinessError } from '@ohos.base'; -let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 -let permissionFlags = 1; +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let tokenID: number = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 +let permissionFlags: number = 1; try { atManager.revokeUserGrantedPermission(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS', permissionFlags).then(() => { console.log('revokeUserGrantedPermission success'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log(`revokeUserGrantedPermission fail, err->${JSON.stringify(err)}`); }); } catch(err) { @@ -324,14 +330,15 @@ revokeUserGrantedPermission(tokenID: number, permissionName: Permissions, permis **示例:** -```js +```ts import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import { BusinessError } from '@ohos.base'; -let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 -let permissionFlags = 1; +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let tokenID: number = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 +let permissionFlags: number = 1; try { - atManager.revokeUserGrantedPermission(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS', permissionFlags, (err, data) => { + atManager.revokeUserGrantedPermission(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS', permissionFlags, (err: BusinessError, data: void) => { if (err) { console.log(`revokeUserGrantedPermission fail, err->${JSON.stringify(err)}`); } else { @@ -382,15 +389,16 @@ getPermissionFlags(tokenID: number, permissionName: Permissions): Promise<num **示例:** -```js +```ts import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import { BusinessError } from '@ohos.base'; -let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let tokenID: number = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 try { - atManager.getPermissionFlags(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS').then((data) => { + atManager.getPermissionFlags(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS').then((data: number) => { console.log(`getPermissionFlags success, data->${JSON.stringify(data)}`); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log(`getPermissionFlags fail, err->${JSON.stringify(err)}`); }); } catch(err) { @@ -416,10 +424,12 @@ getVersion(): Promise<number> **示例:** -```js -let atManager = abilityAccessCtrl.createAtManager(); +```ts +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; + +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); let promise = atManager.getVersion(); -promise.then(data => { +promise.then((data: number) => { console.log(`promise: data->${JSON.stringify(data)}`); }); ``` @@ -459,16 +469,16 @@ on(type: 'permissionStateChange', tokenIDList: Array<number>, permissionLi **示例:** -```js -import {Permissions} from '@ohos.abilityAccessCtrl'; +```ts +import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl'; import bundleManager from '@ohos.bundle.bundleManager'; -let atManager = abilityAccessCtrl.createAtManager(); -let appInfo = bundleManager.getApplicationInfoSync('com.example.myapplication', 0, 100); +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let appInfo: bundleManager.ApplicationInfo = bundleManager.getApplicationInfoSync('com.example.myapplication', 0, 100); let tokenIDList: Array = [appInfo.accessTokenId]; let permissionList: Array = ['ohos.permission.DISTRIBUTED_DATASYNC']; try { - atManager.on('permissionStateChange', tokenIDList, permissionList, (data) => { + atManager.on('permissionStateChange', tokenIDList, permissionList, (data: abilityAccessCtrl.PermissionStateChangeInfo) => { console.debug('receive permission state change, data:' + JSON.stringify(data)); }); } catch(err) { @@ -510,12 +520,12 @@ off(type: 'permissionStateChange', tokenIDList: Array<number>, permissionL **示例:** -```js -import {Permissions} from '@ohos.abilityAccessCtrl'; +```ts +import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl'; import bundleManager from '@ohos.bundle.bundleManager'; -let atManager = abilityAccessCtrl.createAtManager(); -let appInfo = bundleManager.getApplicationInfoSync('com.example.myapplication', 0, 100); +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let appInfo: bundleManager.ApplicationInfo = bundleManager.getApplicationInfoSync('com.example.myapplication', 0, 100); let tokenIDList: Array = [appInfo.accessTokenId]; let permissionList: Array = ['ohos.permission.DISTRIBUTED_DATASYNC']; try { @@ -552,15 +562,22 @@ verifyAccessToken(tokenID: number, permissionName: Permissions): Promise<Gran **示例:** -```js -import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +```ts +import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl'; +import { BusinessError } from '@ohos.base'; -let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 -let promise = atManager.verifyAccessToken(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS'); -promise.then(data => { - console.log(`promise: data->${JSON.stringify(data)}`); -}); +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let tokenID: number = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 +let permissionName: Permissions = 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS'; +try { + atManager.verifyAccessToken(tokenID, permissionName).then((data: abilityAccessCtrl.GrantStatus) => { + console.log(`promise: data->${JSON.stringify(data)}`); + }).catch((err: BusinessError) => { + console.log(`verifyAccessToken fail, err->${JSON.stringify(err)}`); + }); +}catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} ``` ### requestPermissionsFromUser9+ @@ -594,19 +611,68 @@ requestPermissionsFromUser(context: Context, permissionList: Array<Permission **示例:** - ```js +ArkTS语法不支持直接使用globalThis,需要通过一个单例的map来做中转。开发者需要: + + a. 在EntryAbility.ets中导入构建的单例对象GlobalThis。 + ```ts + import { GlobalThis } from '../utils/globalThis'; // 需要根据globalThis.ets的路径自行适配 + ``` + b. 在onCreate中添加: + ```ts + GlobalThis.getInstance().setContext('context', this.context); + ``` + + > **说明:** + > + > 由于在ts中引入ets文件会有告警提示,需要将EntryAbility.ts的文件后缀修改为EntryAbility.ets,并在module.json5中同步修改。 + +**globalThis.ets示例代码如下:** +```ts +import common from '@ohos.app.ability.common'; + +// 构造单例对象 +export class GlobalThis { + private constructor() {} + private static instance: GlobalThis; + private _uiContexts = new Map(); + + public static getInstance(): GlobalThis { + if (!GlobalThis.instance) { + GlobalThis.instance = new GlobalThis(); + } + return GlobalThis.instance; + } + + getContext(key: string): common.UIAbilityContext | undefined { + return this._uiContexts.get(key); + } + + setContext(key: string, value: common.UIAbilityContext): void { + this._uiContexts.set(key, value); + } + + // 其他需要传递的内容依此扩展 +} +``` + +```ts import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; -let atManager = abilityAccessCtrl.createAtManager(); +import { BusinessError } from '@ohos.base'; +import common from '@ohos.app.ability.common'; +import { GlobalThis } from '../utils/globalThis'; + +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); try { - atManager.requestPermissionsFromUser(this.context, ['ohos.permission.CAMERA'], (err, data)=>{ - console.info('data:' + JSON.stringify(data)); - console.info('data permissions:' + data.permissions); - console.info('data authResults:' + data.authResults); + let context: common.UIAbilityContext = GlobalThis.getInstance().getContext('context'); + atManager.requestPermissionsFromUser(context, ['ohos.permission.CAMERA'], (err: BusinessError, data)=>{ + console.info('data:' + JSON.stringify(data)); + console.info('data permissions:' + data.permissions); + console.info('data authResults:' + data.authResults); }); } catch(err) { console.log(`catch err->${JSON.stringify(err)}`); } - ``` +``` ### requestPermissionsFromUser9+ @@ -645,21 +711,28 @@ requestPermissionsFromUser(context: Context, permissionList: Array<Permission **示例:** - ```js +修改EntryAbility.ets和导入GlobalThis等步骤同上,此处不再重复 + +```ts import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; -let atManager = abilityAccessCtrl.createAtManager(); +import { BusinessError } from '@ohos.base'; +import common from '@ohos.app.ability.common'; +import { GlobalThis } from '../utils/globalThis'; + +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); try { - atManager.requestPermissionsFromUser(this.context, ['ohos.permission.CAMERA']).then((data) => { + let context: common.UIAbilityContext = GlobalThis.getInstance().getContext('context'); + atManager.requestPermissionsFromUser(context, ['ohos.permission.CAMERA']).then((data) => { console.info('data:' + JSON.stringify(data)); console.info('data permissions:' + data.permissions); console.info('data authResults:' + data.authResults); - }).catch((err) => { + }).catch((err: BusinessError) => { console.info('data:' + JSON.stringify(err)); }) } catch(err) { console.log(`catch err->${JSON.stringify(err)}`); } - ``` +``` ### verifyAccessToken(deprecated) @@ -688,15 +761,21 @@ verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStat **示例:** -```js +```ts import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import { BusinessError } from '@ohos.base'; -let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 -let promise = atManager.verifyAccessToken(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS'); -promise.then(data => { - console.log(`promise: data->${JSON.stringify(data)}`); -}); +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let tokenID: number = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 +try { + atManager.verifyAccessToken(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS').then((data: abilityAccessCtrl.GrantStatus) => { + console.log(`promise: data->${JSON.stringify(data)}`); + }).catch((err: BusinessError) => { + console.log(`verifyAccessToken fail, err->${JSON.stringify(err)}`); + }); +}catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} ``` ### checkAccessTokenSync10+ @@ -730,10 +809,13 @@ checkAccessTokenSync(tokenID: number, permissionName: Permissions): GrantStatus; **示例:** -```js -let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 -let data = atManager.checkAccessTokenSync(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS'); +```ts +import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl'; + +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let tokenID: number = 0; // 系统应用可以通过bundleManager.getApplicationInfo获取,普通应用可以通过bundleManager.getBundleInfoForSelf获取 +let permissionName: Permissions = 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS'; +let data: abilityAccessCtrl.GrantStatus = atManager.checkAccessTokenSync(tokenID, permissionName); console.log(`data->${JSON.stringify(data)}`); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-missionManager.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-missionManager.md index dd967e7981f4e2b3aee42a2d67a63440c89b0149..756f4235bf54b411cd1226a09585ebc024579b4f 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-missionManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-missionManager.md @@ -1066,7 +1066,7 @@ moveMissionToFront(missionId: number, options?: StartOptions): Promise<void&g | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | missionId | number | 是 | 任务ID。 | - | options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动参数选项,用于指定任务切到前台时的窗口模式,设备ID等。 | + | options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动参数选项,用于指定任务切到前台时的窗口模式,设备ID等。默认为空,表示按照默认启动参数。 | **返回值:** @@ -1243,7 +1243,7 @@ moveMissionsToForeground(missionIds: Array<number>, topMission?: number): | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | missionIds | Array<number> | 是 | 任务ID数组。 | - | topMission | number | 否 | 待移动到最顶层的任务ID | + | topMission | number | 否 | 待移动到最顶层的任务ID。默认值为-1,表示将默认任务移动到最顶层。 | **返回值:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiExtensionContentSession.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiExtensionContentSession.md index ea086e8f5f5c8587372f655f002c75654ae7d225..005e6cb411c81a96ec4b68cb7b1f151900782c69 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiExtensionContentSession.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiExtensionContentSession.md @@ -74,7 +74,7 @@ loadContent(path: string, storage?: LocalStorage): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | | path | string | 是 | 设置加载页面的路径。 | -| storage | [LocalStorage](../../quick-start/arkts-localstorage.md) | 否 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。 | +| storage | [LocalStorage](../../quick-start/arkts-localstorage.md) | 否 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。默认为空。 | **错误码:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md index 15bc8eed451e45318577a284976516647700288e..b1281ba65585366991ad7b0ac31d7671e675180e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md @@ -23,7 +23,7 @@ import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbili | 名称 | 类型 | 可读 | 可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | -| context10+ | [ExtensionContext](js-apis-inner-application-extensionContext.md) | 是 | 否 |表示数据共享扩展能力上下文。继承自[ExtensionContext] | +| context10+ | [ExtensionContext](js-apis-inner-application-extensionContext.md) | 是 | 否 |表示数据共享扩展能力上下文。 | ## onCreate diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-formHost.md b/zh-cn/application-dev/reference/apis/js-apis-application-formHost.md index da1915673114f6f644f9902849a2640a7e33f339..56d6b6b52c51047bb83c26a9ad002abe8f52f246 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-formHost.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-formHost.md @@ -159,7 +159,7 @@ releaseForm(formId: string, isReleaseCache?: boolean): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | -------------- | ------ | ---- | ----------- | | formId | string | 是 | 卡片标识。 | -| isReleaseCache | boolean | 否 | 是否释放缓存。 | +| isReleaseCache | boolean | 否 | 是否释放缓存,默认为false。 | **返回值:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md b/zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md index 1ba196163e899e17570669926f7fa29aee8c846f..86e9a86c6b7e7432aafb350fe0e4b91fa67a176b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md @@ -721,19 +721,21 @@ pushUrl(options: router.RouterOptions): Promise<void> ```ts let router = uiContext.getRouter(); -try { - router.pushUrl({ - url: 'pages/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] - } +router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] } + } +}) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); }) -} catch (err) { - console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); -} ``` ### pushUrl @@ -817,19 +819,21 @@ pushUrl(options: router.RouterOptions, mode: router.RouterMode): Promise<void ```ts let router = uiContext.getRouter(); -try { - router.pushUrl({ - url: 'pages/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] - } +router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] } - }, router.RouterMode.Standard) -} catch (err) { - console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); -} + } +}, router.RouterMode.Standard) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + }) ``` ### pushUrl @@ -912,16 +916,18 @@ replaceUrl(options: router.RouterOptions): Promise<void> ```ts let router = uiContext.getRouter(); -try { - router.replaceUrl({ - url: 'pages/detail', - params: { - data1: 'message' - } +router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message' + } +}) + .then(() => { + // success + }) + .catch(err => { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); }) -} catch (err) { - console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); -} ``` ### replaceUrl @@ -1089,19 +1095,21 @@ pushNamedRoute(options: router.NamedRouterOptions): Promise<void> ```ts let router = uiContext.getRouter(); -try { - router.pushNamedRoute({ - name: 'myPage', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] - } +router.pushNamedRoute({ + name: 'myPage', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] } + } +}) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); }) -} catch (err) { - console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); -} ``` ### pushNamedRoute @@ -1184,19 +1192,21 @@ pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): Pro ```ts let router = uiContext.getRouter(); -try { - router.pushNamedRoute({ - name: 'myPage', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] - } +router.pushNamedRoute({ + name: 'myPage', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] } - }, router.RouterMode.Standard) -} catch (err) { - console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); -} + } +}, router.RouterMode.Standard) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); + }) ``` ### pushNamedRoute @@ -1279,16 +1289,18 @@ replaceNamedRoute(options: router.NamedRouterOptions): Promise<void> ```ts let router = uiContext.getRouter(); -try { - router.replaceNamedRoute({ - name: 'myPage', - params: { - data1: 'message' - } +router.replaceNamedRoute({ + name: 'myPage', + params: { + data1: 'message' + } +}) + .then(() => { + // success + }) + .catch(err => { + console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); }) -} catch (err) { - console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); -} ``` ### replaceNamedRoute @@ -1368,16 +1380,18 @@ replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): ```ts let router = uiContext.getRouter(); -try { - router.replaceNamedRoute({ - name: 'myPage', - params: { - data1: 'message' - } - }, router.RouterMode.Standard) -} catch (err) { - console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); -} +router.replaceNamedRoute({ + name: 'myPage', + params: { + data1: 'message' + } +}, router.RouterMode.Standard) + .then(() => { + // success + }) + .catch(err => { + console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); + }) ``` ### replaceNamedRoute @@ -1531,13 +1545,15 @@ showAlertBeforeBackPage(options: router.EnableAlertOptions): void ```ts let router = uiContext.getRouter(); -try { - router.showAlertBeforeBackPage({ - message: 'Message Info' - }); -} catch(error) { - console.error(`showAlertBeforeBackPage failed, code is ${error.code}, message is ${error.message}`); -} +router.showAlertBeforeBackPage({ + message: 'Message Info' +}); + .then(() => { + // success + }) + .catch(err => { + console.error(`showAlertBeforeBackPage failed, code is ${error.code}, message is ${error.message}`); + }) ``` ### hideAlertBeforeBackPage diff --git a/zh-cn/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md b/zh-cn/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md index ed1e4495a6798ce533d8f1a9966ff3d8ae786a3c..9ab4f8912c9090f474adbd8ee0b8e3f3e65a7720 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md @@ -17,7 +17,7 @@ import { DrawableDescriptor, LayeredDrawableDescriptor } from '@ohos.arkui.drawa ## DrawableDescriptor.constructor constructor() -创建DrawableDescriptor或LayeredDrawableDescriptor对象。对象构造需要使用全球化接口[getDrawableDescriptor](js-apis-resource-manager.md##getdrawabledescriptor)或[getDrawableDescriptorByName](js-apis-resource-manager.md##getdrawabledescriptorbyname)。 +创建DrawableDescriptor或LayeredDrawableDescriptor对象。对象构造需要使用全球化接口[getDrawableDescriptor](js-apis-resource-manager.md#getdrawabledescriptor)或[getDrawableDescriptorByName](js-apis-resource-manager.md#getdrawabledescriptorbyname)。 **系统接口:** 此接口为系统接口。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md b/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md index c79cffc135cb0c15dd6a41eb6173246f81c3fe6c..398738d8a0b7eeda5e8ea8ee176ad6f6bbc38bec 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md @@ -426,14 +426,15 @@ on(type: 'locationChange', request: LocationRequest, callback: Callback<Locat ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let requestInfo = {'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX, 'scenario': geoLocationManager.LocationRequestScenario.UNSET, 'timeInterval': 1, 'distanceInterval': 0, 'maxAccuracy': 0}; - let locationChange = (location) => { + import BusinessError from "@ohos.base"; + let requestInfo:geoLocationManager.LocationRequest = {'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX, 'scenario': geoLocationManager.LocationRequestScenario.UNSET, 'timeInterval': 1, 'distanceInterval': 0, 'maxAccuracy': 0}; + let locationChange = (location:geoLocationManager.Location):void => { console.log('locationChanger: data: ' + JSON.stringify(location)); }; try { geoLocationManager.on('locationChange', requestInfo, locationChange); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -470,15 +471,16 @@ off(type: 'locationChange', callback?: Callback<Location>): void ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let requestInfo = {'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX, 'scenario': geoLocationManager.LocationRequestScenario.UNSET, 'timeInterval': 1, 'distanceInterval': 0, 'maxAccuracy': 0}; - let locationChange = (location) => { - console.log('locationChanger: data: ' + JSON.stringify(location)); + import BusinessError from "@ohos.base"; + let requestInfo:geoLocationManager.LocationRequest = {'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX, 'scenario': geoLocationManager.LocationRequestScenario.UNSET, 'timeInterval': 1, 'distanceInterval': 0, 'maxAccuracy': 0}; + let locationChange = (location:geoLocationManager.Location):void => { + console.log('locationChanger: data: ' + JSON.stringify(location)); }; try { geoLocationManager.on('locationChange', requestInfo, locationChange); geoLocationManager.off('locationChange', locationChange); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -510,13 +512,14 @@ on(type: 'locationEnabledChange', callback: Callback<boolean>): void ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let locationEnabledChange = (state) => { + import BusinessError from "@ohos.base"; + let locationEnabledChange = (state:boolean):void => { console.log('locationEnabledChange: ' + JSON.stringify(state)); } try { geoLocationManager.on('locationEnabledChange', locationEnabledChange); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -548,14 +551,15 @@ off(type: 'locationEnabledChange', callback?: Callback<boolean>): void; ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let locationEnabledChange = (state) => { + import BusinessError from "@ohos.base"; + let locationEnabledChange = (state:boolean):void => { console.log('locationEnabledChange: state: ' + JSON.stringify(state)); } try { geoLocationManager.on('locationEnabledChange', locationEnabledChange); geoLocationManager.off('locationEnabledChange', locationEnabledChange); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -564,7 +568,7 @@ off(type: 'locationEnabledChange', callback?: Callback<boolean>): void; on(type: 'cachedGnssLocationsChange', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>): void; -订阅缓存GNSS定位结果上报事件。 +订阅缓存GNSS定位结果上报事件。该接口功能由gnss定位芯片提供(仅部分型号支持),如果设备无此芯片或使用的芯片型号不支持该功能,则返回错误码801(Capability not supported)。 **需要权限**:ohos.permission.APPROXIMATELY_LOCATION @@ -592,14 +596,15 @@ on(type: 'cachedGnssLocationsChange', request: CachedGnssLocationsRequest, callb ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let cachedLocationsCb = (locations) => { + import BusinessError from "@ohos.base"; + let cachedLocationsCb = (locations:Array):void => { console.log('cachedGnssLocationsChange: locations: ' + JSON.stringify(locations)); } - let requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; + let requestInfo:geoLocationManager.CachedGnssLocationsRequest = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; try { geoLocationManager.on('cachedGnssLocationsChange', requestInfo, cachedLocationsCb); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -608,7 +613,7 @@ on(type: 'cachedGnssLocationsChange', request: CachedGnssLocationsRequest, callb off(type: 'cachedGnssLocationsChange', callback?: Callback<Array<Location>>): void; -取消订阅缓存GNSS定位结果上报事件。 +取消订阅缓存GNSS定位结果上报事件。该接口功能由gnss定位芯片提供(仅部分型号支持),如果设备无此芯片或使用的芯片型号不支持该功能,则返回错误码801(Capability not supported)。 **需要权限**:ohos.permission.APPROXIMATELY_LOCATION @@ -635,15 +640,16 @@ off(type: 'cachedGnssLocationsChange', callback?: Callback<Array<Location& ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let cachedLocationsCb = (locations) => { + import BusinessError from "@ohos.base"; + let cachedLocationsCb = (locations:Array):void => { console.log('cachedGnssLocationsChange: locations: ' + JSON.stringify(locations)); } - let requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; + let requestInfo:geoLocationManager.CachedGnssLocationsRequest = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; try { geoLocationManager.on('cachedGnssLocationsChange', requestInfo, cachedLocationsCb); geoLocationManager.off('cachedGnssLocationsChange'); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -678,14 +684,15 @@ on(type: 'satelliteStatusChange', callback: Callback<SatelliteStatusInfo>) ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let gnssStatusCb = (satelliteStatusInfo) => { + import BusinessError from "@ohos.base"; + let gnssStatusCb = (satelliteStatusInfo:geoLocationManager.SatelliteStatusInfo):void => { console.log('satelliteStatusChange: ' + JSON.stringify(satelliteStatusInfo)); } try { geoLocationManager.on('satelliteStatusChange', gnssStatusCb); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -721,14 +728,15 @@ off(type: 'satelliteStatusChange', callback?: Callback<SatelliteStatusInfo> ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let gnssStatusCb = (satelliteStatusInfo) => { + import BusinessError from "@ohos.base"; + let gnssStatusCb = (satelliteStatusInfo:geoLocationManager.SatelliteStatusInfo):void => { console.log('satelliteStatusChange: ' + JSON.stringify(satelliteStatusInfo)); } try { geoLocationManager.on('satelliteStatusChange', gnssStatusCb); geoLocationManager.off('satelliteStatusChange', gnssStatusCb); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -764,14 +772,15 @@ on(type: 'nmeaMessage', callback: Callback<string>): void; ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let nmeaCb = (str) => { + import BusinessError from "@ohos.base"; + let nmeaCb = (str:string):void => { console.log('nmeaMessage: ' + JSON.stringify(str)); } try { geoLocationManager.on('nmeaMessage', nmeaCb ); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -807,7 +816,8 @@ off(type: 'nmeaMessage', callback?: Callback<string>): void; ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let nmeaCb = (str) => { + import BusinessError from "@ohos.base"; + let nmeaCb = (str:string):void => { console.log('nmeaMessage: ' + JSON.stringify(str)); } @@ -815,7 +825,7 @@ off(type: 'nmeaMessage', callback?: Callback<string>): void; geoLocationManager.on('nmeaMessage', nmeaCb); geoLocationManager.off('nmeaMessage', nmeaCb); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -824,7 +834,7 @@ off(type: 'nmeaMessage', callback?: Callback<string>): void; on(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): void; -添加一个围栏,并订阅地理围栏事件。 +添加一个围栏,并订阅地理围栏事件。该接口功能由gnss定位芯片提供(仅部分型号支持),如果设备无此芯片或使用的芯片型号不支持该功能,则返回错误码801(Capability not supported)。 **需要权限**:ohos.permission.APPROXIMATELY_LOCATION @@ -853,8 +863,9 @@ on(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): vo ```ts import geoLocationManager from '@ohos.geoLocationManager'; import wantAgent from '@ohos.app.ability.wantAgent'; - - let wantAgentInfo = { + import BusinessError from "@ohos.base"; + + let wantAgentInfo:wantAgent.WantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", @@ -868,11 +879,11 @@ on(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): vo }; wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - let requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; + let requestInfo:geoLocationManager.GeofenceRequest = {'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; try { geoLocationManager.on('gnssFenceStatusChange', requestInfo, wantAgentObj); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } }); ``` @@ -882,7 +893,7 @@ on(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): vo off(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): void; -删除一个围栏,并取消订阅该围栏事件。 +删除一个围栏,并取消订阅该围栏事件。该接口功能由gnss定位芯片提供(仅部分型号支持),如果设备无此芯片或使用的芯片型号不支持该功能,则返回错误码801(Capability not supported)。 **需要权限**:ohos.permission.APPROXIMATELY_LOCATION @@ -911,8 +922,9 @@ off(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): v ```ts import geoLocationManager from '@ohos.geoLocationManager'; import wantAgent from '@ohos.app.ability.wantAgent'; + import BusinessError from "@ohos.base"; - let wantAgentInfo = { + let wantAgentInfo:wantAgent.WantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", @@ -926,12 +938,12 @@ off(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): v }; wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - let requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; + let requestInfo:geoLocationManager.GeofenceRequest = {'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}};; try { geoLocationManager.on('gnssFenceStatusChange', requestInfo, wantAgentObj); geoLocationManager.off('gnssFenceStatusChange', requestInfo, wantAgentObj); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } }); ``` @@ -966,14 +978,15 @@ on(type: 'countryCodeChange', callback: Callback<CountryCode>): void; ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let callback = (code) => { + import BusinessError from "@ohos.base"; + let callback = (code:geoLocationManager.CountryCode):void => { console.log('countryCodeChange: ' + JSON.stringify(code)); } try { geoLocationManager.on('countryCodeChange', callback); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -1006,7 +1019,8 @@ off(type: 'countryCodeChange', callback?: Callback<CountryCode>): void; ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let callback = (code) => { + import BusinessError from "@ohos.base"; + let callback = (code:geoLocationManager.CountryCode):void => { console.log('countryCodeChange: ' + JSON.stringify(code)); } @@ -1014,7 +1028,7 @@ off(type: 'countryCodeChange', callback?: Callback<CountryCode>): void; geoLocationManager.on('countryCodeChange', callback); geoLocationManager.off('countryCodeChange', callback); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -1051,14 +1065,15 @@ on(type: 'locatingRequiredDataChange', config: LocatingRequiredDataConfig, callb ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let callback = (code) => { + import BusinessError from "@ohos.base"; + let callback = (code:Array):void => { console.log('locatingRequiredDataChange: ' + JSON.stringify(code)); } - let config = {'type': 1, 'needStartScan': true, 'scanInterval': 10000}; + let config:geoLocationManager.LocatingRequiredDataConfig = {'type': 1, 'needStartScan': true, 'scanInterval': 10000}; try { geoLocationManager.on('locatingRequiredDataChange', config, callback); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -1090,15 +1105,16 @@ off(type: 'locatingRequiredDataChange', callback?: Callback<Array<Locating ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let callback = (code) => { + import BusinessError from "@ohos.base"; + let callback = (code:Array):void => { console.log('locatingRequiredDataChange: ' + JSON.stringify(code)); } - let config = {'type': 1, 'needStartScan': true, 'scanInterval': 10000}; + let config:geoLocationManager.LocatingRequiredDataConfig = {'type': 1, 'needStartScan': true, 'scanInterval': 10000}; try { geoLocationManager.on('locatingRequiredDataChange', config, callback); geoLocationManager.off('locatingRequiredDataChange', callback); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -1134,8 +1150,9 @@ getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<L ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let requestInfo = {'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX, 'scenario': geoLocationManager.LocationRequestScenario.UNSET,'maxAccuracy': 0}; - let locationChange = (err, location) => { + import BusinessError from "@ohos.base"; + let requestInfo:geoLocationManager.CurrentLocationRequest = {'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX, 'scenario': geoLocationManager.LocationRequestScenario.UNSET,'maxAccuracy': 0}; + let locationChange = (err:BusinessError.BusinessError, location:geoLocationManager.Location):void => { if (err) { console.log('locationChanger: err=' + JSON.stringify(err)); } @@ -1147,7 +1164,7 @@ getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<L try { geoLocationManager.getCurrentLocation(requestInfo, locationChange); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -1181,7 +1198,8 @@ getCurrentLocation(callback: AsyncCallback<Location>): void; ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let locationChange = (err, location) => { + import BusinessError from "@ohos.base"; + let locationChange = (err:BusinessError.BusinessError, location:geoLocationManager.Location) => { if (err) { console.log('locationChanger: err=' + JSON.stringify(err)); } @@ -1193,7 +1211,7 @@ getCurrentLocation(callback: AsyncCallback<Location>): void; try { geoLocationManager.getCurrentLocation(locationChange); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -1233,16 +1251,17 @@ getCurrentLocation(request?: CurrentLocationRequest): Promise<Location> ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let requestInfo = {'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX, 'scenario': geoLocationManager.LocationRequestScenario.UNSET,'maxAccuracy': 0}; + import BusinessError from "@ohos.base"; + let requestInfo:geoLocationManager.CurrentLocationRequest = {'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX, 'scenario': geoLocationManager.LocationRequestScenario.UNSET,'maxAccuracy': 0}; try { geoLocationManager.getCurrentLocation(requestInfo).then((result) => { console.log('current location: ' + JSON.stringify(result)); }) - .catch((error) => { + .catch((error:number) => { console.log('promise, getCurrentLocation: error=' + JSON.stringify(error)); }); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -1277,10 +1296,11 @@ getLastLocation(): Location ```ts import geoLocationManager from '@ohos.geoLocationManager'; + import BusinessError from "@ohos.base"; try { let location = geoLocationManager.getLastLocation(); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -1311,10 +1331,11 @@ isLocationEnabled(): boolean ```ts import geoLocationManager from '@ohos.geoLocationManager'; + import BusinessError from "@ohos.base"; try { let locationEnabled = geoLocationManager.isLocationEnabled(); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -1349,6 +1370,7 @@ enableLocation(callback: AsyncCallback<void>): void; ```ts import geoLocationManager from '@ohos.geoLocationManager'; + import BusinessError from "@ohos.base"; try { geoLocationManager.enableLocation((err, data) => { if (err) { @@ -1356,7 +1378,7 @@ enableLocation(callback: AsyncCallback<void>): void; } }); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -1391,15 +1413,16 @@ enableLocation(): Promise<void> ```ts import geoLocationManager from '@ohos.geoLocationManager'; + import BusinessError from "@ohos.base"; try { geoLocationManager.enableLocation().then((result) => { console.log('promise, enableLocation succeed'); }) - .catch((error) => { + .catch((error:number) => { console.log('promise, enableLocation: error=' + JSON.stringify(error)); }); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -1427,10 +1450,11 @@ disableLocation(): void; ```ts import geoLocationManager from '@ohos.geoLocationManager'; + import BusinessError from "@ohos.base"; try { geoLocationManager.disableLocation(); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -1463,7 +1487,8 @@ getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; + import BusinessError from "@ohos.base"; + let reverseGeocodeRequest:geoLocationManager.ReverseGeoCodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; try { geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { if (err) { @@ -1474,7 +1499,7 @@ getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback } }); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -1512,16 +1537,17 @@ getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<Ge ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; + import BusinessError from "@ohos.base"; + let reverseGeocodeRequest:geoLocationManager.ReverseGeoCodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; try { geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest).then((data) => { console.log('getAddressesFromLocation: ' + JSON.stringify(data)); }) - .catch((error) => { + .catch((error:number) => { console.log('promise, getAddressesFromLocation: error=' + JSON.stringify(error)); }); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -1554,7 +1580,8 @@ getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback< ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; + import BusinessError from "@ohos.base"; + let geocodeRequest:geoLocationManager.GeoCodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; try { geoLocationManager.getAddressesFromLocationName(geocodeRequest, (err, data) => { if (err) { @@ -1565,7 +1592,7 @@ getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback< } }); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -1603,16 +1630,17 @@ getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAd ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; + import BusinessError from "@ohos.base"; + let geocodeRequest:geoLocationManager.GeoCodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; try { geoLocationManager.getAddressesFromLocationName(geocodeRequest).then((result) => { console.log('getAddressesFromLocationName: ' + JSON.stringify(result)); }) - .catch((error) => { + .catch((error:number) => { console.log('promise, getAddressesFromLocationName: error=' + JSON.stringify(error)); }); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -1642,10 +1670,11 @@ isGeocoderAvailable(): boolean; ```ts import geoLocationManager from '@ohos.geoLocationManager'; + import BusinessError from "@ohos.base"; try { let isAvailable = geoLocationManager.isGeocoderAvailable(); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -1654,7 +1683,7 @@ isGeocoderAvailable(): boolean; getCachedGnssLocationsSize(callback: AsyncCallback<number>): void; -获取GNSS芯片缓存位置的个数。 +获取GNSS芯片缓存位置的个数。该接口功能由gnss定位芯片提供(仅部分型号支持),如果设备无此芯片或使用的芯片型号不支持该功能,则返回错误码801(Capability not supported)。 **需要权限**:ohos.permission.APPROXIMATELY_LOCATION @@ -1679,6 +1708,7 @@ getCachedGnssLocationsSize(callback: AsyncCallback<number>): void; ```ts import geoLocationManager from '@ohos.geoLocationManager'; + import BusinessError from "@ohos.base"; try { geoLocationManager.getCachedGnssLocationsSize((err, size) => { if (err) { @@ -1689,7 +1719,7 @@ getCachedGnssLocationsSize(callback: AsyncCallback<number>): void; } }); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -1698,7 +1728,7 @@ getCachedGnssLocationsSize(callback: AsyncCallback<number>): void; getCachedGnssLocationsSize(): Promise<number>; -获取GNSS芯片缓存位置的个数。 +获取GNSS芯片缓存位置的个数。该接口功能由gnss定位芯片提供(仅部分型号支持),如果设备无此芯片或使用的芯片型号不支持该功能,则返回错误码801(Capability not supported)。 **需要权限**:ohos.permission.APPROXIMATELY_LOCATION @@ -1723,15 +1753,16 @@ getCachedGnssLocationsSize(): Promise<number>; ```ts import geoLocationManager from '@ohos.geoLocationManager'; + import BusinessError from "@ohos.base"; try { geoLocationManager.getCachedGnssLocationsSize().then((result) => { console.log('promise, getCachedGnssLocationsSize: ' + JSON.stringify(result)); }) - .catch((error) => { + .catch((error:number) => { console.log('promise, getCachedGnssLocationsSize: error=' + JSON.stringify(error)); }); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -1740,7 +1771,7 @@ getCachedGnssLocationsSize(): Promise<number>; flushCachedGnssLocations(callback: AsyncCallback<void>): void; -读取并清空GNSS芯片所有缓存位置。 +读取并清空GNSS芯片所有缓存位置。该接口功能由gnss定位芯片提供(仅部分型号支持),如果设备无此芯片或使用的芯片型号不支持该功能,则返回错误码801(Capability not supported)。 **需要权限**:ohos.permission.APPROXIMATELY_LOCATION @@ -1766,6 +1797,7 @@ flushCachedGnssLocations(callback: AsyncCallback<void>): void; ```ts import geoLocationManager from '@ohos.geoLocationManager'; + import BusinessError from "@ohos.base"; try { geoLocationManager.flushCachedGnssLocations((err, result) => { if (err) { @@ -1773,7 +1805,7 @@ flushCachedGnssLocations(callback: AsyncCallback<void>): void; } }); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -1782,7 +1814,7 @@ flushCachedGnssLocations(callback: AsyncCallback<void>): void; flushCachedGnssLocations(): Promise<void>; -读取并清空GNSS芯片所有缓存位置。 +读取并清空GNSS芯片所有缓存位置。该接口功能由gnss定位芯片提供(仅部分型号支持),如果设备无此芯片或使用的芯片型号不支持该功能,则返回错误码801(Capability not supported)。 **需要权限**:ohos.permission.APPROXIMATELY_LOCATION @@ -1808,15 +1840,16 @@ flushCachedGnssLocations(): Promise<void>; ```ts import geoLocationManager from '@ohos.geoLocationManager'; + import BusinessError from "@ohos.base"; try { geoLocationManager.flushCachedGnssLocations().then((result) => { console.log('promise, flushCachedGnssLocations success'); }) - .catch((error) => { + .catch((error:number) => { console.log('promise, flushCachedGnssLocations: error=' + JSON.stringify(error)); }); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -1848,7 +1881,8 @@ sendCommand(command: LocationCommand, callback: AsyncCallback<void>): void ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let requestInfo = {'scenario': 0x301, 'command': "command_1"}; + import BusinessError from "@ohos.base"; + let requestInfo:geoLocationManager.LocationCommand = {'scenario': 0x301, 'command': "command_1"}; try { geoLocationManager.sendCommand(requestInfo, (err, result) => { if (err) { @@ -1856,7 +1890,7 @@ sendCommand(command: LocationCommand, callback: AsyncCallback<void>): void } }); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -1893,16 +1927,17 @@ sendCommand(command: LocationCommand): Promise<void>; ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let requestInfo = {'scenario': 0x301, 'command': "command_1"}; + import BusinessError from "@ohos.base"; + let requestInfo:geoLocationManager.LocationCommand = {'scenario': 0x301, 'command': "command_1"}; try { geoLocationManager.sendCommand(requestInfo).then((result) => { console.log('promise, sendCommand success'); }) - .catch((error) => { + .catch((error:number) => { console.log('promise, sendCommand: error=' + JSON.stringify(error)); }); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -1934,6 +1969,7 @@ getCountryCode(callback: AsyncCallback<CountryCode>): void; ```ts import geoLocationManager from '@ohos.geoLocationManager'; + import BusinessError from "@ohos.base"; try { geoLocationManager.getCountryCode((err, result) => { if (err) { @@ -1944,7 +1980,7 @@ getCountryCode(callback: AsyncCallback<CountryCode>): void; } }); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -1976,16 +2012,17 @@ getCountryCode(): Promise<CountryCode>; ```ts import geoLocationManager from '@ohos.geoLocationManager'; + import BusinessError from "@ohos.base"; try { geoLocationManager.getCountryCode() .then((result) => { console.log('promise, getCountryCode: result=' + JSON.stringify(result)); }) - .catch((error) => { + .catch((error:number) => { console.log('promise, getCountryCode: error=' + JSON.stringify(error)); }); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -2013,10 +2050,11 @@ enableLocationMock(): void; ```ts import geoLocationManager from '@ohos.geoLocationManager'; + import BusinessError from "@ohos.base"; try { geoLocationManager.enableLocationMock(); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -2044,10 +2082,11 @@ disableLocationMock(): void; ```ts import geoLocationManager from '@ohos.geoLocationManager'; + import BusinessError from "@ohos.base"; try { geoLocationManager.disableLocationMock(); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -2083,19 +2122,20 @@ setMockedLocations(config: LocationMockConfig): void; ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let locations = [ + import BusinessError from "@ohos.base"; + let locations:Array = [ {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} ]; - let config = {"timeInterval": 5, "locations": locations}; + let config:geoLocationManager.LocationMockConfig = {"timeInterval": 5, "locations": locations}; try { geoLocationManager.enableLocationMock(); geoLocationManager.setMockedLocations(config); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -2122,10 +2162,11 @@ enableReverseGeocodingMock(): void; ```ts import geoLocationManager from '@ohos.geoLocationManager'; + import BusinessError from "@ohos.base"; try { geoLocationManager.enableReverseGeocodingMock(); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -2152,10 +2193,11 @@ disableReverseGeocodingMock(): void; ```ts import geoLocationManager from '@ohos.geoLocationManager'; + import BusinessError from "@ohos.base"; try { geoLocationManager.disableReverseGeocodingMock(); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -2190,18 +2232,19 @@ setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>): v ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let mockInfos = [ - {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, + import BusinessError from "@ohos.base"; + let mockInfos:Array = [ + {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "isFromMock": true}}, ]; try { geoLocationManager.enableReverseGeocodingMock(); geoLocationManager.setReverseGeocodingMockInfo(mockInfos); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -2240,10 +2283,11 @@ isLocationPrivacyConfirmed(type: LocationPrivacyType): boolean; ```ts import geoLocationManager from '@ohos.geoLocationManager'; + import BusinessError from "@ohos.base"; try { let isConfirmed = geoLocationManager.isLocationPrivacyConfirmed(1); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -2279,10 +2323,11 @@ setLocationPrivacyConfirmStatus(type: LocationPrivacyType, isConfirmed: boolean) ```ts import geoLocationManager from '@ohos.geoLocationManager'; + import BusinessError from "@ohos.base"; try { geoLocationManager.setLocationPrivacyConfirmStatus(1, true); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` @@ -2323,15 +2368,16 @@ getLocatingRequiredData(config: LocatingRequiredDataConfig): Promise<Array< ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let config = {'type': 1, 'needStartScan': true, 'scanInterval': 10000}; + import BusinessError from "@ohos.base"; + let config:geoLocationManager.LocatingRequiredDataConfig = {'type': 1, 'needStartScan': true, 'scanInterval': 10000}; try { geoLocationManager.getLocatingRequiredData(config).then((result) => { console.log('getLocatingRequiredData return: ' + JSON.stringify(result)); }) - .catch((error) => { + .catch((error:number) => { console.log('promise, getLocatingRequiredData: error=' + JSON.stringify(error)); }); } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); + console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message); } ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-geolocation.md b/zh-cn/application-dev/reference/apis/js-apis-geolocation.md index 1e7eccc4c18451a0c1521c7d0b47c344e586d8fd..9729d1682a75e37a4c557d7204ea66432da41a38 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-geolocation.md +++ b/zh-cn/application-dev/reference/apis/js-apis-geolocation.md @@ -68,8 +68,8 @@ on(type: 'locationChange', request: LocationRequest, callback: Callback<Locat ```ts import geolocation from '@ohos.geolocation'; - let requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; - let locationChange = (location) => { + let requestInfo:geolocation.LocationRequest = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; + let locationChange = (location:geolocation.Location):void => { console.log('locationChanger: data: ' + JSON.stringify(location)); }; geolocation.on('locationChange', requestInfo, locationChange); @@ -101,8 +101,8 @@ off(type: 'locationChange', callback?: Callback<Location>): void ```ts import geolocation from '@ohos.geolocation'; - let requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; - let locationChange = (location) => { + let requestInfo:geolocation.LocationRequest = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; + let locationChange = (location:geolocation.Location):void => { console.log('locationChanger: data: ' + JSON.stringify(location)); }; geolocation.on('locationChange', requestInfo, locationChange); @@ -135,7 +135,7 @@ on(type: 'locationServiceState', callback: Callback<boolean>): void ```ts import geolocation from '@ohos.geolocation'; - let locationServiceState = (state) => { + let locationServiceState = (state:boolean):void => { console.log('locationServiceState: ' + JSON.stringify(state)); } geolocation.on('locationServiceState', locationServiceState); @@ -167,7 +167,7 @@ off(type: 'locationServiceState', callback?: Callback<boolean>): void; ```ts import geolocation from '@ohos.geolocation'; - let locationServiceState = (state) => { + let locationServiceState = (state:boolean):void => { console.log('locationServiceState: state: ' + JSON.stringify(state)); } geolocation.on('locationServiceState', locationServiceState); @@ -202,10 +202,10 @@ on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, ca ```ts import geolocation from '@ohos.geolocation'; - let cachedLocationsCb = (locations) => { + let cachedLocationsCb = (locations:Array):void => { console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); } - let requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; + let requestInfo:geolocation.CachedGnssLocationsRequest = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; geolocation.on('cachedGnssLocationsReporting', requestInfo, cachedLocationsCb); ``` @@ -236,10 +236,10 @@ off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Locati ```ts import geolocation from '@ohos.geolocation'; - let cachedLocationsCb = (locations) => { + let cachedLocationsCb = (locations:Array):void => { console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); } - let requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; + let requestInfo:geolocation.CachedGnssLocationsRequest = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; geolocation.on('cachedGnssLocationsReporting', requestInfo, cachedLocationsCb); geolocation.off('cachedGnssLocationsReporting'); ``` @@ -271,7 +271,7 @@ on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>): voi ```ts import geolocation from '@ohos.geolocation'; - let gnssStatusCb = (satelliteStatusInfo) => { + let gnssStatusCb = (satelliteStatusInfo:geolocation.SatelliteStatusInfo):void => { console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); } geolocation.on('gnssStatusChange', gnssStatusCb); @@ -303,7 +303,7 @@ off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>): v ```ts import geolocation from '@ohos.geolocation'; - let gnssStatusCb = (satelliteStatusInfo) => { + let gnssStatusCb = (satelliteStatusInfo:geolocation.SatelliteStatusInfo) => { console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); } geolocation.on('gnssStatusChange', gnssStatusCb); @@ -337,7 +337,7 @@ on(type: 'nmeaMessageChange', callback: Callback<string>): void; ```ts import geolocation from '@ohos.geolocation'; - let nmeaCb = (str) => { + let nmeaCb = (str:string):void => { console.log('nmeaMessageChange: ' + JSON.stringify(str)); } geolocation.on('nmeaMessageChange', nmeaCb ); @@ -370,7 +370,7 @@ off(type: 'nmeaMessageChange', callback?: Callback<string>): void; ```ts import geolocation from '@ohos.geolocation'; - let nmeaCb = (str) => { + let nmeaCb = (str:string):void => { console.log('nmeaMessageChange: ' + JSON.stringify(str)); } geolocation.on('nmeaMessageChange', nmeaCb); @@ -406,7 +406,7 @@ on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; import geolocation from '@ohos.geolocation'; import wantAgent from '@ohos.app.ability.wantAgent'; - let wantAgentInfo = { + let wantAgentInfo:wantAgent.WantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", @@ -420,7 +420,7 @@ on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; }; wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - let requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; + let requestInfo:geolocation.GeofenceRequest = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; geolocation.on('fenceStatusChange', requestInfo, wantAgentObj); }); ``` @@ -454,7 +454,7 @@ off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; import geolocation from '@ohos.geolocation'; import wantAgent from '@ohos.app.ability.wantAgent'; - let wantAgentInfo = { + let wantAgentInfo:wantAgent.WantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", @@ -468,7 +468,7 @@ off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; }; wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - let requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; + let requestInfo:geolocation.GeofenceRequest = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; geolocation.on('fenceStatusChange', requestInfo, wantAgentObj); geolocation.off('fenceStatusChange', requestInfo, wantAgentObj); }); @@ -499,8 +499,9 @@ getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<L ```ts import geolocation from '@ohos.geolocation'; - let requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; - let locationChange = (err, location) => { + import BusinessError from "@ohos.base" + let requestInfo:geolocation.CurrentLocationRequest = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; + let locationChange = (err:BusinessError.BusinessError, location:geolocation.Location) => { if (err) { console.log('locationChanger: err=' + JSON.stringify(err)); } @@ -536,7 +537,8 @@ getCurrentLocation(callback: AsyncCallback<Location>): void ```ts import geolocation from '@ohos.geolocation'; - let locationChange = (err, location) => { + import BusinessError from "@ohos.base" + let locationChange = (err:BusinessError.BusinessError, location:geolocation.Location):void => { if (err) { console.log('locationChanger: err=' + JSON.stringify(err)); } @@ -578,7 +580,7 @@ getCurrentLocation(request?: CurrentLocationRequest): Promise<Location> ```ts import geolocation from '@ohos.geolocation'; - let requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; + let requestInfo:geolocation.CurrentLocationRequest = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; geolocation.getCurrentLocation(requestInfo).then((result) => { console.log('current location: ' + JSON.stringify(result)); }); @@ -863,7 +865,7 @@ getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback ```ts import geolocation from '@ohos.geolocation'; - let reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; + let reverseGeocodeRequest:geolocation.ReverseGeoCodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { if (err) { console.log('getAddressesFromLocation: err=' + JSON.stringify(err)); @@ -904,7 +906,7 @@ getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<Ge ```ts import geolocation from '@ohos.geolocation'; - let reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; + let reverseGeocodeRequest:geolocation.ReverseGeoCodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest).then((data) => { console.log('getAddressesFromLocation: ' + JSON.stringify(data)); }); @@ -935,7 +937,7 @@ getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback< ```ts import geolocation from '@ohos.geolocation'; - let geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; + let geocodeRequest:geolocation.GeoCodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => { if (err) { console.log('getAddressesFromLocationName: err=' + JSON.stringify(err)); @@ -976,7 +978,7 @@ getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAd ```ts import geolocation from '@ohos.geolocation'; - let geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; + let geocodeRequest:geolocation.GeoCodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest).then((result) => { console.log('getAddressesFromLocationName: ' + JSON.stringify(result)); }); @@ -1138,7 +1140,7 @@ sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>): v ```ts import geolocation from '@ohos.geolocation'; - let requestInfo = {'scenario': 0x301, 'command': "command_1"}; + let requestInfo:geolocation.LocationCommand = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo, (err, result) => { if (err) { console.log('sendCommand: err=' + JSON.stringify(err)); @@ -1180,7 +1182,7 @@ sendCommand(command: LocationCommand): Promise<boolean>; ```ts import geolocation from '@ohos.geolocation'; - let requestInfo = {'scenario': 0x301, 'command': "command_1"}; + let requestInfo:geolocation.LocationCommand = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo).then((result) => { console.log('promise, sendCommand: ' + JSON.stringify(result)); }); diff --git a/zh-cn/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md b/zh-cn/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md index 2c41ccc0392e70edb1e2d0c40870bf1cbbdeee6b..4effaec8436a03272f0b1bcf00e637907f374546 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md @@ -122,7 +122,7 @@ hiAppEvent.write({ | 名称 | 类型 | 必填 | 说明 | | --------- | ----------------------- | ---- | ------------------------------------------------------------ | -| domain | string | 是 | 事件领域。事件领域名称支持数字、小写字母、下划线字符,需要以小写字母开头且不能以下划线结尾,长度非空且不超过32个字符。 | +| domain | string | 是 | 事件领域。事件领域名称支持数字、小写字母、下划线字符,需要以小写字母开头且不能以下划线结尾,长度非空且不超过16个字符。 | | name | string | 是 | 事件名称。事件名称支持数字、小写字母、下划线字符,需要以小写字母开头且不能以下划线结尾,长度非空且不超过48个字符。 | | eventType | [EventType](#eventtype) | 是 | 事件类型。 | | params | object | 是 | 事件参数对象,每个事件参数包括参数名和参数值,其规格定义如下:
- 参数名为string类型,只支持数字、小写字母、下划线字符,需要以小写字母开头且不能以下划线结尾,长度非空且不超过16个字符。
- 参数值支持string、number、boolean、数组类型,string类型参数长度需在8*1024个字符以内,超出会做丢弃处理;number类型参数取值需在Number.MIN_SAFE_INTEGER~Number.MAX_SAFE_INTEGER范围内,超出可能会产生不确定值;数组类型参数中的元素类型只能全为string、number、boolean中的一种,且元素个数需在100以内,超出会做丢弃处理。
- 参数个数需在32个以内,超出的参数会做丢弃处理。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md index 39523a3d373ad9adfa860cf4f5e4fdc37c6e5454..f6228d8323df87d711f8388f83361f4ea0f518d5 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md @@ -28,7 +28,7 @@ import missionManager from '@ohos.app.ability.missionManager'; **示例:** ```ts - import ElementName from '@ohos.bundle'; + import ElementName from '@ohos.bundleManager'; import image from '@ohos.multimedia.image'; import missionManager from '@ohos.app.ability.missionManager'; diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationCommonDef.md b/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationCommonDef.md index bf63991b7f61dd39a9a1b0a24d81a97de8f952d7..98d38d2cd4c4d38d2fe7e93f59de8d24076da832 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationCommonDef.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationCommonDef.md @@ -13,5 +13,5 @@ BundleOption模块为指定应用的包信息。 | 名称 | 类型 | 必填 | 说明 | | ------ | ------ | ------ | ------ | | bundle | string | 是 | 应用的包信息。 | -| uid | number | 否 | 用户ID。 | +| uid | number | 否 | 用户ID,默认为0。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-media.md b/zh-cn/application-dev/reference/apis/js-apis-media.md index 6ead1b2144048a03a7acf751c7cf4785acecc76b..f339a93812313e2774c026b58e8098996c54b93f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-media.md +++ b/zh-cn/application-dev/reference/apis/js-apis-media.md @@ -2542,16 +2542,16 @@ avRecorder.off('error'); | 名称 | 类型 | 必填 | 说明 | | ---------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | -| audioBitrate | number | 否 | 音频编码比特率,选择音频录制时必填。 | -| audioChannels | number | 否 | 音频采集声道数,选择音频录制时必填。 | +| audioBitrate | number | 否 | 音频编码比特率,选择音频录制时必填,支持范围[8000 - 384000]。 | +| audioChannels | number | 否 | 音频采集声道数,选择音频录制时必填,支持范围[1 - 2]。 | | audioCodec | [CodecMimeType](#codecmimetype8) | 否 | 音频编码格式,选择音频录制时必填。当前仅支持AUDIO_AAC。 | -| audioSampleRate | number | 否 | 音频采样率,选择音频录制时必填。 | +| audioSampleRate | number | 否 | 音频采样率,选择音频录制时必填,支持范围[8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 96000]。 | | fileFormat | [ContainerFormatType](#containerformattype8) | 是 | 文件的容器格式,必要参数。 | -| videoBitrate | number | 否 | 视频编码比特率,选择视频录制时必填。 | -| videoCodec | [CodecMimeType](#codecmimetype8) | 否 | 视频编码格式,选择视频录制时必填。需要查询设备支持的编码能力(包括编码格式,分辨率大小等)。 | -| videoFrameWidth | number | 否 | 视频帧的宽,选择视频录制时必填。 | -| videoFrameHeight | number | 否 | 视频帧的高,选择视频录制时必填。 | -| videoFrameRate | number | 否 | 视频帧率,选择视频录制时必填。 | +| videoBitrate | number | 否 | 视频编码比特率,选择视频录制时必填,支持范围[1 - 3000000]。 | +| videoCodec | [CodecMimeType](#codecmimetype8) | 否 | 视频编码格式,选择视频录制时必填。当前仅支持VIDEO_MPEG4。 | +| videoFrameWidth | number | 否 | 视频帧的宽,选择视频录制时必填,支持范围[2 - 1920]。 | +| videoFrameHeight | number | 否 | 视频帧的高,选择视频录制时必填,支持范围[2 - 1080]。 | +| videoFrameRate | number | 否 | 视频帧率,选择视频录制时必填,支持范围[1 - 30]。 | ## AudioSourceType9+ diff --git a/zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md b/zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md index a40b423ad211ffb8ab7e75be25ba563740ce567a..7d9fc61be1811d0976b0747fce52701cc107206e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md +++ b/zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md @@ -28,7 +28,7 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallbac | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------- | ---- | ------------------------------------------ | | iface | string | 是 | 网络接口名 | -| ic | [InterfaceConfiguration](#interfaceconfiguration) | 是 | 要设置的网络接口配置信息 | +| ic | [InterfaceConfiguration](#interfaceconfiguration9) | 是 | 要设置的网络接口配置信息 | | callback | AsyncCallback\ | 是 | 回调函数,成功无返回,失败返回对应错误码。 | **错误码:** @@ -55,12 +55,7 @@ ethernet.setIfaceConfig("eth0", { route: "192.168.xx.xxx", gateway: "192.168.xx.xxx", netMask: "255.255.255.0", - dnsServers: "1.1.1.1", - httpProxy: { - host: "180.89.xx.xx", - port: 8080, - exclusionList: {"example.com","192.168.0.1"} - } + dnsServers: "1.1.1.1" }, (error) => { if (error) { console.log("setIfaceConfig callback error = " + JSON.stringify(error)); @@ -87,7 +82,7 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------------------------------------------- | ---- | ------------------------ | | iface | string | 是 | 接口名 | -| ic | [InterfaceConfiguration](#interfaceconfiguration) | 是 | 要设置的网络接口配置信息 | +| ic | [InterfaceConfiguration](#interfaceconfiguration9) | 是 | 要设置的网络接口配置信息 | **返回值:** @@ -119,12 +114,7 @@ ethernet.setIfaceConfig("eth0", { route: "192.168.xx.xxx", gateway: "192.168.xx.xxx", netMask: "255.255.255.0", - dnsServers: "1.1.1.1", - httpProxy: { - host: "180.89.xx.xx", - port: 8080, - exclusionList: {"example.com","192.168.0.1"} - } + dnsServers: "1.1.1.1" }).then(() => { console.log("setIfaceConfig promise ok "); }).catch(error => { diff --git a/zh-cn/application-dev/reference/apis/js-apis-net-mdns.md b/zh-cn/application-dev/reference/apis/js-apis-net-mdns.md index b259fb04fd9b3bb78bd013bcf8427bb9d61c1556..9f16bb0babbe49b977d19deaf9c6bfa0302ab66e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-net-mdns.md +++ b/zh-cn/application-dev/reference/apis/js-apis-net-mdns.md @@ -63,7 +63,7 @@ let localServiceInfo = { }] } -mdns.addLocalService(context, localServiceInfo, function (error, data) { +mdns.addLocalService(context, localServiceInfo, (error: BusinessError, data: Data) => { console.log(JSON.stringify(error)); console.log(JSON.stringify(data)); }); @@ -72,14 +72,39 @@ mdns.addLocalService(context, localServiceInfo, function (error, data) { Stage模型示例: ```ts +// 构造单例对象 +export class GlobalContext { + private constructor() {} + private static instance: GlobalContext; + private _objects = new Map(); + + public static getContext(): GlobalContext { + if (!GlobalContext.instance) { + GlobalContext.instance = new GlobalContext(); + } + return GlobalContext.instance; + } + + getObject(value: string): Object | undefined { + return this._objects.get(value); + } + + setObject(key: string, objectClass: Object): void { + this._objects.set(key, objectClass); + } + +} + // 获取context import UIAbility from '@ohos.app.ability.UIAbility'; +import { GlobalContext } from '../GlobalContext'; class EntryAbility extends UIAbility { + value:number = 0; onWindowStageCreate(windowStage){ - globalThis.context = this.context; + GlobalContext.getContext().setObject("value", this.value); } } -let context = globalThis.context; +let context = GlobalContext.getContext().getObject("value"); let localServiceInfo = { serviceType: "_print._tcp", @@ -94,7 +119,7 @@ let localServiceInfo = { }] } -mdns.addLocalService(context, localServiceInfo, function (error, data) { +mdns.addLocalService(context, localServiceInfo, (error: BusinessError, data: Data) => { console.log(JSON.stringify(error)); console.log(JSON.stringify(data)); }); @@ -157,7 +182,7 @@ let localServiceInfo = { }] } -mdns.addLocalService(context, localServiceInfo).then(function (data) { +mdns.addLocalService(context, localServiceInfo).then((data: Data) => { console.log(JSON.stringify(data)); }); ``` @@ -167,12 +192,15 @@ Stage模型示例: ```ts // 获取context import UIAbility from '@ohos.app.ability.UIAbility'; +//参考addLocalService 构造单例对象 +import { GlobalContext } from '../GlobalContext'; class EntryAbility extends UIAbility { + value:number = 0; onWindowStageCreate(windowStage){ - globalThis.context = this.context; + GlobalContext.getContext().setObject("value", this.value); } } -let context = globalThis.context; +let context = GlobalContext.getContext().getObject("value"); let localServiceInfo = { serviceType: "_print._tcp", @@ -187,7 +215,7 @@ let localServiceInfo = { }] } -mdns.addLocalService(context, localServiceInfo).then(function (data) { +mdns.addLocalService(context, localServiceInfo).then((data: Data) => { console.log(JSON.stringify(data)); }); ``` @@ -244,7 +272,7 @@ let localServiceInfo = { }] } -mdns.removeLocalService(context, localServiceInfo, function (error, data) { +mdns.removeLocalService(context, localServiceInfo, (error: BusinessError, data: Data) => { console.log(JSON.stringify(error)); console.log(JSON.stringify(data)); }); @@ -255,12 +283,15 @@ Stage模型示例: ```ts // 获取context import UIAbility from '@ohos.app.ability.UIAbility'; +//参考addLocalService 构造单例对象 +import { GlobalContext } from '../GlobalContext'; class EntryAbility extends UIAbility { + value:number = 0; onWindowStageCreate(windowStage){ - globalThis.context = this.context; + GlobalContext.getContext().setObject("value", this.value); } } -let context = globalThis.context; +let context = GlobalContext.getContext().getObject("value"); let localServiceInfo = { serviceType: "_print._tcp", @@ -275,7 +306,7 @@ let localServiceInfo = { }] } -mdns.removeLocalService(context, localServiceInfo, function (error, data) { +mdns.removeLocalService(context, localServiceInfo, (error: BusinessError, data: Data) => { console.log(JSON.stringify(error)); console.log(JSON.stringify(data)); }); @@ -338,7 +369,7 @@ let localServiceInfo = { }] } -mdns.removeLocalService(context, localServiceInfo).then(function (data) { +mdns.removeLocalService(context, localServiceInfo).then((data: Data) => { console.log(JSON.stringify(data)); }); ``` @@ -348,12 +379,15 @@ Stage模型示例: ```ts // 获取context import UIAbility from '@ohos.app.ability.UIAbility'; +//参考addLocalService 构造单例对象 +import { GlobalContext } from '../GlobalContext'; class EntryAbility extends UIAbility { + value:number = 0; onWindowStageCreate(windowStage){ - globalThis.context = this.context; + GlobalContext.getContext().setObject("value", this.value); } } -let context = globalThis.context; +let context = GlobalContext.getContext().getObject("value"); let localServiceInfo = { serviceType: "_print._tcp", @@ -368,7 +402,7 @@ let localServiceInfo = { }] } -mdns.removeLocalService(context, localServiceInfo).then(function (data) { +mdns.removeLocalService(context, localServiceInfo).then((data: Data) => { console.log(JSON.stringify(data)); }); ``` @@ -418,12 +452,15 @@ Stage模型示例: ```ts // 获取context import UIAbility from '@ohos.app.ability.UIAbility'; +//参考addLocalService 构造单例对象 +import { GlobalContext } from '../GlobalContext'; class EntryAbility extends UIAbility { + value:number = 0; onWindowStageCreate(windowStage){ - globalThis.context = this.context; + GlobalContext.getContext().setObject("value", this.value); } } -let context = globalThis.context; +let context = GlobalContext.getContext().getObject("value"); let serviceType = "_print._tcp"; let discoveryService = mdns.createDiscoveryService(context, serviceType); @@ -481,7 +518,7 @@ let localServiceInfo = { }] } -mdns.resolveLocalService(context, localServiceInfo, function (error, data) { +mdns.resolveLocalService(context, localServiceInfo, (error: BusinessError, data: Data) => { console.log(JSON.stringify(error)); console.log(JSON.stringify(data)); }); @@ -492,12 +529,15 @@ Stage模型示例: ```ts // 获取context import UIAbility from '@ohos.app.ability.UIAbility'; +//参考addLocalService 构造单例对象 +import { GlobalContext } from '../GlobalContext'; class EntryAbility extends UIAbility { + value:number = 0; onWindowStageCreate(windowStage){ - globalThis.context = this.context; + GlobalContext.getContext().setObject("value", this.value); } } -let context = globalThis.context; +let context = GlobalContext.getContext().getObject("value"); let localServiceInfo = { serviceType: "_print._tcp", @@ -512,7 +552,7 @@ let localServiceInfo = { }] } -mdns.resolveLocalService(context, localServiceInfo, function (error, data) { +mdns.resolveLocalService(context, localServiceInfo, (error: BusinessError, data: Data) => { console.log(JSON.stringify(error)); console.log(JSON.stringify(data)); }); @@ -575,7 +615,7 @@ let localServiceInfo = { }] } -mdns.resolveLocalService(context, localServiceInfo).then(function (data) { +mdns.resolveLocalService(context, localServiceInfo).then((data: Data) => { console.log(JSON.stringify(data)); }); ``` @@ -585,12 +625,15 @@ Stage模型示例: ```ts // 获取context import UIAbility from '@ohos.app.ability.UIAbility'; +//参考addLocalService 构造单例对象 +import { GlobalContext } from '../GlobalContext'; class EntryAbility extends UIAbility { + value:number = 0; onWindowStageCreate(windowStage){ - globalThis.context = this.context; + GlobalContext.getContext().setObject("value", this.value); } } -let context = globalThis.context; +let context = GlobalContext.getContext().getObject("value"); let localServiceInfo = { serviceType: "_print._tcp", @@ -605,7 +648,7 @@ let localServiceInfo = { }] } -mdns.resolveLocalService(context, localServiceInfo).then(function (data) { +mdns.resolveLocalService(context, localServiceInfo).then((data: Data) => { console.log(JSON.stringify(data)); }); ``` @@ -639,12 +682,15 @@ Stage模型示例: ```ts // 获取context import UIAbility from '@ohos.app.ability.UIAbility'; +//参考addLocalService 构造单例对象 +import { GlobalContext } from '../GlobalContext'; class EntryAbility extends UIAbility { + value:number = 0; onWindowStageCreate(windowStage){ - globalThis.context = this.context; + GlobalContext.getContext().setObject("value", this.value); } } -let context = globalThis.context; +let context = GlobalContext.getContext().getObject("value"); let serviceType = "_print._tcp"; let discoveryService = mdns.createDiscoveryService(context, serviceType); discoveryService.startSearchingMDNS(); @@ -676,12 +722,15 @@ Stage模型示例: ```ts // 获取context import UIAbility from '@ohos.app.ability.UIAbility'; +//参考addLocalService 构造单例对象 +import { GlobalContext } from '../GlobalContext'; class EntryAbility extends UIAbility { + value:number = 0; onWindowStageCreate(windowStage){ - globalThis.context = this.context; + GlobalContext.getContext().setObject("value", this.value); } } -let context = globalThis.context; +let context = GlobalContext.getContext().getObject("value"); let serviceType = "_print._tcp"; let discoveryService = mdns.createDiscoveryService(context, serviceType); discoveryService.stopSearchingMDNS(); @@ -706,12 +755,12 @@ on(type: 'discoveryStart', callback: Callback<{serviceInfo: LocalServiceInfo, er ```js // 参考mdns.createDiscoveryService -let context = globalThis.context; +let context = GlobalContext.getContext().getObject("value"); let serviceType = "_print._tcp"; let discoveryService = mdns.createDiscoveryService(context, serviceType); discoveryService.startSearchingMDNS(); -discoveryService.on('discoveryStart', (data) => { +discoveryService.on('discoveryStart', (data: Data) => { console.log(JSON.stringify(data)); }); @@ -720,7 +769,7 @@ discoveryService.stopSearchingMDNS(); ### off('discoveryStart')10+ -off(type: 'discoveryStart', callback?: Callback<{ serviceInfo: LocalServiceInfo, errorCode?: MdnsError }>): void; +off(type: 'discoveryStart', callback?: Callback<{ serviceInfo: LocalServiceInfo, errorCode?: MdnsError }>): void 取消开启监听mDNS服务的通知。 @@ -731,24 +780,24 @@ off(type: 'discoveryStart', callback?: Callback<{ serviceInfo: LocalServiceInfo, | 参数名 | 类型 | 必填 | 说明 | |-------------|--------------|-----------|-----------------------------------------------------| | type | string | 是 |取消订阅的事件,固定为'discoveryStart'。
discoveryStart:开始搜索局域网内的mDNS服务事件。 | -| callback | Callback<{serviceInfo: [LocalServiceInfo](#localserviceinfo), errorCode?: [MdnsError](#mdnserror)}> | 是 | mDNS服务的信息和事件错误信息。 | +| callback | Callback<{serviceInfo: [LocalServiceInfo](#localserviceinfo), errorCode?: [MdnsError](#mdnserror)}> | 否 | mDNS服务的信息和事件错误信息。 | **示例:** ```js // 参考mdns.createDiscoveryService -let context = globalThis.context; +let context = GlobalContext.getContext().getObject("value"); let serviceType = "_print._tcp"; let discoveryService = mdns.createDiscoveryService(context, serviceType); discoveryService.startSearchingMDNS(); -discoveryService.on('discoveryStart', (data) => { +discoveryService.on('discoveryStart', (data: Data) => { console.log(JSON.stringify(data)); }); discoveryService.stopSearchingMDNS(); -discoveryService.off('discoveryStart', (data) => { +discoveryService.off('discoveryStart', (data: Data) => { console.log(JSON.stringify(data)); }); ``` @@ -772,12 +821,12 @@ on(type: 'discoveryStop', callback: Callback<{serviceInfo: LocalServiceInfo, err ```js // 参考mdns.createDiscoveryService -let context = globalThis.context; +let context = GlobalContext.getContext().getObject("value"); let serviceType = "_print._tcp"; let discoveryService = mdns.createDiscoveryService(context, serviceType); discoveryService.startSearchingMDNS(); -discoveryService.on('discoveryStop', (data) => { +discoveryService.on('discoveryStop', (data: Data) => { console.log(JSON.stringify(data)); }); @@ -786,7 +835,7 @@ discoveryService.stopSearchingMDNS(); ### off('discoveryStop')10+ -off(type: 'discoveryStop', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MdnsError}>): void +off(type: 'discoveryStop', callback?: Callback<{ serviceInfo: LocalServiceInfo, errorCode?: MdnsError }>): void 取消订阅停止监听mDNS服务的通知。 @@ -797,24 +846,24 @@ off(type: 'discoveryStop', callback: Callback<{serviceInfo: LocalServiceInfo, er | 参数名 | 类型 | 必填 | 说明 | |-------------|--------------|-----------|-----------------------------------------------------| | type | string | 是 |取消订阅的事件'discoveryStop'。
discoveryStop:停止搜索局域网内的mDNS服务事件。 | -| callback | Callback<{serviceInfo: [LocalServiceInfo](#localserviceinfo), errorCode?: [MdnsError](#mdnserror)}> | 是 | mDNS服务的信息和事件错误信息。 | +| callback | Callback<{serviceInfo: [LocalServiceInfo](#localserviceinfo), errorCode?: [MdnsError](#mdnserror)}> | 否 | mDNS服务的信息和事件错误信息。 | **示例:** ```js // 参考mdns.createDiscoveryService -let context = globalThis.context; +let context = GlobalContext.getContext().getObject("value"); let serviceType = "_print._tcp"; let discoveryService = mdns.createDiscoveryService(context, serviceType); discoveryService.startSearchingMDNS(); -discoveryService.on('discoveryStop', (data) => { +discoveryService.on('discoveryStop', (data: Data) => { console.log(JSON.stringify(data)); }); discoveryService.stopSearchingMDNS(); -discoveryService.off('discoveryStop', (data) => { +discoveryService.off('discoveryStop', (data: Data) => { console.log(JSON.stringify(data)); }); ``` @@ -838,12 +887,12 @@ on(type: 'serviceFound', callback: Callback\): void ```js // 参考mdns.createDiscoveryService -let context = globalThis.context; +let context = GlobalContext.getContext().getObject("value"); let serviceType = "_print._tcp"; let discoveryService = mdns.createDiscoveryService(context, serviceType); discoveryService.startSearchingMDNS(); -discoveryService.on('serviceFound', (data) => { +discoveryService.on('serviceFound', (data: Data) => { console.log(JSON.stringify(data)); }); @@ -852,7 +901,7 @@ discoveryService.stopSearchingMDNS(); ### off('serviceFound')10+ -off(type: 'serviceFound', callback: Callback\): void +off(type: 'serviceFound', callback?: Callback\): void 取消订阅发现mDNS服务的通知。 @@ -863,24 +912,24 @@ off(type: 'serviceFound', callback: Callback\): void | 参数名 | 类型 | 必填 | 说明 | |-------------|--------------|-----------|-----------------------------------------------------| | type | string | 是 |取消订阅的事件,固定为'serviceFound'。
serviceFound:发现mDNS服务事件。 | -| callback | Callback<[LocalServiceInfo](#localserviceinfo)> | 是 | mDNS服务的信息。 | +| callback | Callback<[LocalServiceInfo](#localserviceinfo)> | 否 | mDNS服务的信息。 | **示例:** ```js // 参考mdns.createDiscoveryService -let context = globalThis.context; +let context = GlobalContext.getContext().getObject("value"); let serviceType = "_print._tcp"; let discoveryService = mdns.createDiscoveryService(context, serviceType); discoveryService.startSearchingMDNS(); -discoveryService.on('serviceFound', (data) => { +discoveryService.on('serviceFound', (data: Data) => { console.log(JSON.stringify(data)); }); discoveryService.stopSearchingMDNS(); -discoveryService.off('serviceFound', (data) => { +discoveryService.off('serviceFound', (data: Data) => { console.log(JSON.stringify(data)); }); ``` @@ -904,12 +953,12 @@ on(type: 'serviceLost', callback: Callback\): void ```js // 参考mdns.createDiscoveryService -let context = globalThis.context; +let context = GlobalContext.getContext().getObject("value"); let serviceType = "_print._tcp"; let discoveryService = mdns.createDiscoveryService(context, serviceType); discoveryService.startSearchingMDNS(); -discoveryService.on('serviceLost', (data) => { +discoveryService.on('serviceLost', (data: Data) => { console.log(JSON.stringify(data)); }); @@ -918,7 +967,7 @@ discoveryService.stopSearchingMDNS(); ### off('serviceLost')10+ -off(type: 'serviceLost', callback: Callback\): void +off(type: 'serviceLost', callback?: Callback\): void 取消订阅移除mDNS服务的通知。 @@ -929,24 +978,24 @@ off(type: 'serviceLost', callback: Callback\): void | 参数名 | 类型 | 必填 | 说明 | |-------------|--------------|-----------|-----------------------------------------------------| | type | string | 是 |取消订阅的事件,固定为'serviceLost'。
serviceLost:移除mDNS服务事件。 | -| callback | Callback<[LocalServiceInfo](#localserviceinfo)> | 是 | mDNS服务的信息。 | +| callback | Callback<[LocalServiceInfo](#localserviceinfo)> | 否 | mDNS服务的信息。 | **示例:** ```js // 参考mdns.createDiscoveryService -let context = globalThis.context; +let context = GlobalContext.getContext().getObject("value"); let serviceType = "_print._tcp"; let discoveryService = mdns.createDiscoveryService(context, serviceType); discoveryService.startSearchingMDNS(); -discoveryService.on('serviceLost', (data) => { +discoveryService.on('serviceLost', (data: Data) => { console.log(JSON.stringify(data)); }); discoveryService.stopSearchingMDNS(); -discoveryService.off('serviceLost', (data) => { +discoveryService.off('serviceLost', (data: Data) => { console.log(JSON.stringify(data)); }); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-net-statistics.md b/zh-cn/application-dev/reference/apis/js-apis-net-statistics.md index 210ae339b766efc56b3418cc86449cfec2f20d1e..f6b148d6041b02964cd872c15ee21c7a00be06d4 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-net-statistics.md +++ b/zh-cn/application-dev/reference/apis/js-apis-net-statistics.md @@ -708,7 +708,7 @@ getTrafficStatsByIface(ifaceInfo: IfaceInfo, callback: AsyncCallback\ { + statistics.getTrafficStatsByIface((ifaceInfo), (error, statsInfo) => { console.log(JSON.stringify(error)) console.log("getTrafficStatsByIface bytes of received = " + JSON.stringify(statsInfo.rxBytes)); console.log("getTrafficStatsByIface bytes of sent = " + JSON.stringify(statsInfo.txBytes)); @@ -761,7 +761,7 @@ getTrafficStatsByIface(ifaceInfo: IfaceInfo): Promise\; endTime: 16859485670 } - statistics.getTrafficStatsByIface().then(function (statsInfo) { + statistics.getTrafficStatsByIface(ifaceInfo).then(function (statsInfo) { console.log("getTrafficStatsByIface bytes of received = " + JSON.stringify(statsInfo.rxBytes)); console.log("getTrafficStatsByIface bytes of sent = " + JSON.stringify(statsInfo.txBytes)); console.log("getTrafficStatsByIface packets of received = " + JSON.stringify(statsInfo.rxPackets)); @@ -814,7 +814,7 @@ getTrafficStatsByUid(uidInfo: UidInfo, callback: AsyncCallback\): uid: 20010037 } - statistics.getTrafficStatsByUid(uidInfo), (error, statsInfo) => { + statistics.getTrafficStatsByUid((uidInfo), (error, statsInfo) => { console.log(JSON.stringify(error)) console.log("getTrafficStatsByUid bytes of received = " + JSON.stringify(statsInfo.rxBytes)); console.log("getTrafficStatsByUid bytes of sent = " + JSON.stringify(statsInfo.txBytes)); diff --git a/zh-cn/application-dev/reference/apis/js-apis-net-vpn.md b/zh-cn/application-dev/reference/apis/js-apis-net-vpn.md index 2d7b20c3ef4447d585df1539741496e77ac23b02..4a0cb7fc9b815fba4d1c88fa8d7a169c69963f4e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-net-vpn.md +++ b/zh-cn/application-dev/reference/apis/js-apis-net-vpn.md @@ -43,16 +43,16 @@ createVpnConnection(context: AbilityContext): VpnConnection Stage模型示例: ```ts -// 获取context -import UIAbility from '@ohos.app.ability.UIAbility'; -class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - globalThis.context = this.context; + // 获取context + import UIAbility from '@ohos.app.ability.UIAbility'; + class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + globalThis.context = this.context; + } } -} -let context = globalThis.context; -VpnConnection = vpn.createVpnConnection(context); -console.info("vpn onInit: " + JSON.stringify(VpnConnection)); + let context = globalThis.context; + let VpnConnection = vpn.createVpnConnection(context); + console.info("vpn onInit: " + JSON.stringify(VpnConnection)); ``` ## VpnConnection @@ -96,6 +96,14 @@ setUp(config: VpnConfig, callback: AsyncCallback\): void **示例:** ```js + import UIAbility from '@ohos.app.ability.UIAbility'; + class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + globalThis.context = this.context; + } + } + let VpnConnection = vpn.createVpnConnection(globalThis.context); + let config = { addresses: [{ address: { @@ -160,6 +168,14 @@ setUp(config: VpnConfig): Promise\ **示例:** ```js + import UIAbility from '@ohos.app.ability.UIAbility'; + class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + globalThis.context = this.context; + } + } + let VpnConnection = vpn.createVpnConnection(globalThis.context); + let config = { addresses: [{ address: { @@ -220,6 +236,14 @@ protect(socketFd: number, callback: AsyncCallback\): void ```js import socket from "@ohos.net.socket"; + import UIAbility from '@ohos.app.ability.UIAbility'; + class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + globalThis.context = this.context; + } + } + let VpnConnection = vpn.createVpnConnection(globalThis.context); + var tcp = socket.constructTCPSocketInstance(); tcp.bind({ address: "0.0.0.0", @@ -283,6 +307,14 @@ protect(socketFd: number): Promise\ ```js import socket from "@ohos.net.socket"; + import UIAbility from '@ohos.app.ability.UIAbility'; + class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + globalThis.context = this.context; + } + } + let VpnConnection = vpn.createVpnConnection(globalThis.context); + var tcp = socket.constructTCPSocketInstance(); tcp.bind({ address: "0.0.0.0", @@ -339,6 +371,13 @@ destroy(callback: AsyncCallback\): void **示例:** ```js + import UIAbility from '@ohos.app.ability.UIAbility'; + class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + globalThis.context = this.context; + } + } + let VpnConnection = vpn.createVpnConnection(globalThis.context); VpnConnection.destroy((error) => { console.info(JSON.stringify(error)); }) @@ -376,6 +415,13 @@ destroy(): Promise\ **示例:** ```js + import UIAbility from '@ohos.app.ability.UIAbility'; + class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + globalThis.context = this.context; + } + } + let VpnConnection = vpn.createVpnConnection(globalThis.context); VpnConnection.destroy().then(() => { console.info("destroy success.") }).catch(err => { diff --git a/zh-cn/application-dev/reference/apis/js-apis-notification.md b/zh-cn/application-dev/reference/apis/js-apis-notification.md index 12d12966b90dbc4b7901324066251e1ecfd2152e..2b0f10675a41329c8aa0947abfa07fa9d811eff2 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-notification.md +++ b/zh-cn/application-dev/reference/apis/js-apis-notification.md @@ -74,7 +74,7 @@ publish(request: NotificationRequest): Promise\ ```js // 通知Request对象 let notificationRequest = { - notificationId: 1, + id: 1, content: { contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { @@ -161,7 +161,7 @@ publish(request: NotificationRequest, userId: number): Promise\ ```js let notificationRequest = { - notificationId: 1, + id: 1, content: { contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { @@ -225,7 +225,7 @@ cancel(id: number, label?: string): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | -------- | | id | number | 是 | 通知ID。 | -| label | string | 否 | 通知标签。 | +| label | string | 否 | 通知标签,默认为空。 | **示例:** @@ -808,7 +808,7 @@ subscribe(subscriber: NotificationSubscriber, info?: NotificationSubscribeInfo): | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------------------------- | ---- | ------------ | | subscriber | [NotificationSubscriber](js-apis-inner-notification-notificationSubscriber.md#notificationsubscriber) | 是 | 通知订阅对象。 | -| info | [NotificationSubscribeInfo](#notificationsubscribeinfo) | 否 | 通知订阅信息。 | +| info | [NotificationSubscribeInfo](#notificationsubscribeinfo) | 否 | 通知订阅信息,默认为空。 | **示例:** @@ -1668,7 +1668,7 @@ removeAll(bundle?: BundleOption): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | 否 | 指定应用的包信息。 | +| bundle | [BundleOption](#bundleoption) | 否 | 指定应用的包信息。默认为空,表示删除所有通知。 | **示例:** @@ -2872,7 +2872,7 @@ Notification.getDeviceRemindType().then((data) => { | 名称 | 类型 | 必填 | 说明 | | ------ | ------ | --- | ------ | | bundle | string | 是 | 应用的包信息。 | -| uid | number | 否 | 用户ID。 | +| uid | number | 否 | 用户ID,默认为0。 | ## NotificationKeydeprecated diff --git a/zh-cn/application-dev/reference/apis/js-apis-notificationManager.md b/zh-cn/application-dev/reference/apis/js-apis-notificationManager.md index ca406ed0ae385ee789d4a43bd27ea0dd990809d3..bc53c3be1bed101504afb5affe28fdf4802ab3c3 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-notificationManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-notificationManager.md @@ -290,7 +290,7 @@ cancel(id: number, label?: string): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | -------- | | id | number | 是 | 通知ID。 | -| label | string | 否 | 通知标签。 | +| label | string | 否 | 通知标签,默认为空。 | **错误码:** @@ -3921,7 +3921,7 @@ off(type: 'checkNotification', callback?: (checkInfo: NotificationCheckInfo) => | 参数名 | 类型 | 必填 | 说明 | | ------ | ----------------------------- | ---- | -------------- | | type | string | 是 | 回调函数类型名,固定为'checkNotification'。 | -| callback | (checkInfo: [NotificationCheckInfo](#notificationcheckinfo)) => [NotificationCheckResult](#notificationcheckresult) | 否 | 消息验证函数指针。 | +| callback | (checkInfo: [NotificationCheckInfo](#notificationcheckinfo)) => [NotificationCheckResult](#notificationcheckresult) | 否 | 消息验证函数指针,默认为空。 | **错误码:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-notificationSubscribe.md b/zh-cn/application-dev/reference/apis/js-apis-notificationSubscribe.md index 3969df3f2968d1a8226c360cb29b3e0b17c7d78b..6973568b999b87c607555b2f1f8dd60f04210c7f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-notificationSubscribe.md +++ b/zh-cn/application-dev/reference/apis/js-apis-notificationSubscribe.md @@ -134,7 +134,7 @@ subscribe(subscriber: NotificationSubscriber, info?: NotificationSubscribeInfo): | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------------------------- | ---- | ------------ | | subscriber | [NotificationSubscriber](js-apis-notification.md#notificationsubscriber) | 是 | 通知订阅对象。 | -| info | [NotificationSubscribeInfo](js-apis-notification.md#notificationsubscribeinfo) | 否 | 通知订阅信息。 | +| info | [NotificationSubscribeInfo](js-apis-notification.md#notificationsubscribeinfo) | 否 | 通知订阅信息,默认为空。 | **错误码:** @@ -632,7 +632,7 @@ removeAll(bundle?: BundleOption): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 否 | 指定应用的包信息。 | +| bundle | [BundleOption](js-apis-inner-notification-notificationCommonDef.md#bundleoption) | 否 | 指定应用的包信息。默认为空,表示删除所有通知。 | **错误码:** @@ -754,7 +754,7 @@ notificationSubscribe.removeAll(userId, removeAllCallback); | 名称 | 类型 | 必填 | 说明 | | ----- | ------ | --- | -------- | | id | number | 是 | 通知ID。 | -| label | string | 否 | 通知标签。 | +| label | string | 否 | 通知标签,默认为空。 | ## RemoveReason diff --git a/zh-cn/application-dev/reference/apis/js-apis-overlay.md b/zh-cn/application-dev/reference/apis/js-apis-overlay.md index 26c956b547cd0685f62b5e0b8079dc4eb106a446..9cd7882ca94dfe88482ce7ff782901fb1d9afefb 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-overlay.md +++ b/zh-cn/application-dev/reference/apis/js-apis-overlay.md @@ -179,7 +179,7 @@ setOverlayEnabledByBundleName(bundleName:string, moduleName:string, isEnabled: b | bundleName | string | 是 | 指定应用的bundle名称。 | | moduleName | string | 是 | 指定应用的overlay特征module的HAP名称。 | | isEnabled | boolean | 是 | 值为true表示使能,值为false表示禁用。 | -| callback | AsyncCallback\ | 是 | 回调函数。当设置指定应用的overlay module的禁用使能状态成功时,err为undefined,data为获取到的处置状态;否则为错误对象。 | +| callback | AsyncCallback\ | 是 | 回调函数。当设置指定应用的overlay module的禁用使能状态成功时,err为undefined,否则为错误对象。 | **错误码:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-permissionrequestresult.md b/zh-cn/application-dev/reference/apis/js-apis-permissionrequestresult.md index 948eb9a341774b3d717489f6b80a0136966716b5..25a6f0c8a00da59860244c7159a4b278bf6ccbe8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-permissionrequestresult.md +++ b/zh-cn/application-dev/reference/apis/js-apis-permissionrequestresult.md @@ -21,15 +21,65 @@ 通过atManager实例来获取。 **示例:** + +ArkTS语法不支持直接使用globalThis,需要通过一个单例的map来做中转。开发者需要: + +a. 在EntryAbility.ets中导入构建的单例对象GlobalThis。 + ```typescript + import { GlobalThis } from '../utils/globalThis'; // 需要根据globalThis.ets的路径自行适配 + ``` +b. 在onCreate中添加: + ```typescript + GlobalThis.getInstance().setContext('context', this.context); + ``` + +> **说明:** +> +> 由于在ts中引入ets文件会有告警提示,需要将EntryAbility.ts的文件后缀修改为EntryAbility.ets,并在module.json5中同步修改。 + +**globalThis.ets示例代码如下:** +```typescript +import common from '@ohos.app.ability.common'; + +// 构造单例对象 +export class GlobalThis { + private constructor() {} + private static instance: GlobalThis; + private _uiContexts = new Map(); + + public static getInstance(): GlobalThis { + if (!GlobalThis.instance) { + GlobalThis.instance = new GlobalThis(); + } + return GlobalThis.instance; + } + + getContext(key: string): common.UIAbilityContext | undefined { + return this._uiContexts.get(key); + } + + setContext(key: string, value: common.UIAbilityContext): void { + this._uiContexts.set(key, value); + } + + // 其他需要传递的内容依此扩展 +} +``` + ```ts +import { BusinessError } from '@ohos.base'; import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import common from '@ohos.app.ability.common'; +import { GlobalThis } from '../utils/globalThis'; + let atManager = abilityAccessCtrl.createAtManager(); try { - atManager.requestPermissionsFromUser(this.context, ["ohos.permission.CAMERA"]).then((data) => { + let context: common.UIAbilityContext = GlobalThis.getInstance().getContext('context'); + atManager.requestPermissionsFromUser(context, ["ohos.permission.CAMERA"]).then((data) => { console.info("data:" + JSON.stringify(data)); console.info("data permissions:" + data.permissions); console.info("data authResults:" + data.authResults); - }).catch((err) => { + }).catch((err: BusinessError) => { console.info("data:" + JSON.stringify(err)); }) } catch(err) { diff --git a/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md b/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md index 7698bd864cc33b7f435f145c584162ba352c769c..de9777d937b67e241c76f9aacc30d979de05922d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md @@ -8,7 +8,7 @@ ## 导入模块 -```js +```ts import privacyManager from '@ohos.privacyManager'; ``` @@ -53,14 +53,15 @@ addPermissionUsedRecord(tokenID: number, permissionName: Permissions, successCou **示例:** -```js +```ts import privacyManager from '@ohos.privacyManager'; +import { BusinessError } from '@ohos.base'; -let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId +let tokenID: number = 0; // 可以通过getApplicationInfo获取accessTokenId try { privacyManager.addPermissionUsedRecord(tokenID, 'ohos.permission.PERMISSION_USED_STATS', 1, 0).then(() => { console.log('addPermissionUsedRecord success'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log(`addPermissionUsedRecord fail, err->${JSON.stringify(err)}`); }); } catch(err) { @@ -103,12 +104,13 @@ addPermissionUsedRecord(tokenID: number, permissionName: Permissions, successCou **示例:** -```js +```ts import privacyManager from '@ohos.privacyManager'; +import { BusinessError } from '@ohos.base'; -let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId +let tokenID: number = 0; // 可以通过getApplicationInfo获取accessTokenId try { - privacyManager.addPermissionUsedRecord(tokenID, 'ohos.permission.PERMISSION_USED_STATS', 1, 0, (err, data) => { + privacyManager.addPermissionUsedRecord(tokenID, 'ohos.permission.PERMISSION_USED_STATS', 1, 0, (err: BusinessError, data: void) => { if (err) { console.log(`addPermissionUsedRecord fail, err->${JSON.stringify(err)}`); } else { @@ -156,10 +158,11 @@ getPermissionUsedRecord(request: PermissionUsedRequest): Promise<PermissionUs **示例:** -```js +```ts import privacyManager from '@ohos.privacyManager'; +import { BusinessError } from '@ohos.base'; -let request = { +let request: privacyManager.PermissionUsedRequest = { 'tokenId': 1, 'isRemote': false, 'deviceId': 'device', @@ -172,7 +175,7 @@ let request = { try { privacyManager.getPermissionUsedRecord(request).then((data) => { console.log(`getPermissionUsedRecord success, data->${JSON.stringify(data)}`); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log(`getPermissionUsedRecord fail, err->${JSON.stringify(err)}`); }); } catch(err) { @@ -211,10 +214,11 @@ getPermissionUsedRecord(request: PermissionUsedRequest, callback: AsyncCallback& **示例:** -```js +```ts import privacyManager from '@ohos.privacyManager'; +import { BusinessError } from '@ohos.base'; -let request = { +let request: privacyManager.PermissionUsedRequest = { 'tokenId': 1, 'isRemote': false, 'deviceId': 'device', @@ -225,7 +229,7 @@ let request = { 'flag':privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL, }; try { - privacyManager.getPermissionUsedRecord(request, (err, data) => { + privacyManager.getPermissionUsedRecord(request, (err: BusinessError, data: privacyManager.PermissionUsedResponse) => { if (err) { console.log(`getPermissionUsedRecord fail, err->${JSON.stringify(err)}`); } else { @@ -275,14 +279,15 @@ startUsingPermission(tokenID: number, permissionName: Permissions): Promise<v **示例:** -```js +```ts import privacyManager from '@ohos.privacyManager'; +import { BusinessError } from '@ohos.base'; -let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId +let tokenID: number = 0; // 可以通过getApplicationInfo获取accessTokenId try { privacyManager.startUsingPermission(tokenID, 'ohos.permission.PERMISSION_USED_STATS').then(() => { console.log('startUsingPermission success'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log(`startUsingPermission fail, err->${JSON.stringify(err)}`); }); } catch(err) { @@ -323,12 +328,13 @@ startUsingPermission(tokenID: number, permissionName: Permissions, callback: Asy **示例:** -```js +```ts import privacyManager from '@ohos.privacyManager'; +import { BusinessError } from '@ohos.base'; -let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId +let tokenID: number = 0; // 可以通过getApplicationInfo获取accessTokenId try { - privacyManager.startUsingPermission(tokenID, 'ohos.permission.PERMISSION_USED_STATS', (err, data) => { + privacyManager.startUsingPermission(tokenID, 'ohos.permission.PERMISSION_USED_STATS', (err: BusinessError, data: void) => { if (err) { console.log(`startUsingPermission fail, err->${JSON.stringify(err)}`); } else { @@ -378,14 +384,15 @@ stopUsingPermission(tokenID: number, permissionName: Permissions): Promise<vo **示例:** -```js +```ts import privacyManager from '@ohos.privacyManager'; +import { BusinessError } from '@ohos.base'; -let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId +let tokenID: number = 0; // 可以通过getApplicationInfo获取accessTokenId try { privacyManager.stopUsingPermission(tokenID, 'ohos.permission.PERMISSION_USED_STATS').then(() => { console.log('stopUsingPermission success'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log(`stopUsingPermission fail, err->${JSON.stringify(err)}`); }); } catch(err) { @@ -426,12 +433,13 @@ stopUsingPermission(tokenID: number, permissionName: Permissions, callback: Asyn **示例:** -```js +```ts import privacyManager from '@ohos.privacyManager'; +import { BusinessError } from '@ohos.base'; -let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId +let tokenID: number = 0; // 可以通过getApplicationInfo获取accessTokenId try { - privacyManager.stopUsingPermission(tokenID, 'ohos.permission.PERMISSION_USED_STATS', (err, data) => { + privacyManager.stopUsingPermission(tokenID, 'ohos.permission.PERMISSION_USED_STATS', (err: BusinessError, data: void) => { if (err) { console.log(`stopUsingPermission fail, err->${JSON.stringify(err)}`); } else { @@ -475,12 +483,13 @@ on(type: 'activeStateChange', permissionList: Array<Permissions>, callback **示例:** -```js -import privacyManager from '@ohos.privacyManager'; +```ts +import privacyManager, { Permissions } from '@ohos.privacyManager'; +import { BusinessError } from '@ohos.base'; -let permissionList = []; +let permissionList: Array = []; try { - privacyManager.on('activeStateChange', permissionList, (data) => { + privacyManager.on('activeStateChange', permissionList, (data: privacyManager.ActiveChangeResponse) => { console.debug('receive permission state change, data:' + JSON.stringify(data)); }); } catch(err) { @@ -519,10 +528,10 @@ off(type: 'activeStateChange', permissionList: Array<Permissions>, callbac **示例:** -```js -import privacyManager from '@ohos.privacyManager'; +```ts +import privacyManager, { Permissions } from '@ohos.privacyManager'; -let permissionList = []; +let permissionList: Array = []; try { privacyManager.off('activeStateChange', permissionList); }catch(err) { diff --git a/zh-cn/application-dev/reference/apis/js-apis-promptAction.md b/zh-cn/application-dev/reference/apis/js-apis-promptAction.md index 1da49c28f040b142fbdea6f1b12b6259696184d0..3d2a5c6c1a3b852dae553f4a49d97ee1e6fdfba2 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-promptAction.md +++ b/zh-cn/application-dev/reference/apis/js-apis-promptAction.md @@ -62,11 +62,11 @@ try { **系统能力:** SystemCapability.ArkUI.ArkUI.Full。 -| 名称 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| message | string\| [Resource](../arkui-ts/ts-types.md#resource类型)9+ | 是 | 显示的文本信息。 | -| duration | number | 否 | 默认值1500ms,取值区间:1500ms-10000ms。若小于1500ms则取默认值,若大于10000ms则取上限值10000ms。 | -| bottom | string\| number | 否 | 设置弹窗边框距离屏幕底部的位置。
默认值:80vp | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| message | string\| [Resource](../arkui-ts/ts-types.md#resource类型)9+ | 是 | 显示的文本信息。
**说明:**
默认字体为'Harmony Sans',不支持设置其他字体。 | +| duration | number | 否 | 默认值1500ms,取值区间:1500ms-10000ms。若小于1500ms则取默认值,若大于10000ms则取上限值10000ms。 | +| bottom | string\| number | 否 | 设置弹窗边框距离屏幕底部的位置。
默认值:80vp | ## promptAction.showDialog diff --git a/zh-cn/application-dev/reference/apis/js-apis-router.md b/zh-cn/application-dev/reference/apis/js-apis-router.md index 4a997321335af457371122ecd71c354f6f9e3772..a74441cf6d3972a4833f0ab4cc66e285714d3fdd 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-router.md +++ b/zh-cn/application-dev/reference/apis/js-apis-router.md @@ -51,19 +51,21 @@ pushUrl(options: RouterOptions): Promise<void> **示例:** ```ts -try { - router.pushUrl({ - url: 'pages/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] - } +router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] } + } +}) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); }) -} catch (err) { - console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); -} ``` ## router.pushUrl9+ @@ -144,19 +146,21 @@ pushUrl(options: RouterOptions, mode: RouterMode): Promise<void> **示例:** ```ts -try { - router.pushUrl({ - url: 'pages/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] - } +router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] } - }, router.RouterMode.Standard) -} catch (err) { - console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); -} + } +}, router.RouterMode.Standard) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + }) ``` ## router.pushUrl9+ @@ -237,16 +241,18 @@ replaceUrl(options: RouterOptions): Promise<void> **示例:** ```ts -try { - router.replaceUrl({ - url: 'pages/detail', - params: { - data1: 'message' - } +router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message' + } +}) + .then(() => { + // success + }) + .catch(err => { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); }) -} catch (err) { - console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); -} ``` ## router.replaceUrl9+ @@ -324,16 +330,18 @@ replaceUrl(options: RouterOptions, mode: RouterMode): Promise<void> **示例:** ```ts -try { - router.replaceUrl({ - url: 'pages/detail', - params: { - data1: 'message' - } - }, router.RouterMode.Standard) -} catch (err) { - console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); -} +router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message' + } +}, router.RouterMode.Standard) + .then(() => { + // success + }) + .catch(err => { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + }) ``` ## router.replaceUrl9+ @@ -412,19 +420,21 @@ pushNamedRoute(options: NamedRouterOptions): Promise<void> **示例:** ```ts -try { - router.pushNamedRoute({ - name: 'myPage', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] - } +router.pushNamedRoute({ + name: 'myPage', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] } + } +}) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); }) -} catch (err) { - console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); -} ``` 详细示例请参考:[UI开发-页面路由](../../ui/arkts-routing.md#命名路由) @@ -507,19 +517,21 @@ pushNamedRoute(options: NamedRouterOptions, mode: RouterMode): Promise<void&g **示例:** ```ts -try { - router.pushNamedRoute({ - name: 'myPage', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] - } +router.pushNamedRoute({ + name: 'myPage', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] } - }, router.RouterMode.Standard) -} catch (err) { - console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); -} + } +}, router.RouterMode.Standard) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); + }) ``` ## router.pushNamedRoute10+ @@ -600,16 +612,18 @@ replaceNamedRoute(options: NamedRouterOptions): Promise<void> **示例:** ```ts -try { - router.replaceNamedRoute({ - name: 'myPage', - params: { - data1: 'message' - } +router.replaceNamedRoute({ + name: 'myPage', + params: { + data1: 'message' + } +}) + .then(() => { + // success + }) + .catch(err => { + console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); }) -} catch (err) { - console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); -} ``` ## router.replaceNamedRoute10+ @@ -687,16 +701,18 @@ replaceNamedRoute(options: NamedRouterOptions, mode: RouterMode): Promise<voi **示例:** ```ts -try { - router.replaceNamedRoute({ - name: 'myPage', - params: { - data1: 'message' - } - }, router.RouterMode.Standard) -} catch (err) { - console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); -} +router.replaceNamedRoute({ + name: 'myPage', + params: { + data1: 'message' + } +}, router.RouterMode.Standard) + .then(() => { + // success + }) + .catch(err => { + console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); + }) ``` ## router.replaceNamedRoute10+ @@ -857,13 +873,15 @@ showAlertBeforeBackPage(options: EnableAlertOptions): void **示例:** ```ts -try { - router.showAlertBeforeBackPage({ - message: 'Message Info' - }); -} catch(error) { - console.error(`showAlertBeforeBackPage failed, code is ${error.code}, message is ${error.message}`); -} +router.showAlertBeforeBackPage({ + message: 'Message Info' +}) + .then(() => { + // success + }) + .catch(err => { + console.error(`showAlertBeforeBackPage failed, code is ${error.code}, message is ${error.message}`); + }) ``` ## EnableAlertOptions diff --git a/zh-cn/application-dev/reference/apis/js-apis-sensor.md b/zh-cn/application-dev/reference/apis/js-apis-sensor.md index 6b638e95a4424251ec6cee9552c936bcce64d9ae..8e1d5e6ecfc51e24b79cea50e569684e92a7eb1d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-sensor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-sensor.md @@ -3598,7 +3598,7 @@ try { ## SensorId9+ -表示要订阅或取消订阅的传感器类型。 +表示当前支持订阅或取消订阅的传感器类型。 **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor @@ -3677,16 +3677,16 @@ try { | 名称 | 类型 | 可读 | 可写 | 说明 | | --------------- | -------- | ---------------------- | ---------------------- | ---------------------- | -| sensorName | string | 是 | 是 | 传感器名称。 | -| vendorName | string | 是 | 是 | 传感器供应商。 | -| firmwareVersion | string | 是 | 是 | 传感器固件版本。 | -| hardwareVersion | string | 是 | 是 | 传感器硬件版本。 | -| sensorId | number | 是 | 是 | 传感器类型id。 | -| maxRange | number | 是 | 是 | 传感器测量范围的最大值。 | -| minSamplePeriod | number | 是 | 是 | 允许的最小采样周期。 | -| maxSamplePeriod | number | 是 | 是 | 允许的最大采样周期。 | -| precision | number | 是 | 是 | 传感器精度。 | -| power | number | 是 | 是 | 传感器功率。 | +| sensorName | string | 是 | 否 | 传感器名称。 | +| vendorName | string | 是 | 否 | 传感器供应商。 | +| firmwareVersion | string | 是 | 否 | 传感器固件版本。 | +| hardwareVersion | string | 是 | 否 | 传感器硬件版本。 | +| sensorId | number | 是 | 否 | 传感器类型id。 | +| maxRange | number | 是 | 否 | 传感器测量范围的最大值。 | +| minSamplePeriod | number | 是 | 否 | 允许的最小采样周期。 | +| maxSamplePeriod | number | 是 | 否 | 允许的最大采样周期。 | +| precision | number | 是 | 否 | 传感器精度。 | +| power | number | 是 | 否 | 传感器功率的估计值,单位:mA。 | ## ColorResponse10+ diff --git a/zh-cn/application-dev/reference/apis/js-apis-socket.md b/zh-cn/application-dev/reference/apis/js-apis-socket.md index fc79882a4eb9a58272203027f52203f21c2d407c..fd826c5fb640e8469ee7168a1201bba7aedaadde 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-socket.md +++ b/zh-cn/application-dev/reference/apis/js-apis-socket.md @@ -1262,7 +1262,7 @@ getSocketFd(callback: AsyncCallback\): void ```js import socket from "@ohos.net.socket"; - var tcp = socket.constructTCPSocketInstance(); + let tcp = socket.constructTCPSocketInstance(); let tunnelfd = 0 tcp.bind({ address: "0.0.0.0", @@ -1302,7 +1302,7 @@ getSocketFd(): Promise\ ```js import socket from "@ohos.net.socket"; - var tcp = socket.constructTCPSocketInstance(); + let tcp = socket.constructTCPSocketInstance(); let tunnelfd = 0 tcp.bind({ address: "0.0.0.0", @@ -1715,7 +1715,7 @@ listen(address: NetAddress, callback: AsyncCallback\): void | 2303109 | Bad file number. | | 2303111 | Resource temporarily unavailable try again. | | 2303198 | Address already in use. | -| 2303199 | Cannot assign requested address. | +| 2303199 | Address not available. | **示例:** @@ -1765,7 +1765,7 @@ listen(address: NetAddress): Promise\ | 2303109 | Bad file number. | | 2303111 | Resource temporarily unavailable try again. | | 2303198 | Address already in use. | -| 2303199 | Cannot assign requested address. | +| 2303199 | Address not available. | **示例:** @@ -1805,7 +1805,7 @@ getState(callback: AsyncCallback\): void | 401 | Parameter error. | | 201 | Permission denied. | | 2300002 | System internal error. | -| 2303188 | Socket operation on non-socket. | +| 2303188 | Not a socket. | **示例:** @@ -1852,7 +1852,7 @@ getState(): Promise\ | -------- | ------------------------------- | | 201 | Permission denied. | | 2300002 | System internal error. | -| 2303188 | Socket operation on non-socket. | +| 2303188 | Not a socket. | **示例:** @@ -1899,7 +1899,7 @@ setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\): void | 401 | Parameter error. | | 201 | Permission denied. | | 2300002 | System internal error. | -| 2303188 | Socket operation on non-socket. | +| 2303188 | Not a socket. | **示例:** @@ -1962,7 +1962,7 @@ setExtraOptions(options: TCPExtraOptions): Promise\ | 401 | Parameter error. | | 201 | Permission denied. | | 2300002 | System internal error. | -| 2303188 | Socket operation on non-socket. | +| 2303188 | Not a socket. | **示例:** @@ -2338,7 +2338,7 @@ getRemoteAddress(callback: AsyncCallback\): void | 401 | Parameter error. | | 201 | Permission denied. | | 2300002 | System internal error. | -| 2303188 | Socket operation on non-socket. | +| 2303188 | Not a socket. | **示例:** @@ -2380,7 +2380,7 @@ getRemoteAddress(): Promise\ | -------- | ------------------------------- | | 201 | Permission denied. | | 2300002 | System internal error. | -| 2303188 | Socket operation on non-socket. | +| 2303188 | Not a socket. | **示例:** @@ -2751,7 +2751,7 @@ getState(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | ------- | ------------------------------ | -| 2303188 | Socket operation on non-socket.| +| 2303188 | Not a socket.| | 2300002 | System internal error. | **示例:** @@ -2791,7 +2791,7 @@ getState(): Promise\ | 错误码ID | 错误信息 | | ------- | ------------------------------ | -| 2303188 | Socket operation on non-socket.| +| 2303188 | Not a socket.| | 2300002 | System internal error. | **示例:** @@ -2831,7 +2831,7 @@ setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\): void | 错误码ID | 错误信息 | | ------- | ----------------------------- | | 401 | Parameter error. | -| 2303188 | Socket operation on non-socket.| +| 2303188 | Not a socket.| | 2300002 | System internal error. | **示例:** @@ -2888,7 +2888,7 @@ setExtraOptions(options: TCPExtraOptions): Promise\ | 错误码ID | 错误信息 | | ------- | ------------------------------ | | 401 | Parameter error. | -| 2303188 | Socket operation on non-socket.| +| 2303188 | Not a socket.| | 2300002 | System internal error. | **示例:** @@ -2936,6 +2936,7 @@ on(type: 'message', callback: Callback<{message: ArrayBuffer, remoteInfo: Socket **示例:** ```js +import socket from '@ohos.net.socket'; let tls = socket.constructTLSSocketInstance(); let messageView = ''; tls.on('message', value => { @@ -2970,6 +2971,7 @@ off(type: 'message', callback?: Callback\<{message: ArrayBuffer, remoteInfo: Soc **示例:** ```js +import socket from '@ohos.net.socket'; let tls = socket.constructTLSSocketInstance(); let messageView = ''; let callback = value => { @@ -3003,6 +3005,7 @@ on(type: 'connect' | 'close', callback: Callback\): void **示例:** ```js +import socket from '@ohos.net.socket'; let tls = socket.constructTLSSocketInstance(); tls.on('connect', () => { console.log("on connect success") @@ -3033,6 +3036,7 @@ off(type: 'connect' | 'close', callback?: Callback\): void **示例:** ```js +import socket from '@ohos.net.socket'; let tls = socket.constructTLSSocketInstance(); let callback1 = () => { console.log("on connect success"); @@ -3067,6 +3071,7 @@ on(type: 'error', callback: ErrorCallback): void **示例:** ```js +import socket from '@ohos.net.socket'; let tls = socket.constructTLSSocketInstance(); tls.on('error', err => { console.log("on error, err:" + JSON.stringify(err)) @@ -3094,6 +3099,7 @@ off(type: 'error', callback?: ErrorCallback): void **示例:** ```js +import socket from '@ohos.net.socket'; let tls = socket.constructTLSSocketInstance(); let callback = err => { console.log("on error, err:" + JSON.stringify(err)); @@ -3126,10 +3132,10 @@ connect(options: TLSConnectOptions, callback: AsyncCallback\): void | 2303104 | Interrupted system call. | | 2303109 | Bad file number. | | 2303111 | Resource temporarily unavailable try again. | -| 2303188 | Socket operation on non-socket. | +| 2303188 | Not a socket. | | 2303191 | Protocol wrong type for socket. | | 2303198 | Address already in use. | -| 2303199 | Cannot assign requested address. | +| 2303199 | Address not available. | | 2303210 | Connection timed out. | | 2303501 | SSL is null. | | 2303502 | Error in tls reading. | @@ -3225,10 +3231,10 @@ connect(options: TLSConnectOptions): Promise\ | 2303104 | Interrupted system call. | | 2303109 | Bad file number. | | 2303111 | Resource temporarily unavailable try again. | -| 2303188 | Socket operation on non-socket. | +| 2303188 | Not a socket. | | 2303191 | Protocol wrong type for socket. | | 2303198 | Address already in use. | -| 2303199 | Cannot assign requested address. | +| 2303199 | Address not available. | | 2303210 | Connection timed out. | | 2303501 | SSL is null. | | 2303502 | Error in tls reading. | @@ -3316,7 +3322,7 @@ getRemoteAddress(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | ------- | ----------------------------- | -| 2303188 | Socket operation on non-socket.| +| 2303188 | Not a socket.| | 2300002 | System internal error. | **示例:** @@ -3349,7 +3355,7 @@ getRemoteAddress(): Promise\ | 错误码ID | 错误信息 | | ------- | ------------------------------ | -| 2303188 | Socket operation on non-socket.| +| 2303188 | Not a socket.| | 2300002 | System internal error. | **示例:** @@ -3937,7 +3943,7 @@ listen(options: TLSConnectOptions, callback: AsyncCallback\): void | 2303109 | Bad file number. | | 2303111 | Resource temporarily unavailable try again. | | 2303198 | Address already in use. | -| 2303199 | Cannot assign requested address. | +| 2303199 | Address not available. | | 2303501 | SSL is null. | | 2303502 | Error in tls reading. | | 2303503 | Error in tls writing | @@ -4003,7 +4009,7 @@ listen(options: TLSConnectOptions): Promise\ | 2303109 | Bad file number. | | 2303111 | Resource temporarily unavailable try again. | | 2303198 | Address already in use. | -| 2303199 | Cannot assign requested address. | +| 2303199 | Address not available. | | 2303501 | SSL is null. | | 2303502 | Error in tls reading. | | 2303503 | Error in tls writing | @@ -4061,7 +4067,7 @@ getState(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | -------- | ------------------------------- | | 401 | Parameter error. | -| 2303188 | Socket operation on non-socket. | +| 2303188 | Not a socket. | | 2300002 | System internal error. | **示例:** @@ -4121,7 +4127,7 @@ getState(): Promise\ | 错误码ID | 错误信息 | | -------- | ------------------------------- | -| 2303188 | Socket operation on non-socket. | +| 2303188 | Not a socket. | | 2300002 | System internal error. | **示例:** @@ -4183,7 +4189,7 @@ setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\): void | 错误码ID | 错误信息 | | -------- | ------------------------------- | | 401 | Parameter error. | -| 2303188 | Socket operation on non-socket. | +| 2303188 | Not a socket. | | 2300002 | System internal error. | **示例:** @@ -4258,7 +4264,7 @@ setExtraOptions(options: TCPExtraOptions): Promise\ | 错误码ID | 错误信息 | | -------- | ------------------------------- | | 401 | Parameter error. | -| 2303188 | Socket operation on non-socket. | +| 2303188 | Not a socket. | | 2300002 | System internal error. | **示例:** @@ -5066,7 +5072,7 @@ getRemoteAddress(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | -------- | ------------------------------- | | 401 | Parameter error. | -| 2303188 | Socket operation on non-socket. | +| 2303188 | Not a socket. | | 2300002 | System internal error. | **示例:** @@ -5124,7 +5130,7 @@ getRemoteAddress(): Promise\ | 错误码ID | 错误信息 | | -------- | ------------------------------- | -| 2303188 | Socket operation on non-socket. | +| 2303188 | Not a socket. | | 2300002 | System internal error. | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-thermal.md b/zh-cn/application-dev/reference/apis/js-apis-thermal.md index f3e304c00c4b3e37c31303516de651fae43090d1..21027cf5284dc2a203f47f92191e36a128e66c21 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-thermal.md +++ b/zh-cn/application-dev/reference/apis/js-apis-thermal.md @@ -129,7 +129,7 @@ subscribeThermalLevel(callback: AsyncCallback<ThermalLevel>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback<ThermalLevel> | 是 | 回调函数。AsyncCallback只返回一个参数,为热档位信息,此时可能会产生告警,可通过`// @ts-ignore`进行抑制。 | +| callback | AsyncCallback<ThermalLevel> | 是 | 回调函数。AsyncCallback只返回一个参数,为热档位信息。| **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-timer.md b/zh-cn/application-dev/reference/apis/js-apis-timer.md index bdf2ef921ee4b63d3218d82ed1a47efaa2ac2065..69a9f83235a71cfa7f1f387473a36296ce6c5c18 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-timer.md +++ b/zh-cn/application-dev/reference/apis/js-apis-timer.md @@ -10,7 +10,8 @@ setTimeout(handler: Function | string, delay?: number, ...arguments: any[]): number -设置一个定时器,该定时器在定时器到期后执行一个函数。 +设置一个定时器,该定时器在定时器到期后执行一个函数。 +该定时器在回调被执行后自动删除,或使用clearTimeout接口手动删除。 **系统能力:** SystemCapability.ArkUI.ArkUI.Full @@ -26,7 +27,7 @@ setTimeout(handler: Function | string, delay?: number, ...arguments: any[]): num | 类型 | 说明 | | -------- | -------- | -| number | 该定时器的ID。 | +| number | 该定时器的ID,为整数。 | **示例:** @@ -65,7 +66,8 @@ clearTimeout(timeoutID?: number): void setInterval(handler: Function | string, delay: number, ...arguments: any[]): number -重复调用一个函数,在每次调用之间具有固定的时间延迟。 +重复调用一个函数,在每次调用之间具有固定的时间延迟。 +删除该定时器需手动调用clearInterval接口。 **系统能力:** SystemCapability.ArkUI.ArkUI.Full @@ -81,7 +83,7 @@ setInterval(handler: Function | string, delay: number, ...arguments: any[]): num | 类型 | 说明 | | -------- | -------- | -| number | 该定时器的ID。 | +| number | 该定时器的ID,为整数。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-update.md b/zh-cn/application-dev/reference/apis/js-apis-update.md index e2aa8974228692c77c455a1276bfa002f3b8b61c..f0d8466665ac4896104a72fe08f7c71123eee101 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-update.md +++ b/zh-cn/application-dev/reference/apis/js-apis-update.md @@ -39,13 +39,6 @@ getOnlineUpdater(upgradeInfo: UpgradeInfo): Updater | ------------------- | ---- | | [Updater](#updater) | 升级对象。 | -**错误码**: - -以下的错误码的详细介绍请参见[升级错误码](../errorcodes/errorcode-update.md) - -| 错误码ID | 错误信息 | -| ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | **示例:** @@ -79,14 +72,6 @@ getRestorer(): Restorer | --------------------- | ------ | | [Restorer](#restorer) | 恢复出厂对象。 | -**错误码**: - -以下的错误码的详细介绍请参见[升级错误码](../errorcodes/errorcode-update.md) - -| 错误码ID | 错误信息 | -| ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | - **示例:** ```ts @@ -111,13 +96,6 @@ getLocalUpdater(): LocalUpdater | ----------------------------- | ------ | | [LocalUpdater](#localupdater) | 本地升级对象。 | -**错误码**: - -以下的错误码的详细介绍请参见[升级错误码](../errorcodes/errorcode-update.md) - -| 错误码ID | 错误信息 | -| ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | **示例:** @@ -153,7 +131,7 @@ checkNewVersion(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -185,7 +163,7 @@ checkNewVersion(): Promise\ | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -221,7 +199,7 @@ getNewVersionInfo(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -254,7 +232,7 @@ getNewVersionInfo(): Promise\ | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -291,7 +269,7 @@ getNewVersionDescription(versionDigestInfo: VersionDigestInfo, descriptionOption | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -342,7 +320,7 @@ getNewVersionDescription(versionDigestInfo: VersionDigestInfo, descriptionOption | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -387,7 +365,7 @@ getCurrentVersionInfo(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -421,7 +399,7 @@ getCurrentVersionInfo(): Promise\ | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -458,7 +436,7 @@ getCurrentVersionDescription(descriptionOptions: DescriptionOptions, callback: A | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -503,7 +481,7 @@ getCurrentVersionDescription(descriptionOptions: DescriptionOptions): Promise\): void | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -575,7 +553,7 @@ getTaskInfo(): Promise\ | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -611,7 +589,7 @@ download(versionDigestInfo: VersionDigestInfo, downloadOptions: DownloadOptions, | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -660,7 +638,7 @@ download(versionDigestInfo: VersionDigestInfo, downloadOptions: DownloadOptions) | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -706,7 +684,7 @@ resumeDownload(versionDigestInfo: VersionDigestInfo, resumeDownloadOptions: Resu | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -754,7 +732,7 @@ resumeDownload(versionDigestInfo: VersionDigestInfo, resumeDownloadOptions: Resu | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -799,7 +777,7 @@ pauseDownload(versionDigestInfo: VersionDigestInfo, pauseDownloadOptions: PauseD | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -847,7 +825,7 @@ pauseDownload(versionDigestInfo: VersionDigestInfo, pauseDownloadOptions: PauseD | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -892,7 +870,7 @@ upgrade(versionDigestInfo: VersionDigestInfo, upgradeOptions: UpgradeOptions, ca | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -940,7 +918,7 @@ upgrade(versionDigestInfo: VersionDigestInfo, upgradeOptions: UpgradeOptions): P | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -985,7 +963,7 @@ clearError(versionDigestInfo: VersionDigestInfo, clearOptions: ClearOptions, cal | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -1033,7 +1011,7 @@ clearError(versionDigestInfo: VersionDigestInfo, clearOptions: ClearOptions): Pr | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -1076,7 +1054,7 @@ getUpgradePolicy(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -1109,7 +1087,7 @@ getUpgradePolicy(): Promise\ | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -1145,7 +1123,7 @@ setUpgradePolicy(policy: UpgradePolicy, callback: AsyncCallback\): void | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -1188,7 +1166,7 @@ setUpgradePolicy(policy: UpgradePolicy): Promise\ | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -1227,7 +1205,7 @@ terminateUpgrade(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -1259,7 +1237,7 @@ terminateUpgrade(): Promise\ | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -1286,13 +1264,6 @@ on(eventClassifyInfo: EventClassifyInfo, taskCallback: UpgradeTaskCallback): voi | eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | 是 | 事件信息。 | | taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | 是 | 事件回调。 | -**错误码**: - -以下的错误码的详细介绍请参见[升级错误码](../errorcodes/errorcode-update.md) - -| 错误码ID | 错误信息 | -| ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | **示例:** @@ -1321,14 +1292,6 @@ off(eventClassifyInfo: EventClassifyInfo, taskCallback?: UpgradeTaskCallback): v | eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | 是 | 事件信息。 | | taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | 否 | 事件回调。 | -**错误码**: - -以下的错误码的详细介绍请参见[升级错误码](../errorcodes/errorcode-update.md) - -| 错误码ID | 错误信息 | -| ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | - **示例:** ```ts @@ -1366,7 +1329,7 @@ factoryReset(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -1398,7 +1361,7 @@ factoryReset(): Promise\ | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -1436,7 +1399,7 @@ verifyUpgradePackage(upgradeFile: UpgradeFile, certsFile: string, callback: Asyn | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -1480,7 +1443,7 @@ verifyUpgradePackage(upgradeFile: UpgradeFile, certsFile: string): Promise\, callback: Asyn | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -1555,7 +1518,7 @@ applyNewVersion(upgradeFiles: Array<[UpgradeFile](#upgradefile)>): Promise\ **说明:** > diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-appendix-enums.md b/zh-cn/application-dev/reference/arkui-ts/ts-appendix-enums.md index 76892a0d0ce6e0daea11289fb82a4a9bab9564a9..323f92fc6a60533cb5f2a3804790173cc89c79de 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-appendix-enums.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-appendix-enums.md @@ -564,24 +564,4 @@ | 名称 | 描述 | | ------- | ------------------------------------------------------------ | | DEFAULT | 默认风格,光标宽1.5vp,光标高度与文本选中底板高度和字体大小相关。 | -| INLINE | 内联输入风格。文本选中底板高度与输入框高度相同。 | - -## ImageSmoothingQuality8+ - -从API version 9开始,该接口支持在ArkTS卡片中使用。 - -| 名称 | 描述 | -| -------- | -------------- | -| low | 低画质 | -| medium | 中画质 | -| high | 高画质 | - -## CanvasDirection8+ - -从API version 9开始,该接口支持在ArkTS卡片中使用。 - -| 名称 | 描述 | -| -------- | -------------- | -| inherit | 继承canvas组件已设定的文本方向 | -| ltr | 从左往右 | -| rtl | 从右往左 | \ No newline at end of file +| INLINE | 内联输入风格。文本选中底板高度与输入框高度相同。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-button.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-button.md index c56c0a02fe2e8189cf473e3ca07ac7d4c7dcadcf..7c2ae62cd5cdf13a7b7dc45cb4820900052aa6b7 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-button.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-button.md @@ -14,7 +14,9 @@ ## 接口 -**方法1:** Button(options?: {type?: ButtonType, stateEffect?: boolean}) +### Button + +Button(options?: {type?: ButtonType, stateEffect?: boolean}) 从API version 9开始,该接口支持在ArkTS卡片中使用。 @@ -25,9 +27,11 @@ | type | ButtonType | 否 | 描述按钮显示样式。
默认值:ButtonType.Capsule | | stateEffect | boolean | 否 | 按钮按下时是否开启按压态显示效果,当设置为false时,按压效果关闭。
默认值:true
**说明:**
当开启按压态显示效果,开发者设置状态样式时,会基于状态样式设置完成后的背景色再进行颜色叠加。 | -**方法2:** Button(label?: ResourceStr, options?: { type?: ButtonType, stateEffect?: boolean }) +### Button + +Button(label?: ResourceStr, options?: { type?: ButtonType, stateEffect?: boolean }) - 使用文本内容创建相应的按钮组件,此时Button无法包含子组件。 +使用文本内容创建相应的按钮组件,此时Button无法包含子组件。 从API version 9开始,该接口支持在ArkTS卡片中使用。 @@ -36,7 +40,7 @@ | 参数名 | 参数类型 | 必填 | 参数描述 | | ------- | ----------------------------------- | ---- | ------------- | | label | [ResourceStr](ts-types.md#resourcestr) | 否 | 按钮文本内容。 | -| options | { type?: ButtonType, stateEffect?: boolean } | 否 | 见方法1参数说明。 | +| options | { type?: ButtonType, stateEffect?: boolean } | 否 | 见[Button](#button-1)参数说明。 | ## 属性 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navdestination.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navdestination.md index fd2ca1a9b280cbea25ead154b267da9ae8167e85..5f4904999aa1b210f774b06f1dad54ed25d690b8 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navdestination.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navdestination.md @@ -26,7 +26,7 @@ NavDestination() | 名称 | 参数类型 | 描述 | | ------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | -| title | string \| [CustomBuilder](ts-types.md#custombuilder8) \| [NavigationCommonTitle](ts-basic-components-navigation.md#navigationcommontitle类型说明) \| [NavigationCustomTitle](ts-basic-components-navigation.md##navigationcustomtitle类型说明) | 页面标题。
**说明:**
使用NavigationCustomTitle类型设置height高度时,titleMode属性不会生效。
字符串超长时,如果不设置副标题,先缩小再换行2行后以...截断。如果设置副标题,先缩小后以...截断。 | +| title | string \| [CustomBuilder](ts-types.md#custombuilder8) \| [NavigationCommonTitle](ts-basic-components-navigation.md#navigationcommontitle类型说明) \| [NavigationCustomTitle](ts-basic-components-navigation.md#navigationcustomtitle类型说明) | 页面标题。
**说明:**
使用NavigationCustomTitle类型设置height高度时,titleMode属性不会生效。
字符串超长时,如果不设置副标题,先缩小再换行2行后以...截断。如果设置副标题,先缩小后以...截断。 | | hideTitleBar | boolean | 是否显示标题栏。
默认值:false
true: 隐藏标题栏。
false: 显示标题栏。 | ## 事件 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navrouter.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navrouter.md index e4a9d52a930be72f90a5b18a258c79111c8bbf5e..a30bcd13c5acb228adcc75cbc0ccad1e1b8b5f20 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navrouter.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navrouter.md @@ -20,11 +20,15 @@ ## 接口 -**方法1:** NavRouter() +### NavRouter -**方法2:** NavRouter(value: RouteInfo)10+ +NavRouter() - 提供路由信息,指定点击NavRouter时,要跳转的NavDestination页面。 +### NavRouter10+ + +NavRouter(value: RouteInfo) + +提供路由信息,指定点击NavRouter时,要跳转的NavDestination页面。 **参数:** diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-richtext.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-richtext.md index f394f34b2831a18f6b4fe2c4cc1a15bbe75eedc0..f4c0cdb40525bcd37f9803fb189a757df4768ca3 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-richtext.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-richtext.md @@ -42,7 +42,7 @@ RichText(content:string) | \

--\

| 被用来定义HTML,\

定义重要等级最高的标题,\

定义重要等级最低的标题。 | \

这是一个标题\

\

这是h2标题\

| | \

\

| 定义段落。 | \

这是一个段落\

| | \
| 插入一个简单的换行符。 | \

这是一个段落\
这是换行段落\

| -| \ | 规定文本的字体、字体尺寸、字体颜色。 | \这是一段红色字体。\ | +| \ | 规定文本的字体、字体尺寸、字体颜色。在标签中font size能够设置的值只有1到7的数字,默认值是3,由于标签在HTML 4.01中不建议使用,在XHTML1.0 Strict DTD中不支持,所以不建议使用此标签,请使用CSS代替。CSS语法:\

| \这是一段红色字体。\ | | \


| 定义HTML页面中的主题变化(比如话题的转移),并显示为一条水平线。 | \

这个一个段落\

\
\

这是一个段落\

| | \\ | 用来定义图片。 | \\ | | \
\
| 常用于组合块级元素,以便通过CSS来对这些元素进行格式化。 | \
\

这是一个在div元素中的标题。\

\
| diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md index 84f8f5e504369383ec11fd690b6e46b91cbcfc38..6bd7bcedd9547118d42f5a1dfbe535818b3e2b05 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md @@ -128,7 +128,7 @@ caretPosition(value: number): void | value | number | 是 | 从字符串开始到光标所在位置的字符长度。 | ### setTextSelection10+ -setTextSelection(selectionStart: number, selectionStart: number): void +setTextSelection(selectionStart: number, selectionEnd: number): void 设置文本选择区域并高亮显示。 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md index fb808bf398665fd34d6132ef11aa11fd2395e4a0..0097cf270dbd908f1fd8954bf248343b1d0db274 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md @@ -14,7 +14,9 @@ ## 接口 -**方法1:** XComponent(value: {id: string, type: string, libraryname?: string, controller?: XComponentController}) +### XComponent + +XComponent(value: {id: string, type: string, libraryname?: string, controller?: XComponentController}) **参数:** @@ -25,7 +27,9 @@ | libraryname | string | 否 | 应用Native层编译输出动态库名称,仅XComponent类型为"surface"时有效。 | | controller | [XComponentcontroller](#xcomponentcontroller) | 否 | 给组件绑定一个控制器,通过控制器调用组件方法,仅XComponent类型为"surface"时有效。 | -**方法2:** XComponent(value: {id: string, type: XComponentType, libraryname?: string, controller?: XComponentController})10+ +### XComponent10+ + +XComponent(value: {id: string, type: XComponentType, libraryname?: string, controller?: XComponentController}) **参数:** diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md b/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md index 0eb644b0a1d4636e3c275fed02c979c1719e2929..727cd35021db9a7a85885a781b386b50d02eaafa 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md @@ -46,7 +46,7 @@ RenderingContextSettings(antialias?: boolean) | [lineCap](#linecap) | CanvasLineCap | 指定线端点的样式,可选值为:
- 'butt':线端点以方形结束。
- 'round':线端点以圆形结束。
- 'square':线端点以方形结束,该样式下会增加一个长度和线段厚度相同,宽度是线段厚度一半的矩形。
默认值:'butt'
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | [lineJoin](#linejoin) | CanvasLineJoin | 指定线段间相交的交点样式,可选值为:
- 'round':在线段相连处绘制一个扇形,扇形的圆角半径是线段的宽度。
- 'bevel':在线段相连处使用三角形为底填充, 每个部分矩形拐角独立。
- 'miter':在相连部分的外边缘处进行延伸,使其相交于一点,形成一个菱形区域,该属性可以通过设置miterLimit属性展现效果。
默认值:'miter'
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | [miterLimit](#miterlimit) | number | 设置斜接面限制值,该值指定了线条相交处内角和外角的距离。
默认值:10
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| [font](#font) | string | 设置文本绘制中的字体样式。
语法:ctx.font='font-size font-family'
- font-size(可选),指定字号和行高,单位只支持px。
- font-family(可选),指定字体系列。
语法:ctx.font='font-style font-weight font-size font-family'
- font-style(可选),用于指定字体样式,支持如下几种样式:'normal','italic'。
- font-weight(可选),用于指定字体的粗细,支持如下几种类型:'normal', 'bold', 'bolder', 'lighter', 100, 200, 300, 400, 500, 600, 700, 800, 900。
- font-size(可选),指定字号和行高,单位支持px、vp。使用时需要添加单位。
- font-family(可选),指定字体系列,支持如下几种类型:'sans-serif', 'serif', 'monospace'。
默认值:'normal normal 14px sans-serif'
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [font](#font) | string | 设置文本绘制中的字体样式。
语法:ctx.font='font-size font-family'
- font-size(可选),指定字号和行高,单位支持px和vp。
- font-family(可选),指定字体系列。
语法:ctx.font='font-style font-weight font-size font-family'
- font-style(可选),用于指定字体样式,支持如下几种样式:'normal','italic'。
- font-weight(可选),用于指定字体的粗细,支持如下几种类型:'normal', 'bold', 'bolder', 'lighter', 100, 200, 300, 400, 500, 600, 700, 800, 900。
- font-size(可选),指定字号和行高,单位支持px、vp。使用时需要添加单位。
- font-family(可选),指定字体系列,支持如下几种类型:'sans-serif', 'serif', 'monospace'。
默认值:'normal normal 14px sans-serif'
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | [textAlign](#textalign) | CanvasTextAlign | 设置文本绘制中的文本对齐方式,可选值为:
- 'left':文本左对齐。
- 'right':文本右对齐。
- 'center':文本居中对齐。
- 'start':文本对齐界线开始的地方。
- 'end':文本对齐界线结束的地方。
ltr布局模式下'start'和'left'一致,rtl布局模式下'start'和'right'一致·。
默认值:'left'
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | [textBaseline](#textbaseline) | CanvasTextBaseline | 设置文本绘制中的水平对齐方式,可选值为:
- 'alphabetic':文本基线是标准的字母基线。
- 'top':文本基线在文本块的顶部。
- 'hanging':文本基线是悬挂基线。
- 'middle':文本基线在文本块的中间。
- 'ideographic':文字基线是表意字基线;如果字符本身超出了alphabetic基线,那么ideograhpic基线位置在字符本身的底部。
- 'bottom':文本基线在文本块的底部。 与ideographic基线的区别在于ideographic基线不需要考虑下行字母。
默认值:'alphabetic'
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | [globalAlpha](#globalalpha) | number | 设置透明度,0.0为完全透明,1.0为完全不透明。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | @@ -273,7 +273,7 @@ struct MiterLimit { struct Fonts { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -282,8 +282,10 @@ struct Fonts { .backgroundColor('#ffff00') .onReady(() =>{ this.context.font = '30px sans-serif' - this.context.fillText("Hello World", 20, 60) - }) + this.context.fillText("Hello px", 20, 60) + this.context.font = '30vp sans-serif' + this.context.fillText("Hello vp", 20, 100) + }) } .width('100%') .height('100%') @@ -2923,3 +2925,78 @@ struct CanvasExample { ``` ![zh-cn_image_0000001239032419](figures/zh-cn_image_0000001239032420.png) + + +## CanvasDirection + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + +| 名称 | 描述 | +| -------- | -------------- | +| inherit | 继承canvas组件已设定的文本方向。 | +| ltr | 从左往右。 | +| rtl | 从右往左。 | + +## CanvasFillRule + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + +| 名称 | 描述 | +| -------- | -------------- | +| evenodd | 奇偶规则。 | +| nonzero | 非零规则。 | + +## CanvasLineCap + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + +| 名称 | 描述 | +| -------- | -------------- | +| butt | 线条两端为平行线,不额外扩展。 | +| round | 在线条两端延伸半个圆,直径等于线宽。 | +| square | 在线条两端延伸一个矩形,宽度等于线宽的一半,高度等于线宽。 | + +## CanvasLineJoin + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + +| 名称 | 描述 | +| -------- | -------------- | +| bevel | 在线段相连处使用三角形为底填充, 每个部分矩形拐角独立。 | +| miter | 在相连部分的外边缘处进行延伸,使其相交于一点,形成一个菱形区域,该属性可以通过设置miterLimit属性展现效果。 | +| round | 在线段相连处绘制一个扇形,扇形的圆角半径是线段的宽度。 | + +## CanvasTextAlign + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + +| 名称 | 描述 | +| -------- | -------------- | +| center | 文本居中对齐。 | +| start | 文本对齐界线开始的地方。 | +| end | 文本对齐界线结束的地方。 | +| left | 文本左对齐。 | +| right | 文本右对齐。 | + +## CanvasTextBaseline + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + +| 名称 | 描述 | +| -------- | -------------- | +| alphabetic | 文本基线是标准的字母基线。 | +| bottom | 文本基线在文本块的底部。 与ideographic基线的区别在于ideographic基线不需要考虑下行字母。 | +| hanging | 文本基线是悬挂基线。 | +| ideographic | 文字基线是表意字基线;如果字符本身超出了alphabetic基线,那么ideograhpic基线位置在字符本身的底部。 | +| middle | 文本基线在文本块的中间。 | +| top | 文本基线在文本块的顶部。 | + +## ImageSmoothingQuality + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + +| 名称 | 描述 | +| -------- | -------------- | +| low | 低画质 | +| medium | 中画质 | +| high | 高画质 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-combined-gestures.md b/zh-cn/application-dev/reference/arkui-ts/ts-combined-gestures.md index d1355645ece52650e091b68c4572ab20cc0bc6a4..a632c063c3ee555c5a102d76ef189447ea048a2c 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-combined-gestures.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-combined-gestures.md @@ -21,7 +21,7 @@ GestureGroup(mode: GestureMode, ...gesture: GestureType[]) | 名称 | 描述 | | --------- | ---------------------------------------- | -| Sequence | 顺序识别,按照手势的注册顺序识别手势,直到所有手势识别成功。当有一个手势识别失败时,所有手势识别失败。 | +| Sequence | 顺序识别,按照手势的注册顺序识别手势,直到所有手势识别成功。当有一个手势识别失败时,所有手势识别失败。
顺序识别手势组仅有最后一个手势可以响应onActionEnd。 | | Parallel | 并发识别,注册的手势同时识别,直到所有手势识别结束,手势识别互相不影响。 | | Exclusive | 互斥识别,注册的手势同时识别,若有一个手势识别成功,则结束手势识别。 | @@ -67,9 +67,6 @@ struct GestureGroupExample { this.count++ } console.info('LongPress onAction') - }) - .onActionEnd(() => { - console.info('LongPress end') }), PanGesture() .onActionStart(() => { diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md index d6c5d6129d38b8694652115f0ac3688a81ca826d..16e7d36dc0295fe069844f7c578e5b4420a01265 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md @@ -16,7 +16,7 @@ ImageBitmap(src: string) | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | ------ | -------- | ---- | ------ | ------------------------------------------------------------ | -| src | string | 是 | - | 图片的数据源
**说明:**
- ArkTS卡片上不支持`http://`等网络相关路径前缀、`datashare://`路径前缀以及`file://data/storage`路径前缀的字符串 | +| src | string | 是 | - | 图片的数据源支持本地图片。
1、string格式用于加载本地图片,例如ImageBitmap("common/images/example.jpg"),图片加载路径的起点为ets文件夹。
2、支持本地图片类型:bmp、jpg、png、svg和webp类型。
**说明:**
- ArkTS卡片上不支持`http://`等网络相关路径前缀、`datashare://`路径前缀以及`file://data/storage`路径前缀的字符串。 | @@ -24,8 +24,8 @@ ImageBitmap(src: string) | 属性 | 类型 | 描述 | | -------- | -------- | -------- | -| width | number | ImageBitmap的像素宽度,当前值为0。。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| height | number | ImageBitmap的像素高度,当前值为0。。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| width | number | ImageBitmap的像素宽度,当前值为0。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| height | number | ImageBitmap的像素高度,当前值为0。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | **示例:** diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md index 21ea39dcf2741d81522bf64077c4beb25586fb1b..edbf37ee364695748d76dea432ee89e23b985fdb 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md @@ -18,7 +18,7 @@ ## 接口 -**方法1:** Badge(value: {count: number, position?: BadgePosition, maxCount?: number, style: BadgeStyle}) +**方法1:** Badge(value: {count: number, position?: BadgePosition \| Position, maxCount?: number, style: BadgeStyle}) 创建数字标记组件。 @@ -33,7 +33,7 @@ | maxCount | number | 否 | 最大消息数,超过最大消息时仅显示maxCount+。
默认值:99
取值范围:[-2147483648,2147483647],非整数时会舍去小数部分取整数部分,如5.5取5。 | | style | [BadgeStyle](#badgestyle对象说明) | 是 | Badge组件可设置样式,支持设置文本颜色、尺寸、圆点颜色和尺寸。 | -**方法2:** Badge(value: {value: string, position?: BadgePosition, style: BadgeStyle}) +**方法2:** Badge(value: {value: string, position?: BadgePosition \| Position, style: BadgeStyle}) 根据字符串创建标记组件。 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-effectcomponent.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-effectcomponent.md new file mode 100644 index 0000000000000000000000000000000000000000..5d993f61b1c26fe03657e32c789aae6f3855133b --- /dev/null +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-effectcomponent.md @@ -0,0 +1,99 @@ +# EffectComponent + +特效合并容器组件,用于子节点特效绘制的合并,实现特效的绘制性能优化。 + +> **说明:** +> +> - 该组件从API Version 10开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> +> - 该组件为系统接口。 +> +> - 目前该组件仅支持子组件背景模糊效果的绘制合并优化。 +> +> - 在对子组件的背景模糊特效进行绘制合并时,需要将子组件的backgroundBlurStyle(BlurStyle)属性替换成useEffect(true)。 + + +## 子组件 + +可以包含子组件。 + + +## 接口 + +EffectComponent() + +创建特效绘制合并组件,用于对子组件背景模糊特效的绘制合并。 + +## 事件 + +不支持通用事件。 + +## 属性 + +支持通用属性,目前仅支持对backgroundBlurStyle属性做绘制合并优化。 + +## 示例 + +```ts +//Index.ets +@Entry +@Component +struct Index { + build() { + Stack() { + Image($r("app.media.example")) + .autoResize(true) + EffectComponent() { + Column({ space: 20 }) { + // 使用backgroundBlurStyle进行模糊绘制 + Text("Normal text with backgroundBlurStyle") + .textAlign(TextAlign.Center) + .fontSize(16) + .fontWeight(FontWeight.Medium) + .backgroundBlurStyle(BlurStyle.Thick) + .borderRadius(16) + .width('90%') + .height('48') + + // 不进行模糊绘制 + Text("Normal text without blur effect") + .textAlign(TextAlign.Center) + .fontSize(16) + .fontWeight(FontWeight.Medium) + .border({ width: 1 }) + .borderRadius(16) + .width('90%') + .height('48') + + // 使用useEffect进行模糊合并绘制,继承EffectComponent的模糊参数 + Text("Normal text with useeffcet blur 1") + .textAlign(TextAlign.Center) + .useEffect(true) + .fontSize(16) + .fontWeight(FontWeight.Medium) + .borderRadius(16) + .width('90%') + .height('48') + + // 使用useEffect进行模糊合并绘制,继承EffectComponent的模糊参数 + Text("Normal text with useeffcet blur 2") + .textAlign(TextAlign.Center) + .useEffect(true) + .fontSize(16) + .fontWeight(FontWeight.Medium) + .borderRadius(16) + .width('90%') + .height('48') + } + .width('100%') + } + .backgroundBlurStyle(BlurStyle.Thin) + } + .backgroundColor(Color.Black) + .width('100%') + .height('100%') + } +} +``` + +![zh-cn_image_effectcomponent](figures/zh-cn_image_effectcomponent.png) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-listitem.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-listitem.md index f8aeeaaf3d6304a3ecf3198b0389bdd887aec835..a5f10e6fa12a7613fa81e627305c991b300ce178 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-listitem.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-listitem.md @@ -15,7 +15,9 @@ 从API version 9开始,该接口支持在ArkTS卡片中使用。 -**方法1:** ListItem(value?: ListItemOptions)10+ +### ListItem10+ + +ListItem(value?: ListItemOptions) **参数:** @@ -23,15 +25,18 @@ | ------ | --------------------------------------------- | ---- | ------------------------------------------------------------ | | value | [ListItemOptions](#listitemoptions10对象说明) | 否 | 为ListItem提供可选参数, 该对象内含有ListItemStyle枚举类型的style参数。 | -**方法2:** ListItem(value?: string)(deprecated) -从API version 10开始, 该接口不再维护,推荐使用方法1。 +### ListItem(deprecated) + +ListItem(value?: string) + +从API version 10开始, 该接口不再维护,推荐使用[ListItem10+](#listitem10)。 **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | | ------ | ----------------------------- | ---- | -------- | -| value | string(deprecated) | 否 | 无 | +| value | string | 否 | 无 | ## 属性 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md index 72eb33eaa2c724fab078873adb3072c39193213a..f5c1d94a838a5e2bf5aa4df12f07025506c503f0 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md @@ -143,6 +143,7 @@ struct SideBarContainerExample { .sideBarWidth(150) .minSideBarWidth(50) .maxSideBarWidth(300) + .minContentWidth(0) .onChange((value: boolean) => { console.info('status:' + value) }) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-swiper.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-swiper.md index 5db42c5d42ca0cb43e5b8f93735110f5f92980c9..82801b12da9249cfe9025e6681ed4d45b4517863 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-swiper.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-swiper.md @@ -46,7 +46,7 @@ Swiper(controller?: SwiperController) | vertical | boolean | 是否为纵向滑动。
默认值:false | | itemSpace | number \| string | 设置子组件与子组件之间间隙。
默认值:0
**说明:**
不支持设置百分比。 | | displayMode | SwiperDisplayMode | 主轴方向上元素排列的模式,优先以displayCount设置的个数显示,displayCount未设置时本属性生效。
默认值:SwiperDisplayMode.Stretch | -| cachedCount8+ | number | 设置预加载子组件个数。
默认值:1
**说明:**
cachedCount只在Swiper使用[LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md)时才生效。 | +| cachedCount8+ | number | 设置预加载子组件个数。
默认值:1 | | disableSwipe8+ | boolean | 禁用组件滑动切换功能。
默认值:false | | curve8+ | [Curve](ts-appendix-enums.md#curve) \| string | 设置Swiper的动画曲线,默认为淡入淡出曲线,常用曲线参考[Curve枚举说明](ts-appendix-enums.md#curve),也可以通过[插值计算](../apis/js-apis-curve.md)模块提供的接口创建自定义的插值曲线对象。
默认值:Curve.Linear | | indicatorStyle(deprecated) | {
left?: [Length](ts-types.md#length),
top?: [Length](ts-types.md#length),
right?: [Length](ts-types.md#length),
bottom?: [Length](ts-types.md#length),
size?: [Length](ts-types.md#length),
mask?: boolean,
color?: [ResourceColor](ts-types.md),
selectedColor?: [ResourceColor](ts-types.md)
} | 设置导航点样式:
\- left: 设置导航点距离Swiper组件左边的距离。
\- top: 设置导航点距离Swiper组件顶部的距离。
\- right: 设置导航点距离Swiper组件右边的距离。
\- bottom: 设置导航点距离Swiper组件底部的距离。
\- size: 设置导航点的直径,不支持设置百分比。默认值:6vp。
\- mask: 设置是否显示导航点蒙层样式。
\- color: 设置导航点的颜色。
\- selectedColor: 设置选中的导航点的颜色。
从API version 8开始支持,从API version 10开始不再维护,建议使用[indicator](#indicator10对象说明)代替。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-tabs.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-tabs.md index f1c4f5d7121cdc140850dcdd5b3d80d7b559275f..93610e839e339d1aff66369dcdea17da4bc15af0 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-tabs.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-tabs.md @@ -20,7 +20,7 @@ Tabs(value?: {barPosition?: BarPosition, index?: number, controller?: [TabsContr | 参数名 | 参数类型 | 必填 | 参数描述 | | ----------- | --------------------------------- | ---- | ---------------------------------------- | -| barPosition | BarPosition | 否 | 设置Tabs的页签位置。
默认值:BarPosition.Start | +| barPosition | [BarPosition](#barposition枚举说明)| 否 | 设置Tabs的页签位置。
默认值:BarPosition.Start | | index | number | 否 | 设置初始页签索引。
默认值:0
**说明:**
设置为小于0的值时按默认值显示。
可选值为[0, TabContent子节点数量-1]。
设置不同值时,默认生效切换动效,可以设置animationDuration为0关闭动画。
从API version 10开始,该参数支持[$$](../../quick-start/arkts-two-way-sync.md)双向绑定变量。 | | controller | [TabsController](#tabscontroller) | 否 | 设置Tabs控制器。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-explicit-animation.md b/zh-cn/application-dev/reference/arkui-ts/ts-explicit-animation.md index eb891e4848d5c25aace39a40ec56b2f0308569bf..eb028cd2f7e0c4bf04089475b8f1fefee0811ef9 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-explicit-animation.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-explicit-animation.md @@ -1,6 +1,6 @@ # 显式动画 -提供全局animateTo显式动画接口来指定由于闭包代码导致的状态变化插入过渡动效。 +提供全局animateTo显式动画接口来指定由于闭包代码导致的状态变化插入过渡动效。同属性动画,布局类改变宽高的动画,内容都是直接到终点状态,例如文字、canvas的内容、linearGradient等,如果要内容跟随宽高变化,可以使用[renderFit](ts-universal_attributes-renderfit.md)属性配置。 > **说明:** > diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md index 2f767586487fdaa987cef85c791a685cbdde4d5a..6495ca1d4259f8b8c6362c685ee1cdd64ca83716 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md @@ -106,7 +106,7 @@ struct CustomDialogUser { }), cancel: this.existApp, autoCancel: true, - alignment: DialogAlignment.Default, + alignment: DialogAlignment.Bottom, offset: { dx: 0, dy: -20 }, gridCount: 4, customStyle: false diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md b/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md index 6fe560c25eaca837892b1c8e88903b09151fc387..5a4f8f6383ccf1d17788291801b5721fb91919c8 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md @@ -193,7 +193,7 @@ let value: number = AppStorage.get('PropA'); // 47 static set<T>(propName: string, newValue: T): boolean -在AppStorage中设置propName对应属性的值。 +在AppStorage中设置propName对应属性的值。如果newValue的值和propName对应属性的值相同,即不需要做赋值操作,状态变量不会通知UI刷新propName对应属性的值。 **参数:** @@ -220,7 +220,8 @@ let res1: boolean = AppStorage.set('PropB', 47) // false static setOrCreate<T>(propName: string, newValue: T): void -propName如果已经在AppStorage中存在,则设置propName对应是属性的值为newValue。如果不存在,则创建propName属性,值为newValue。 +如果propName已经在AppStorage中存在,并且newValue和propName对应属性的值不同,则设置propName对应属性的值为newValue,否则状态变量不会通知UI刷新propName对应属性的值。 +如果propName不存在,则创建propName属性,值为newValue。 **参数:** @@ -534,7 +535,7 @@ let res1: boolean = AppStorage.Set('PropB', 47) // false static SetOrCreate<T>(propName: string, newValue: T): void -propName如果已经在AppStorage中存在,则设置propName对应是属性的值为newValue。如果不存在,则创建propName属性,值为newValue。 +如果propName已经在AppStorage中存在,则设置propName对应是属性的值为newValue。如果不存在,则创建propName属性,值为newValue。 从API version 10开始废弃,推荐使用[setOrCreate10+](#setorcreate10)。 @@ -802,7 +803,7 @@ let value: number = storage.get('PropA'); // 47 set<T>(propName: string, newValue: T): boolean -在LocalStorage中设置propName对应属性的值。 +在LocalStorage中设置propName对应属性的值。如果newValue的值和propName对应属性的值相同,即不需要做赋值操作,状态变量不会通知UI刷新propName对应属性的值。 从API version 9开始,该接口支持在ArkTS卡片中使用。 @@ -831,7 +832,8 @@ let res1: boolean = storage.set('PropB', 47); // false setOrCreate<T>(propName: string, newValue: T): boolean -propName如果已经在LocalStorage中存在,则设置propName对应是属性的值为newValue。如果不存在,则创建propName属性,初始化为newValue。 +如果propName已经在AppStorage中存在,并且newValue和propName对应属性的值不同,则设置propName对应属性的值为newValue,否则状态变量不会通知UI刷新propName对应属性的值。 +如果propName不存在,则创建propName属性,值为newValue。 从API version 9开始,该接口支持在ArkTS卡片中使用。 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-click-effect.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-click-effect.md index ee0065f626e3e91548618f2c602f5a479b191d10..31e254f8fa45296c20eb8f18b03caae211178e0e 100755 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-click-effect.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-click-effect.md @@ -7,20 +7,20 @@ > 从API Version 10开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 -### 属性 +## 属性 | 名称 | 参数类型 | 描述 | | ----------- | ------------------------------------------- | ------------------------------------------------------------ | | clickEffect | [ClickEffect](#clickeffect对象说明) \| null | 设置当前组件点击回弹效果。
**说明:**
可通过undefined或者null取消点击回弹效果。
不建议在组件大小动态变化的场景中使用该功能。
当组件无法触发通用事件时,不支持该属性。 | -### ClickEffect对象说明 +## ClickEffect对象说明 | 名称 | 参数类型 | 必填 | 描述 | | ----- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | | level | [ClickEffectLevel](ts-appendix-enums.md#clickeffectlevel10) | 是 | 设置当前组件点击回弹效果。
**说明:**
level等于undefined或者null时, ClickEffect采用ClickEffectLevel.LIGHT对应的回弹效果, 缩放比参照scale说明。 | | scale | number | 否 | 回弹缩放比例,支持在设置ClickEffectLevel的基础上微调回弹缩放比例。
**说明:**
level等于ClickEffectLevel.LIGHT时,默认值:0.90
level等于ClickEffectLevel.MIDDLE或者ClickEffectLevel.HEAVY时,默认值:0.95
level等于undefined或者null时,level为ClickEffectLevel.LIGHT,默认值:0.90
scale等于undefined或者null时,scale与当前设置的level对应的默认缩放比相同。
| -### 示例 +## 示例 ```ts // xxx.ets diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md index ed24ec2eb887a44704bad164563a909488608ec2..64c7aa75101343582826beeff31f924447ef3a12 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md @@ -11,7 +11,7 @@ | 名称 | 参数说明 | 描述 | | --------------- | ------ | ---------------------------------------- | -| aspectRatio | number | 指定当前组件的宽高比,aspectRatio = width/height。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| aspectRatio | number | 指定当前组件的宽高比,aspectRatio = width/height。
从API version 9开始,该接口支持在ArkTS卡片中使用。
API version 9及以前,默认值为:1.0。
API version 10:无默认值。
**说明:**
该属性在不设置值或者设置非法值时不生效。
例如,Row只设置宽度且没有子组件,aspectRatio不设置值或者设置成负数时,此时Row高度为0。 | | displayPriority | number | 设置当前组件在布局容器中显示的优先级,当父容器空间不足时,低优先级的组件会被隐藏。
小数点后的数字不作优先级区分,即区间为[x, x + 1)内的数字视为相同优先级。例如:1.0与1.9为同一优先级。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
仅在Row/Column/Flex(单行)容器组件中生效。 | ## 示例 @@ -72,10 +72,10 @@ struct AspectRatioExample { ``` **图1** 竖屏显示
-![zh-cn_image_0000001219744205](figures/zh-cn_image_0000001219744205.gif) +![zh-cn_image_0000001219744205](figures/zh-cn_image_0000001219744205.PNG) **图2** 横屏显示
-![zh-cn_image_0000001174264382](figures/zh-cn_image_0000001174264382.gif) +![zh-cn_image_0000001174264382](figures/zh-cn_image_0000001174264382.PNG) ### 示例2 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-use-effect.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-use-effect.md new file mode 100644 index 0000000000000000000000000000000000000000..a46bcbe5a67a0ff77aed5b5eae96c46960bbeb81 --- /dev/null +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-use-effect.md @@ -0,0 +1,19 @@ +# 特效绘制合并 + +用于对背景模糊等特效进行绘制合并。 + +> **说明:** +> +> 从API Version 10开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> +> 该接口为系统接口。 + +## 属性 + +| 名称 | 参数类型 | 参数描述 | +| -------- | -------- | -------- | +| useEffect | bool | 控制组件是否继承EffectComponent组件的特效属性参数,从而合并绘制特效。
useEffect为true时子组件继承EffectComponent组件的特效属性参数。
默认值:false| + +## 示例 + +示例请参考[EffectComponent](ts-container-effectcomponent.md) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal_attributes-renderfit.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal_attributes-renderfit.md new file mode 100644 index 0000000000000000000000000000000000000000..67beb9c7e16c97f4bd476cd7b258ed0ddc1cf838 --- /dev/null +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal_attributes-renderfit.md @@ -0,0 +1,88 @@ +# 组件内容填充方式 + +用于决定在组件的宽高动画过程中,如何将动画最终的组件内容绘制在组件上。 + +> **说明:** +> +> 从API Version 10开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + + +## 属性 + +| 名称 | 参数类型 | 必填 | 描述 | +| -----| ------------------------------------------ | -----| ------------------------------------ | +| renderFit | [RenderFit](#renderfit枚举说明) | 是 | 设置宽高动画过程中的组件内容填充方式。
当不设置renderFit属性时,取默认值RenderFit.TOP_LEFT。 | + +## RenderFit枚举说明 + +| 名称 | 描述 | 示意图 | +| ------- | ------------------------------------ | --------------------------------- | +| CENTER | 保持动画终态的内容大小,并且内容始终与组件保持中心对齐。 | ![renderfit_center](figures/renderfit_center.png) | +| TOP | 保持动画终态的内容大小,并且内容始终与组件保持顶部中心对齐。 | ![renderfit_top](figures/renderfit_top.png) | +| BOTTOM | 保持动画终态的内容大小,并且内容始终与组件保持底部中心对齐。 | ![renderfit_bottom](figures/renderfit_bottom.png) | +| LEFT | 保持动画终态的内容大小,并且内容始终与组件保持左侧对齐。 | ![renderfit_left](figures/renderfit_left.png) | +| RIGHT | 保持动画终态的内容大小,并且内容始终与组件保持右侧对齐。 | ![renderfit_right](figures/renderfit_right.png) | +| TOP_LEFT | 保持动画终态的内容大小,并且内容始终与组件保持左上角对齐。 | ![renderfit_top_left](figures/renderfit_top_left.png) | +| TOP_RIGHT | 保持动画终态的内容大小,并且内容始终与组件保持右上角对齐。 | ![renderfit_top_right](figures/renderfit_top_right.png) | +| BOTTOM_LEFT | 保持动画终态的内容大小,并且内容始终与组件保持左下角对齐。 | ![renderfit_bottom_left](figures/renderfit_bottom_left.png) | +| BOTTOM_RIGHT | 保持动画终态的内容大小,并且内容始终与组件保持右下角对齐。 | ![renderfit_bottom_right](figures/renderfit_bottom_right.png) | +| RESIZE_FILL | 不考虑动画终态内容的宽高比,并且内容始终缩放到组件的大小。 | ![renderfit_resize_fill](figures/renderfit_resize_fill.png) | +| RESIZE_CONTAIN | 保持动画终态内容的宽高比进行缩小或放大,使内容完整显示在组件内,且与组件保持中心对齐。 | ![renderfit_resize_contain](figures/renderfit_resize_contain.png) | +| RESIZE_CONTAIN_TOP_LEFT | 保持动画终态内容的宽高比进行缩小或放大,使内容完整显示在组件内。当组件宽方向有剩余时,内容与组件保持左侧对齐,当组件高方向有剩余时,内容与组件保持顶部对齐。 | ![renderfit_resize_contain_top_left](figures/renderfit_resize_contain_top_left.png) | +| RESIZE_CONTAIN_BOTTOM_RIGHT | 保持动画终态内容的宽高比进行缩小或放大,使内容完整显示在组件内。当组件宽方向有剩余时,内容与组件保持右侧对齐,当组件高方向有剩余时,内容与组件保持底部对齐。 | ![renderfit_resize_contain_bottom_right](figures/renderfit_resize_contain_bottom_right.png) | +| RESIZE_COVER | 保持动画终态内容的宽高比进行缩小或放大,使内容两边都大于或等于组件两边,且与组件保持中心对齐,显示内容的中间部分。 | ![renderfit_resize_cover](figures/renderfit_resize_cover.png) | +| RESIZE_COVER_TOP_LEFT | 保持动画终态内容的宽高比进行缩小或放大,使内容的两边都恰好大于或等于组件两边。当内容宽方向有剩余时,内容与组件保持左侧对齐,显示内容的左侧部分。当内容高方向有剩余时,内容与组件保持顶部对齐,显示内容的顶侧部分。 | ![renderfit_resize_cover_top_left](figures/renderfit_resize_cover_top_left.png) | +| RESIZE_COVER_BOTTOM_RIGHT | 保持动画终态内容的宽高比进行缩小或放大,使内容的两边都恰好大于或等于组件两边。当内容宽方向有剩余时,内容与组件保持右侧对齐,显示内容的右侧部分。当内容高方向有剩余时,内容与组件保持底部对齐,显示内容的底侧部分。| ![renderfit_resize_cover_bottom_right](figures/renderfit_resize_cover_bottom_right.png) | + +> **说明:** +> +> - 示意图中,蓝色区域表示内容,橙黄色区域表示节点大小。 +> - 不同的内容填充方式在宽高动画过程中效果不一致,开发者需要选择合适的内容填充方式以实现需要的动画效果。 + +## 示例 + +```ts +// xxx.ets +@Entry +@Component +struct RenderFitExample { + @State width1: number = 100; + @State height1: number = 30; + flag: boolean = true; + build() { + Column() { + Text("Hello") + .width(this.width1) + .height(this.height1) + .borderWidth(1) + .textAlign(TextAlign.Start) + .renderFit(RenderFit.LEFT) // 设置LEFT的renderFit,动画过程中,动画的终态内容与组件保持左对齐 + .margin(20) + + Text("Hello") + .width(this.width1) + .height(this.height1) + .textAlign(TextAlign.Center) + .borderWidth(1) + .renderFit(RenderFit.CENTER) // 设置CENTER的renderFit,动画过程中,动画的终态内容与组件保持中心对齐 + .margin(20) + + Button("animate") + .onClick(() => { + animateTo({ curve: Curve.Ease }, () => { + if (this.flag) { + this.width1 = 150; + this.height1 = 50; + } else { + this.width1 = 100; + this.height1 = 30; + } + this.flag = !this.flag; + }) + }) + }.width("100%").height("100%").alignItems(HorizontalAlign.Center) + } +} +``` + +![renderfit](figures/renderfit.gif) diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-hiappevent.md b/zh-cn/application-dev/reference/errorcodes/errorcode-hiappevent.md index 1249deef43af46f479ec2ba0ac5d3abcff535066..873cf2073c7c512db9b15da93f06db8f7ec3a2c1 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-hiappevent.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-hiappevent.md @@ -43,7 +43,7 @@ Invalid event domain. - 事件领域名称只包含数字、小写字母、下划线字符。 - 事件领域名称以小写字母开头,不以下划线结尾。 -- 事件领域名称非空且长度不超过32个字符。 +- 事件领域名称非空且长度不超过16个字符。 **处理步骤** @@ -185,7 +185,7 @@ Invalid filtering event domain. - 事件领域名称只包含数字、小写字母、下划线字符。 - 事件领域名称以小写字母开头,不以下划线结尾。 -- 事件领域名称非空且长度不超过32个字符。 +- 事件领域名称非空且长度不超过16个字符。 **处理步骤** diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-net-socket.md b/zh-cn/application-dev/reference/errorcodes/errorcode-net-socket.md index dc037fcff3c611ed6ef72867539d1e3f2aef05df..7f34de7454242c5624d19f8d79ff3a2ff1599806 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-net-socket.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-net-socket.md @@ -159,7 +159,7 @@ Resource temporarily unavailable try again. **错误信息** -Socket operation on non-socket. +Not a socket. **错误描述** @@ -214,7 +214,7 @@ Address already in use. **错误信息** -Cannot assign requested address. +Address not available. **错误描述** diff --git a/zh-cn/application-dev/reference/native-apis/_o_h___rdb___config.md b/zh-cn/application-dev/reference/native-apis/_o_h___rdb___config.md index 008e7380959716b0c4ff0f2da829917e9c11883e..34bcb47f2da72521ec2d9720e0d16cb144560aef 100644 --- a/zh-cn/application-dev/reference/native-apis/_o_h___rdb___config.md +++ b/zh-cn/application-dev/reference/native-apis/_o_h___rdb___config.md @@ -23,6 +23,7 @@ | -------- | -------- | | [selfSize](_r_d_b.md#selfsize) | 该结构体的大小。 | | [dataBaseDir](_r_d_b.md#databasedir) | 数据库文件路径。 | +| [storeName](_r_d_b.md#storename) | 数据库名称。 | | [bundleName](_r_d_b.md#bundlename) | 应用包名。 | | [moduleName](_r_d_b.md#modulename) | 应用模块名。 | | [isEncrypt](_r_d_b.md#isencrypt) | 指定数据库是否加密。 | diff --git a/zh-cn/application-dev/reference/native-apis/_r_d_b.md b/zh-cn/application-dev/reference/native-apis/_r_d_b.md index c1108f5ae184a16910a7ffaa76c17d36713231af..b7cbab6d009d4beb685b50d1aa8f3324ec77b752 100644 --- a/zh-cn/application-dev/reference/native-apis/_r_d_b.md +++ b/zh-cn/application-dev/reference/native-apis/_r_d_b.md @@ -148,6 +148,7 @@ | [OH_VBucket::destroy](#destroy-34) | 销毁[OH_VBucket](_o_h___v_bucket.md)对象,并回收该对象占用的内存。 | | [OH_Rdb_Config::selfSize](#selfsize) | 该结构体的大小。 | | [OH_Rdb_Config::dataBaseDir](#databasedir) | 数据库文件路径。 | +| [OH_Rdb_Config::storeName](#storename) | 数据库名称。 | | [OH_Rdb_Config::bundleName](#bundlename) | 应用包名。 | | [OH_Rdb_Config::moduleName](#modulename) | 应用模块名。 | | [OH_Rdb_Config::isEncrypt](#isencrypt) | 指定数据库是否加密。 | @@ -732,7 +733,7 @@ OH_Cursor* OH_Rdb_Query (OH_Rdb_Store * store, OH_Predicates * predicates, const | store | 表示指向[OH_Rdb_Store](_o_h___rdb___store.md)实例的指针。 | | predicates | 表示指向[OH_Predicates](_o_h___predicates.md)实例的指针,指定查询条件。 | | columnNames | 表示要查询的列。如果值为空,则查询应用于所有列。 | -| length | 表示columnNames数组的长度。 | +| length | 表示columnNames数组的长度。若length大于columnNames数组的实际长度,则会访问越界。 | **返回:** @@ -932,6 +933,15 @@ OH_Predicates*(* OH_Predicates::between) (OH_Predicates *predicates, const char [OH_Predicates](_o_h___predicates.md), [OH_VObject](_o_h___v_object.md). +### storeName + +``` +const char* OH_Rdb_Config::storeName +``` + +**描述:** + +数据库名称。 ### bundleName diff --git a/zh-cn/application-dev/security/accesstoken-guidelines.md b/zh-cn/application-dev/security/accesstoken-guidelines.md index 445fcdeecd2d788663ec8a33c0a970491fe0ea4b..eea99f1d5929f72dbfae11314c3d2c7e8acba030 100644 --- a/zh-cn/application-dev/security/accesstoken-guidelines.md +++ b/zh-cn/application-dev/security/accesstoken-guidelines.md @@ -370,7 +370,7 @@ 通过调用[requestPermissionsFromUser()](../reference/apis/js-apis-inner-app-context.md#contextrequestpermissionsfromuser7)接口向用户动态申请授权。 -```js +```ts import { BusinessError } from '@ohos.base'; import featureAbility from '@ohos.ability.featureAbility'; @@ -378,7 +378,7 @@ reqPermissions() { let context = featureAbility.getContext(); let array:Array = ["ohos.permission.PERMISSION2"]; //requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗 - context.requestPermissionsFromUser(array, 1).then(function(data) { + context.requestPermissionsFromUser(array, 1).then(data => { console.log("data:" + JSON.stringify(data)); console.log("data permissions:" + JSON.stringify(data.permissions)); console.log("data result:" + JSON.stringify(data.authResults)); diff --git a/zh-cn/application-dev/security/permission-verify-guidelines.md b/zh-cn/application-dev/security/permission-verify-guidelines.md index f8645aba530437dfaaf1500fcdfd69306cf57914..fe163636ab1e862b952f9fdb22db13292dd25b9c 100644 --- a/zh-cn/application-dev/security/permission-verify-guidelines.md +++ b/zh-cn/application-dev/security/permission-verify-guidelines.md @@ -27,19 +27,20 @@ checkAccessToken(tokenID: number, permissionName: Permissions): Promise<Grant 3. 使用checkAccessToken接口对当前调用者进行权限校验。 4. 根据权限校验结果采取对应的措施。 -```js +```ts import abilityAccessCtrl from '@ohos.abilityAccessCtrl' + import { BusinessError } from '@ohos.base'; import rpc from '@ohos.rpc' class Stub extends rpc.RemoteObject { - onRemoteRequest(code, data, reply, option) { - let callerTokenId = rpc.IPCSkeleton.getCallingTokenId(); + onRemoteMessageRequest(code: number, data: rpc.MessageSequence, reply: rpc.MessageSequence, option: rpc.MessageOption) { + let callerTokenId: number = rpc.IPCSkeleton.getCallingTokenId(); console.log("RpcServer: getCallingTokenId result: " + callerTokenId); - var atManager = abilityAccessCtrl.createAtManager(); + let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); try { - atManager.checkAccessToken(callerTokenId, "ohos.permission.ACCELEROMETER").then((data) => { + atManager.checkAccessToken(callerTokenId, "ohos.permission.ACCELEROMETER").then((data: abilityAccessCtrl.GrantStatus) => { console.log(`checkAccessToken success, data->${JSON.stringify(data)}`); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log(`checkAccessToken fail, err->${JSON.stringify(err)}`); }); } catch(err) { @@ -48,5 +49,4 @@ checkAccessToken(tokenID: number, permissionName: Permissions): Promise<Grant return true; } } - ``` diff --git a/zh-cn/application-dev/ui/arkts-component-animation.md b/zh-cn/application-dev/ui/arkts-component-animation.md index 831132f9b4f194a7f1ebadce6e4f1d0a2c4ce069..3199691f74ccbd41e766ef6d11ec92e258c8e975 100644 --- a/zh-cn/application-dev/ui/arkts-component-animation.md +++ b/zh-cn/application-dev/ui/arkts-component-animation.md @@ -279,7 +279,7 @@ export struct TaskSwitchMainPage { .translate({ x: this.cardOffset }) .animation({ curve: curves.springMotion() }) .zIndex((this.getProgress(index) >= 0.4 && this.getProgress(index) <= 0.6) ? 2 : 1) - }, item => item) + }, item => item.index) } .width((this.cardWidth + this.cardSpace) * (taskDataArr.length + 1)) .height('100%') diff --git a/zh-cn/application-dev/ui/arkts-graphics-display.md b/zh-cn/application-dev/ui/arkts-graphics-display.md index 0596121209e9d63213c9e02210b0f2a16dd96291..7344be7d89066d70c2bc8361d96440d2d4473688 100644 --- a/zh-cn/application-dev/ui/arkts-graphics-display.md +++ b/zh-cn/application-dev/ui/arkts-graphics-display.md @@ -168,7 +168,8 @@ PixelMap是图片解码后的像素图,具体用法请参考[图片开发指 ```ts let code = data.responseCode; if (ResponseCode.ResponseCode.OK === code) { - let imageSource = image.createImageSource(data.result); + let res: any = data.result + let imageSource = image.createImageSource(res); let options = { alphaType: 0, // 透明度 editable: false, // 是否可编辑 diff --git a/zh-cn/application-dev/ui/arkts-layout-development-create-grid.md b/zh-cn/application-dev/ui/arkts-layout-development-create-grid.md index 32dffaef023bbbd582fc72f56aea06fe3acc3268..2eb07b9dc8c61c45f3de0b1a867c746b7954bc70 100644 --- a/zh-cn/application-dev/ui/arkts-layout-development-create-grid.md +++ b/zh-cn/application-dev/ui/arkts-layout-development-create-grid.md @@ -170,7 +170,7 @@ Grid() { } } .rowsTemplate('1fr 1fr') -.rowsTemplate('1fr 1fr') +.columnsTemplate('1fr 1fr') ``` 对于内容结构相似的多个GridItem,通常更推荐使用ForEach语句中嵌套GridItem的形式,来减少重复代码。 @@ -193,7 +193,7 @@ struct OfficeService { }, service => service) } .rowsTemplate('1fr 1fr') - .rowsTemplate('1fr 1fr') + .columnsTemplate('1fr 1fr') ... } ... diff --git a/zh-cn/application-dev/ui/arkts-popup-and-menu-components-menu.md b/zh-cn/application-dev/ui/arkts-popup-and-menu-components-menu.md index 6a5b06eafebb38c1a229cd741b1c82b3c4201ba4..c51650dcda1b999dc0abc92b48d22493ffe45ac6 100644 --- a/zh-cn/application-dev/ui/arkts-popup-and-menu-components-menu.md +++ b/zh-cn/application-dev/ui/arkts-popup-and-menu-components-menu.md @@ -28,7 +28,7 @@ Button('click for Menu') ## 创建自定义样式的菜单 -当默认样式不满足开发需求时,可使用\@CustomBuilder自定义菜单内容。可通过bindMenu接口进行菜单的自定义。 +当默认样式不满足开发需求时,可使用[\@Builder](../quick-start/arkts-builder.md)自定义菜单内容。可通过bindMenu接口进行菜单的自定义。 ### \@Builder开发菜单内的内容 diff --git a/zh-cn/application-dev/ui/arkts-routing.md b/zh-cn/application-dev/ui/arkts-routing.md index 7decc43dfb49b9687754ba34a15aa8156b48173d..122934119ca423b64ac1ddf7511f8d0afe857606 100644 --- a/zh-cn/application-dev/ui/arkts-routing.md +++ b/zh-cn/application-dev/ui/arkts-routing.md @@ -352,7 +352,7 @@ struct MyComponent { ```ts // entry/src/main/ets/pages/Index.ets import router from '@ohos.router'; -import 'library/src/main/ets/pages/Index.ets' // 引入共享包library中的命名路由页面 +import 'library/src/main/ets/pages/Index' // 引入共享包library中的命名路由页面 @Entry @Component diff --git a/zh-cn/application-dev/website.md b/zh-cn/application-dev/website.md index 28f5929408b531993f9df1fdbb938df6a3348f27..5d1a2926f964ec255afc3b5727a7f714f33fb1b3 100644 --- a/zh-cn/application-dev/website.md +++ b/zh-cn/application-dev/website.md @@ -682,31 +682,7 @@ - [前言](key-features/multi-device-app-dev/foreword.md) - [简介](key-features/multi-device-app-dev/introduction.md) - [从一个例子开始](key-features/multi-device-app-dev/start-with-a-example.md) - - 应用UX设计 - - [设计原则和要点](key-features/multi-device-app-dev/design-principles.md) - - 应用架构设计 - - [应用导航结构设计要求](key-features/multi-device-app-dev/navigation-design.md) - - [应用页面结构设计](key-features/multi-device-app-dev/page-design.md) - - 界面布局 - - [概述](key-features/multi-device-app-dev/interface-layout-design-intro.md) - - 布局基础 - - [栅格系统](key-features/multi-device-app-dev/design-grid.md) - - [自适应布局](key-features/multi-device-app-dev/design-adaptive-layout.md) - - [响应式布局](key-features/multi-device-app-dev/design-responsive-layout.md) - - [布局基础运用案例](key-features/multi-device-app-dev/design-layout-cases.md) - - 人机交互 - - [交互基础](key-features/multi-device-app-dev/interaction-basics.md) - - [常见输入方式](key-features/multi-device-app-dev/common-input-modes.md) - - [交互事件归一](key-features/multi-device-app-dev/design-interaction-event-normalization.md) - - 视觉风格 - - [视觉基础](key-features/multi-device-app-dev/visual-basics.md) - - [色彩](key-features/multi-device-app-dev/visual-style-color.md) - - [字体](key-features/multi-device-app-dev/visual-style-font.md) - - [图标](key-features/multi-device-app-dev/visual-style-icon.md) - - [多态控件](key-features/multi-device-app-dev/design-polymorphic-controls.md) - - [设计自检表](key-features/multi-device-app-dev/design-checklist.md) - - [设计交付](key-features/multi-device-app-dev/design-delivery.md) - - [资源](key-features/multi-device-app-dev/design-resources.md) + - [应用UX设计](key-features/multi-device-app-dev/design-principles.md) - [工程管理](key-features/multi-device-app-dev/ide-using.md) - 页面开发的一多能力介绍 - [简介](key-features/multi-device-app-dev/page-development-intro.md) diff --git a/zh-cn/device-dev/quick-start/quickstart-pkg-prepare.md b/zh-cn/device-dev/quick-start/quickstart-pkg-prepare.md index 62abffed40b0d40ba7c093e1e03302e4cb963a69..d5673e31061c4f4eeb0e432a6f0494a687a2aabb 100644 --- a/zh-cn/device-dev/quick-start/quickstart-pkg-prepare.md +++ b/zh-cn/device-dev/quick-start/quickstart-pkg-prepare.md @@ -20,7 +20,7 @@ ## Ubuntu环境要求 -- Ubuntu18.04及以上版本,内存推荐16 GB及以上。 +- Ubuntu18.04及以上版本,X86_64架构,内存推荐16 GB及以上。 - Ubuntu系统的用户名不能包含中文字符。 diff --git a/zh-cn/device-dev/security/security-privacy-protection.md b/zh-cn/device-dev/security/security-privacy-protection.md index 1bea6df05d9ce614b45f68460058d40e469dc490..67e8b1893f7096843b4a76d02929ff1881d4ab96 100644 --- a/zh-cn/device-dev/security/security-privacy-protection.md +++ b/zh-cn/device-dev/security/security-privacy-protection.md @@ -123,7 +123,7 @@ - 禁止在日志中打印敏感个人数据,如需要打印一般个人数据时,应对个人数据进行匿名化或假名化处理; - 优先使用可以重置的标识符,如系统提供了NetworkID和DVID作为分布式场景下的设备标识符,广告业务场景下则建议使用OAID,基于应用的分析则建议使用ODID和AAID,其他需要唯一标识符的场景可以使用UUID接口生成;可重置的标识符不能满足业务需求时,才选择序列号和MAC地址等永久性标识符。 + 优先使用可以重置的标识符,如系统提供了NetworkID和DVID作为分布式场景下的设备标识符,其他需要唯一标识符的场景可以使用UUID接口生成;可重置的标识符不能满足业务需求时,才选择序列号和MAC地址等永久性标识符。 **数据处理选择和控制** diff --git a/zh-cn/website.md b/zh-cn/website.md index 9be2af42710e5cf67bd5bedbb9c3584a9495333e..bb8c1b405fc4f1f534cf4523be38bcf5ecf70aeb 100644 --- a/zh-cn/website.md +++ b/zh-cn/website.md @@ -75,7 +75,7 @@ - [总览](release-notes/changelogs/v4.0-beta2/Readme-CN.md) - [ArkUI Changelog](release-notes/changelogs/v4.0-beta2/changelogs-arkui.md) - [包管理Changelog](release-notes/changelogs/v4.0-beta2/changelogs-bundlemanager.md) - - [程序访问控制Changelog](release-notes/changelogs/v4.0-beta2/changelogs-accesstoken.md) + - [程序访问控制Changelog](release-notes/changelogs/v4.0-beta2/changelogs-accessToken.md) - [分布式数据管理Changelog](release-notes/changelogs/v4.0-beta2/changelogs-distributeddatamgr.md) - [元能力-卡片框架Changelog](release-notes/changelogs/v4.0-beta2/changelogs-formfwk.md) - [输入法框架Changelog](release-notes/changelogs/v4.0-beta2/changelogs-imf.md)